Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
The First Flight of TurboFieldfare
Andrey Mikhaylov6b9070f6b0cd
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 00000000..579108fe--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,17 @@+name: CI++on:+ push:+ pull_request:++jobs:+ test:+ runs-on: macos-26+ steps:+ - uses: actions/checkout@v4+ - name: Build release products+ run: swift build -c release+ - name: Run serial tests+ run: Scripts/test.sh+ - name: Check Markdown links+ run: ruby Scripts/check_markdown_links.rbdiff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..6d12f045--- /dev/null+++ b/.gitignore@@ -0,0 +1,50 @@+# Swift Package Manager+.build/+.swiftpm/+*.xcodeproj+*.xcworkspace++# Xcode+DerivedData/+xcuserdata/+*.xcuserstate+*.xcscheme++# macOS+.DS_Store++# Build artifacts+*.o+*.a+*.dylib+*.metallib++# Model weights / large blobs+*.safetensors+*.gguf+*.bin+*.npz+weights/+models/+Model/+!Tests/**/Model/+# Repacked .gturbo directories (manifest.json/layout.json inside aren't caught by *.bin)+*.gturbo/++# Editor+.vscode/+.idea/+*.swp+*~++# Logs / scratch+*.log+benchmark-results/+scratch/+tmp/++# Python+__pycache__/+*.pyc+.venv/diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 00000000..d053ba58--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,40 @@+# TurboFieldfare++Swift and Metal inference for Gemma 4 26B-A4B on Apple Silicon.++## Scope++This checkout is for running and reporting existing behavior. Do not edit source, change runtime defaults, or start optimization work unless the user asks.++## Layout and commands++`Sources/TurboFieldfare/` is the runtime; `Sources/TurboFieldfareRepack/`, `Sources/TurboFieldfareCLI/`, and `Sources/TurboFieldfareApp/` contain the installer, CLI, and Mac app.+`Tests/` contains focused public tests; `docs/` contains design, benchmark, and experiment notes.++```bash+swift run -c release TurboFieldfareRepack --output scratch/gemma4.gturbo+swift build -c release+.build/release/TurboFieldfareMac+swift run -c release TurboFieldfareCLI \+ --model scratch/gemma4.gturbo \+ --prompt "The capital of France is" \+ --max-new 64+```++The installer streams the pinned model without staging the full source checkpoint. Set `HF_TOKEN` only if requested. The download is about 15 GB.++## Test rules++Before a model run, require macOS 26+, Swift 6.2+, enough disk, acceptable `memory_pressure -Q`, a completed `scratch/gemma4.gturbo`, and no process from `pgrep -fl 'TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'`. If a check fails, inform the user and stop; do not terminate apps or delete or reinstall the model.++Run package tests through `Scripts/test.sh`. Run only one app, CLI, or model-using test at a time.++For performance results, build release once and follow the [community benchmark guide](docs/COMMUNITY_BENCHMARKS.md) exactly. Do not enable experimental controls or profiling.++Do not download a full checkpoint, duplicate the `.gturbo` model, create a worktree, or purge caches just to run tests.++Report the commit, hardware and RAM, macOS, Swift version, exact command, exit code, complete timing footer or error, and every protocol deviation. Treat results as measurements, not performance ceilings.++## App controls++The Mac app exposes generation controls plus cache slots, LFU/LRU, prefill, FP16 or K4/V4 KV, RDADVISE, and verification. Interactive generation defaults to 1,024 new tokens, temperature 0.1, Top-K 64, Top-P 0.95, and repetition penalty off at 1.0. Start with production defaults. The HUD reports rate, tokens, and decode-service memory; Last run adds TTFT and I/O. The app must be built with its sibling `TurboFieldfareDecodeService`; it never falls back to loading a second in-process model. See [README](README.md) and [Runtime controls](docs/RUNTIME_CONTROLS.md).diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 00000000..ec081fc5--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,37 @@+# Contributing++TurboFieldfare welcomes focused fixes, documentation improvements, and+benchmark reports from Apple Silicon Macs.++## Before opening a change++- Keep the package compatible with macOS 26, Swift 6.2, and Metal 4.+- Preserve the bounded-memory model path. Never load a complete checkpoint,+ shard, or large model tensor into Swift heap memory.+- Keep public runtime controls limited to those documented in+ [Runtime controls](docs/RUNTIME_CONTROLS.md).+- Add or update a focused test for behavior changes.++Run the release build, serial tests, and Markdown link check:++```bash+swift build -c release+Scripts/test.sh+ruby Scripts/check_markdown_links.rb+```++These checks do not download or load the model. For a real-model change, also+report the prompt, generated token count, output, timing footer, Mac model,+memory, macOS version, Swift version, and any protocol change.++## Benchmark reports++Follow the [community benchmark protocol](docs/COMMUNITY_BENCHMARKS.md). Review+all captured files before sharing them, and remove personal paths or unrelated+process details.++## Pull requests++Keep each pull request narrow. Explain the behavior change, tests run, and any+remaining limitation. By contributing, you agree that your work is licensed+under the repository's [Apache License 2.0](LICENSE).diff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..261eeb9e--- /dev/null+++ b/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/Package.resolved b/Package.resolvednew file mode 100644index 00000000..29567267--- /dev/null+++ b/Package.resolved@@ -0,0 +1,105 @@+{+ "originHash" : "fcd8c6c7b3bdc1b2987889f5525974610779e7fe094361a13b5cd2b27afa046b",+ "pins" : [+ {+ "identity" : "eventsource",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/mattt/EventSource.git",+ "state" : {+ "revision" : "a3a85a85214caf642abaa96ae664e4c772a59f6e",+ "version" : "1.4.1"+ }+ },+ {+ "identity" : "swift-asn1",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-asn1.git",+ "state" : {+ "revision" : "eb50cbd14606a9161cbc5d452f18797c90ef0bab",+ "version" : "1.7.0"+ }+ },+ {+ "identity" : "swift-atomics",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-atomics.git",+ "state" : {+ "revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7",+ "version" : "1.3.0"+ }+ },+ {+ "identity" : "swift-collections",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-collections.git",+ "state" : {+ "revision" : "fea17c02d767f46b23070fdfdacc28a03a39232a",+ "version" : "1.5.1"+ }+ },+ {+ "identity" : "swift-crypto",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-crypto.git",+ "state" : {+ "revision" : "1b6b2e274e85105bfa155183145a1dcfd63331f1",+ "version" : "4.5.0"+ }+ },+ {+ "identity" : "swift-huggingface",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/huggingface/swift-huggingface.git",+ "state" : {+ "revision" : "b721959445b617d0bf03910b2b4aced345fd93bf",+ "version" : "0.9.0"+ }+ },+ {+ "identity" : "swift-jinja",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/huggingface/swift-jinja.git",+ "state" : {+ "revision" : "0b67ecb79139f6addef8699eff3622808aa6c7dc",+ "version" : "2.3.6"+ }+ },+ {+ "identity" : "swift-nio",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-nio.git",+ "state" : {+ "revision" : "f71c8d2a5e74a2c6d11a0fbe324774b5d6084237",+ "version" : "2.99.0"+ }+ },+ {+ "identity" : "swift-system",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-system.git",+ "state" : {+ "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df",+ "version" : "1.6.4"+ }+ },+ {+ "identity" : "swift-transformers",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/huggingface/swift-transformers",+ "state" : {+ "revision" : "2fa33e1f5e7131a7fc64c28e6d161dcec0d24820",+ "version" : "1.3.3"+ }+ },+ {+ "identity" : "yyjson",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/ibireme/yyjson.git",+ "state" : {+ "revision" : "8b4a38dc994a110abaec8a400615567bd996105f",+ "version" : "0.12.0"+ }+ }+ ],+ "version" : 3+}diff --git a/Package.swift b/Package.swiftnew file mode 100644index 00000000..3aadd7e2--- /dev/null+++ b/Package.swift@@ -0,0 +1,94 @@+// swift-tools-version: 6.2+import PackageDescription++let package = Package(+ name: "TurboFieldfare",+ platforms: [+ .macOS(.v26),+ .iOS(.v26),+ ],+ products: [+ .library(name: "TurboFieldfare", targets: ["TurboFieldfare"]),+ .executable(name: "TurboFieldfareRepack", targets: ["TurboFieldfareRepack"]),+ .executable(name: "TurboFieldfareCLI", targets: ["TurboFieldfareCLI"]),+ .executable(name: "TurboFieldfareMac", targets: ["TurboFieldfareMac"]),+ .executable(name: "TurboFieldfareDecodeService", targets: ["TurboFieldfareDecodeService"]),+ ],+ dependencies: [+ .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),+ ],+ targets: [+ .target(+ name: "TurboFieldfare",+ dependencies: [+ .product(name: "Tokenizers", package: "swift-transformers"),+ ],+ path: "Sources/TurboFieldfare",+ resources: [+ .copy("Metal"),+ ]+ ),+ .target(+ name: "TurboFieldfareRepackCore",+ path: "Sources/TurboFieldfareRepack/Core"+ ),+ .executableTarget(+ name: "TurboFieldfareRepack",+ dependencies: ["TurboFieldfareRepackCore"],+ path: "Sources/TurboFieldfareRepack/Command"+ ),+ .target(+ name: "TurboFieldfareCLICore",+ dependencies: ["TurboFieldfare"],+ path: "Sources/TurboFieldfareCLI",+ exclude: ["Command"]+ ),+ .executableTarget(+ name: "TurboFieldfareCLI",+ dependencies: ["TurboFieldfareCLICore"],+ path: "Sources/TurboFieldfareCLI/Command"+ ),+ .target(+ name: "TurboFieldfareAppCore",+ dependencies: ["TurboFieldfare", "TurboFieldfareRepackCore", "TurboFieldfareDecodeProtocol"],+ path: "Sources/TurboFieldfareApp/Core"+ ),+ .target(+ name: "TurboFieldfareDecodeProtocol",+ path: "Sources/TurboFieldfareDecodeProtocol"+ ),+ .executableTarget(+ name: "TurboFieldfareDecodeService",+ dependencies: ["TurboFieldfareAppCore", "TurboFieldfareDecodeProtocol"],+ path: "Sources/TurboFieldfareDecodeService"+ ),+ .executableTarget(+ name: "TurboFieldfareMac",+ dependencies: ["TurboFieldfareAppCore"],+ path: "Sources/TurboFieldfareApp/Mac",+ resources: [+ .copy("Resources/turbofieldfare-app-icon.png"),+ ]+ ),+ .target(+ name: "TurboFieldfareValidationSupport",+ dependencies: ["TurboFieldfare"],+ path: "Sources/TurboFieldfareValidation/Support"+ ),+ .testTarget(+ name: "TurboFieldfareTestsCore",+ dependencies: ["TurboFieldfare", "TurboFieldfareValidationSupport", "TurboFieldfareRepackCore", "TurboFieldfareCLICore"],+ path: "Tests/TurboFieldfare/Core"+ ),+ .testTarget(+ name: "TurboFieldfareRepackTests",+ dependencies: ["TurboFieldfareRepackCore"],+ path: "Tests/TurboFieldfareRepack/Core"+ ),+ .testTarget(+ name: "TurboFieldfareAppCoreTests",+ dependencies: ["TurboFieldfareAppCore", "TurboFieldfare", "TurboFieldfareRepackCore", "TurboFieldfareDecodeProtocol"],+ path: "Tests/TurboFieldfareApp/Core"+ ),+ ]+)diff --git a/README.md b/README.mdnew file mode 100644index 00000000..b8ecbfcc--- /dev/null+++ b/README.md@@ -0,0 +1,341 @@+<p align="center">+ <img src="docs/assets/turbofieldfare-logo-rounded.png" alt="TurboFieldfare logo: a fieldfare inside a segmented cache ring" width="280">+</p>++<h1 align="center">TurboFieldfare</h1>++<p align="center">+ <strong>Gemma 4 26B-A4B inference in about 2 GB of RAM</strong><br>+ A custom Swift + Metal runtime for Apple Silicon Macs, even the 8 GB ones.+</p>++<p align="center">+ <img alt="Swift 6.2" src="https://img.shields.io/badge/Swift-6.2-F05138?logo=swift&logoColor=white">+ <img alt="Metal 4" src="https://img.shields.io/badge/Metal-4-5E5CE6">+ <img alt="macOS 26 or later" src="https://img.shields.io/badge/macOS-26%2B-000000?logo=apple&logoColor=white">+ <a href="LICENSE"><img alt="Apache 2.0 license" src="https://img.shields.io/badge/License-Apache%202.0-2ea44f"></a>+</p>++<p align="center">+ <a href="#try-it">Quick start</a> ·+ <a href="docs/BENCHMARKS.md">Benchmarks</a> ·+ <a href="docs/COMMUNITY_BENCHMARKS.md">Contribute results</a> ·+ <a href="docs/SYSTEM_DESIGN.md">How it works</a> ·+ <a href="docs/OPTIMIZATION_JOURNEY.md">Experiments</a> ·+ <a href="docs/IMPLEMENTATION_REFERENCES.md">References</a>+</p>++++Memory got expensive. So I gave a 26-billion-parameter model a ~2 GB budget.++TurboFieldfare runs **[Gemma 4 26B-A4B](https://ai.google.dev/gemma/docs/core/model_card_4)** on Apple Silicon by keeping the common+weights, working buffers, and a 4K-context KV cache in unified memory. The+routed-expert pool stays on SSD and is read on demand.++Even at 4 bits, the text-only model occupies about 14.5 GB. Keeping the complete+checkpoint resident on the target 8 GB M2 MacBook Air would exceed physical+memory before allocating the KV cache.++Gemma's mixture-of-experts layers create an opening: each layer has 128 routed+experts, but each token uses only 8. TurboFieldfare keeps the 1.58 GB common+core in unified memory and reads only the experts selected for the current+layer.++The runtime, streaming installer, CLI, and native Mac app are written in Swift+and Metal. TurboFieldfare is model-specific rather than a wrapper around MLX or+llama.cpp. The curated [experiment record](docs/experiments/EXPERIMENT_INVENTORY.md)+summarizes 102 measured results across kernels, caching, I/O, prefill, and+decode.++## Try it++```bash+git clone https://github.com/drumih/turbo-fieldfare.git+cd turbo-fieldfare+swift build -c release+.build/release/TurboFieldfareMac+```++On the first run, Swift Package Manager downloads and builds the Swift packages+required by the tokenizer. The complete release build includes the foreground+Mac app and its sibling decode-service executable.++When the app opens, choose **Install** and let TurboFieldfare fetch and repack+the pinned model (about 15 GB). Once it is ready, choose **Load Model**, type+your prompt, and press **Generate**.++## At a glance++| Metric | Value |+| --------------- | ------------------------------------------------------------------------------------------------------------------------ |+| Model | Gemma 4 26B-A4B, 26B total parameters, ~3.88B active per token |+| Weights | MLX affine 4-bit, group 64, with 8-bit router and shared-expert overrides |+| Memory | ~1.9 GB common model, KV, and scratch allocation at 4K; expert-slot and file-cache residency varies with use |+| Storage | ~14.5 GB text-only `.gturbo` model installation |+| Hardware | Apple Silicon Mac; validated on an 8 GB M2 MacBook Air |+| Platform | macOS 26, Metal 4, Swift 6.2 |+| M2 measured decode | [5.1-6.3 tok/s](docs/BENCHMARKS.md#m2-measured-decode) on an 8 GB M2 MacBook Air |+| M5 measured decode | [32.0-36.1 tok/s](docs/BENCHMARKS.md#m5-measured-decode) on a 24 GB M5 Pro |++The measured result is a reference point, not a performance ceiling. Prompt+length, generated length, page-cache state, and hardware all affect throughput.+To help measure another Apple Silicon Mac, follow the+[community benchmark guide](docs/COMMUNITY_BENCHMARKS.md).++## Using TurboFieldfare++TurboFieldfare provides a native Mac app and a command-line interface. Both+use the same `.gturbo` model directory. Start with the Mac app; use the CLI for+scripts, reproducible runs, and direct control over generation settings.++The Swift package exposes five products:++| Product | Purpose |+| --- | --- |+| `TurboFieldfare` | Swift library containing the runtime and Metal kernels |+| `TurboFieldfareMac` | Native Mac app for installation and generation |+| `TurboFieldfareDecodeService` | One-shot local model and Metal owner used by the Mac app |+| `TurboFieldfareCLI` | Command-line text completion |+| `TurboFieldfareRepack` | Streaming model installer and install verifier |++### Requirements++- An Apple Silicon Mac; the validated target is an 8 GB M2 MacBook Air+- macOS 26 with Metal 4+- Xcode 26 and Swift 6.2 or newer+- Enough free storage for the ~14.5 GB model installation+- An internet connection for the first model install++The package is arm64-only. Older macOS and Metal versions are not supported.++### Prompting the model++> [!IMPORTANT]+> TurboFieldfare performs **text completion**, not instruction following.+> The Mac app and CLI pass prompts directly to the base model without an+> instruction or chat template. Write text you want continued, such as `The+> capital of France is` or `Q: Why is the sky blue?\nA:`.++The interactive default generates up to 1,024 new tokens with temperature+`0.1`, Top-K `64`, and Top-P `0.95`. The repetition penalty is off (`1.0`).+Temperature `0` selects deterministic greedy decoding. The model may still+repeat, loop, or produce incorrect text, so review its continuation.++For help writing effective prompts, see Google’s [Gemma prompt guide](https://ai.google.dev/gemma/docs/capabilities/text/basic).+TurboFieldfare handles model tokenization, so enter only the prompt text rather than Gemma’s control tokens.++### Mac app++Clone the repository, then run the app from its root:++```bash+swift build -c release+.build/release/TurboFieldfareMac+```++Build the complete package so the app and its sibling decode service are both+available. When launched from this checkout, the app stores the model in+`scratch/gemma4.gturbo`.++#### Install the model++On first launch, the app checks the available storage and shows the download+and installed sizes. Choose **Install** to begin.++The installer never materializes the full source checkpoint. It streams the+required byte ranges from the pinned Hugging Face revision and repacks them+directly into the `.gturbo` layout as they arrive. This avoids a second full+checkpoint on disk and keeps scratch memory bounded.++The first installation transfers about 15 GB through bounded Hugging Face+range requests. Network speed and Hugging Face response times vary, so it can+take a while. The completed `.gturbo` installation occupies about 14.5 GB and+is accepted only after its manifest and file hashes have been validated.+Installation does not load the model into memory.++#### Load and generate++After installation:++1. Choose **Load Model**.+2. Enter a prompt in the composer.+3. Choose **Generate**, or press <kbd>Command</kbd>+<kbd>Return</kbd>.+4. Use the stop button or <kbd>Escape</kbd> to end generation early.++The status bar reports the current phase, generated tokens, decode rate, and+decode-service memory use. The fixed right settings pane controls sampling,+context length, the expert cache, and runtime options. Settings that affect the+loaded runtime require a reload before the next generation. During chunked+prefill, the app reports exact progress such as `Prefill (128/514)`. See+[Runtime controls](docs/RUNTIME_CONTROLS.md) for the allowed values, defaults,+and result metrics.++### Command-line interface++The CLI uses an existing `.gturbo` installation. If you installed the model+through the Mac app, it is already available at `scratch/gemma4.gturbo`.+Otherwise, install it from the command line:++```bash+swift run -c release TurboFieldfareRepack \+ --output scratch/gemma4.gturbo \+ --overwrite+```++The runtime accepts only a completed `.gturbo` directory with a final+`manifest.json`.++Verify an existing installation without loading the model:++```bash+swift run -c release TurboFieldfareRepack \+ --verify-install \+ --input-gturbo scratch/gemma4.gturbo+```++#### Raw completion++`--prompt` passes text directly to the model without applying a chat template:++```bash+swift run -c release TurboFieldfareCLI \+ --model scratch/gemma4.gturbo \+ --prompt "The capital of France is" \+ --max-new 64 \+ --temperature 0+```++This example deliberately requests a short greedy completion. Omitting its+generation overrides uses the same interactive defaults as the Mac app.++Common generation options include `--max-context`, `--temperature`, `--top-k`,+`--top-p`, `--repetition-penalty`, `--seed`, and repeatable `--stop` strings.+The public CLI uses production runtime defaults. Run the following command for+the complete option list:++```bash+swift run -c release TurboFieldfareCLI --help+```++Generated text goes to standard output. Timing statistics go to standard error;+add `--quiet` to suppress that footer in scripts.++## Test and contribute++Run the public test suite serially:++```bash+Scripts/test.sh+```++Before starting a model run, close memory-heavy apps and check+`memory_pressure -Q`. If it reports little free memory, postpone the run. Run+only one TurboFieldfare or local-model process at a time.++To contribute a comparable performance result, follow the+[community benchmark guide](docs/COMMUNITY_BENCHMARKS.md).++## How the inference engine works++At each transformer layer, Metal computes attention and the router from+resident weights. The CPU uses the router's top-8 expert IDs to plan against+the layer's 16-slot LFU cache, then fills misses with bounded parallel `pread`+calls into Metal-visible buffers. Metal computes the resident shared-expert+branch while those reads run, then combines the shared and routed outputs.++Prompt prefill uses chunks of up to 128 tokens so one fetched expert can serve+multiple rows. Generation repeats the routed layer loop one token at a time.+The installer applies the same bounded-memory rule: it repacks remote ranges+directly into `.gturbo` without staging a full shard or tensor.++For a visual introduction to the model architecture, see Maarten Grootendorst's+[A Visual Guide to Gemma 4](https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-gemma-4).++[System design](docs/SYSTEM_DESIGN.md) explains the `.gturbo` layout, memory+ownership, prefill, router handoff, `cb1`/`io`/`cb2` phases, Metal kernels, and+correctness invariants.++## Status and scope++TurboFieldfare currently includes:++- Remote streaming repack into the `.gturbo` model format+- 4-bit MLX affine weights with 8-bit router and shared-expert overrides+- Custom Metal kernels for quantized GEMV, attention, MoE, normalization,+ RoPE, sampling, and production fusions+- SSD-backed routed-expert streaming with a bounded expert cache+- Chunked single-prompt prefill and token-by-token generation with a production+ FP16 KV ring through 4K+- A Swift library, streaming installer, command-line interface, and native+ SwiftUI/AppKit Mac app with a one-shot local decode service++Current scope is text-only inference from the pinned Gemma 4 26B-A4B+checkpoint on Apple Silicon Macs. The 8 GB M2 MacBook Air is the deployment+and compatibility reference; the 24 GB M5 Pro is the current performance host.++The Mac app exposes the experimental packed K4/V4 KV path as an explicit+control. It is not the default because it failed the full quality gate.++### Future work++- Build iPhone and iPad apps, then measure inference speed and memory use on+ mobile hardware.+- Benchmark more Apple Silicon Macs, especially the base 16 GB M4 Mac mini and+ other 8 GB models.++## Experiments and technical documentation++The [experiments that shaped TurboFieldfare](docs/OPTIMIZATION_JOURNEY.md)+explain the largest wins, the plausible ideas that failed, and the early+results that reversed under stronger validation. The detailed+[experiment record](docs/experiments/EXPERIMENT_INVENTORY.md) keeps all 102 audited entries+as optional evidence; neither document requires the private benchmark archive.++Useful entry points:++- [System design](docs/SYSTEM_DESIGN.md)+- [Benchmarks](docs/BENCHMARKS.md)+- [The experiments that shaped TurboFieldfare](docs/OPTIMIZATION_JOURNEY.md)+- [Experiment inventory and summaries](docs/experiments/EXPERIMENT_INVENTORY.md)+- [Implementation references](docs/IMPLEMENTATION_REFERENCES.md)++## License and model terms++TurboFieldfare's source and documentation are licensed under the+[Apache License 2.0](LICENSE).++Model weights are not included. The installer downloads them separately from+the pinned Hugging Face checkpoint, and the weights remain governed by their+source terms. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for the model+and Swift package license review.++TurboFieldfare is an independent research project. It is not affiliated with,+sponsored by, or endorsed by Google.++## Afterword and the project name++Thanks for checking out this project!++My name is Andrey Mikhaylov. You can find me on+[LinkedIn](https://www.linkedin.com/in/andrey-mikhaylov-ios-dev/).+I am the author of TurboFieldfare and an iOS and Metal engineer. Most of my+work is with images, video, and on-device AI.++I dedicate this project to my wife, Sasha, the most supportive person I know.+She stands by me even through the hardest times. She loves wildlife, goes+birdwatching, and volunteers with our local birding community. Because of her,+I have also grown closer to birds and nature.++TurboFieldfare is named after the fieldfare, a member of the thrush family and+my favourite bird. It is not the most noticeable or brightly coloured bird, but+it definitely has a character and unique features of its own. I think the same+is true of this project: it may not be the most practical, but I built it with+my favourite tools, especially Metal, in my favourite field, on-device ML+inference. It definitely has its own character and unique features.++Next time you are outside, touch the grass and listen to the birds. Sometimes+it is the most beautiful thing you can do. And if you can, support your local+wildlife community. They do important work.++Thank you!diff --git a/Scripts/check_markdown_links.rb b/Scripts/check_markdown_links.rbnew file mode 100644index 00000000..4bd4f8e3--- /dev/null+++ b/Scripts/check_markdown_links.rb@@ -0,0 +1,111 @@+#!/usr/bin/env ruby++require "pathname"+require "set"+require "uri"++ROOT = Pathname.new(File.expand_path("..", __dir__))++def markdown_files(arguments)+ return arguments.map { |path| ROOT.join(path).cleanpath } unless arguments.empty?++ root_files = Dir[ROOT.join("*.md").to_s].map { |path| Pathname.new(path) }+ docs_files = Dir[ROOT.join("docs/**/*.md").to_s].map { |path| Pathname.new(path) }+ (root_files + docs_files).select(&:file?).uniq.sort+end++def without_inline_code(line)+ line.gsub(/`+[^`]*`+/, "")+end++def github_heading_slug(heading)+ heading+ .gsub(/<[^>]*>/, "")+ .gsub(/!\[([^\]]*)\]\([^)]+\)/, "\\1")+ .gsub(/\[([^\]]+)\]\([^)]+\)/, "\\1")+ .gsub(/[`*_~]/, "")+ .downcase+ .gsub(/[^\p{L}\p{N}\s_-]/u, "")+ .strip+ .gsub(/\s+/, "-")+end++def anchors_for(path)+ anchors = Set.new+ slug_counts = Hash.new(0)+ in_fence = false++ path.each_line do |line|+ if line.lstrip.start_with?("```")+ in_fence = !in_fence+ next+ end+ next if in_fence++ line.scan(/\bid=["']([^"']+)["']/i).flatten.each { |id| anchors << id }++ match = line.match(/\A {0,3}\#{1,6}\s+(.+?)\s*\#*\s*\z/)+ next unless match++ base = github_heading_slug(match[1])+ next if base.empty?++ occurrence = slug_counts[base]+ anchors << (occurrence.zero? ? base : "#{base}-#{occurrence}")+ slug_counts[base] += 1+ end++ anchors+end++def local_targets(line)+ markdown = without_inline_code(line)+ .scan(/\[[^\]]*\]\((<[^>]+>|[^)\s]+)(?:\s+["'][^"']*["'])?\)/)+ .flatten+ html = line.scan(/<(?:a|img)\b[^>]*\b(?:href|src)=["']([^"']+)["']/i).flatten+ markdown + html+end++missing = []+files = markdown_files(ARGV)+anchor_cache = {}++files.each do |source|+ in_fence = false+ source.each_line.with_index(1) do |line, line_number|+ if line.lstrip.start_with?("```")+ in_fence = !in_fence+ next+ end+ next if in_fence++ local_targets(line).each do |raw_target|+ target = raw_target.delete_prefix("<").delete_suffix(">")+ next if target.empty?+ next if target.match?(%r{\A(?:https?:|mailto:|data:)})++ path, fragment = target.split("#", 2)+ resolved = path.empty? ? source : source.dirname.join(path).cleanpath+ unless resolved.exist?+ missing << "#{source.relative_path_from(ROOT)}:#{line_number} -> #{raw_target}"+ next+ end++ next if fragment.nil? || fragment.empty? || resolved.extname.downcase != ".md"++ anchor = URI::DEFAULT_PARSER.unescape(fragment)+ anchor_cache[resolved] ||= anchors_for(resolved)+ unless anchor_cache[resolved].include?(anchor)+ missing << "#{source.relative_path_from(ROOT)}:#{line_number} -> #{raw_target} (missing anchor)"+ end+ end+ end+end++if missing.empty?+ puts "checked #{files.count} Markdown files; all local links and anchors resolve"+ exit 0+end++warn missing.join("\n")+exit 1diff --git a/Scripts/test.sh b/Scripts/test.shnew file mode 100755index 00000000..747c0486--- /dev/null+++ b/Scripts/test.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Serial test runner. Shared Metal state makes in-process parallel tests+# unreliable. Pass any extra arguments through, for example --filter.++if [[ "${1:-}" == "--package-path" ]]; then+ shift 2+fi++script_directory="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"+cd "$script_directory/.."+exec swift test --no-parallel "$@"diff --git a/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swiftnew file mode 100644index 00000000..117a0b71--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift@@ -0,0 +1,208 @@+import Foundation+import Metal++enum MetalError: Error, CustomStringConvertible {+ case noDevice+ case noQueue+ case missingShaderResource(String)+ case missingFunction(String)+ case libraryCompileFailed(String)++ public var description: String {+ switch self {+ case .noDevice: return "No Metal device"+ case .noQueue: return "Failed to create Metal command queue"+ case .missingShaderResource(let n): return "Shader resource missing: \(n)"+ case .missingFunction(let n): return "Metal function missing in library: \(n)"+ case .libraryCompileFailed(let s):return "Metal library compile failed: \(s)"+ }+ }+}++public struct MetalFunctionConstant: Hashable, Sendable {+ public enum Value: Hashable, Sendable {+ case bool(Bool)+ case uint32(UInt32)+ case float(Float)+ }++ public let index: Int+ public let value: Value++ public init(index: Int, value: Value) {+ self.index = index+ self.value = value+ }+}++/// Single owner of the `MTLDevice`, queue, and the runtime-compiled shader library.+/// On Mac and iOS we ship `.metal` source files as bundle resources and compile+/// them into one combined `MTLLibrary` at startup. This keeps the dev loop+/// fast — edit a shader, rebuild the Swift target, no Xcode metallib step.+/// `@unchecked Sendable`: device/queue/library are immutable and Metal objects+/// are thread-safe for encoding; the pipeline cache is the only mutable state+/// and is lock-guarded.+public final class MetalContext: @unchecked Sendable {+ public let device: MTLDevice+ public let queue: MTLCommandQueue+ public let library: MTLLibrary++ private struct PipelineCacheKey: Hashable {+ var name: String+ var constants: [MetalFunctionConstant]+ var maxTotalThreadsPerThreadgroup: Int?+ }++ private var pipelineCache: [PipelineCacheKey: MTLComputePipelineState] = [:]+ private let pipelineCacheLock = NSLock()++ public init() throws {+ guard let dev = MTLCreateSystemDefaultDevice() else { throw MetalError.noDevice }+ guard let q = dev.makeCommandQueue() else { throw MetalError.noQueue }+ self.device = dev+ self.queue = q+ self.library = try Self.compileShaderLibrary(device: dev)+ }++ /// Production shader modules compiled into the shared runtime library.+ private static let shaderModules: [String] = [+ "dequant_int4",+ "dequant_int8",+ "rmsnorm",+ "rope",+ "attention",+ "moe",+ "logit",+ "turboquant",+ "fused",+ "prefill",+ ]++ /// Bundle locations for runtime shader modules.+ private static let shaderSubdirectories: [String: String] = [+ "attention": "Metal/Attention",+ "dequant_int4": "Metal/Quant",+ "dequant_int8": "Metal/Quant",+ "fused": "Metal/Fusions",+ "logit": "Metal/Sampling",+ "moe": "Metal/MoE",+ "prefill": "Metal/Prefill",+ "rmsnorm": "Metal/Primitives",+ "rope": "Metal/Primitives",+ "tensorops": "Metal/TensorCore",+ "turboquant": "Metal/KVCache",+ ]++ private static func shaderURL(module: String) -> URL? {+ guard let subdirectory = shaderSubdirectories[module] else { return nil }+ return Bundle.module.url(forResource: module, withExtension: "metal",+ subdirectory: subdirectory)+ }++ private static func compileShaderLibrary(device: MTLDevice) throws -> MTLLibrary {+ var combined = ""+ for name in shaderModules {+ guard let url = shaderURL(module: name) else {+ throw MetalError.missingShaderResource(name)+ }+ let src = try String(contentsOf: url, encoding: .utf8)+ combined += "\n// ==== \(name).metal ====\n" + src + "\n"+ }+ do {+ let opts = MTLCompileOptions()+ // The MPP prefill path requires MSL 4.0 tensor operations.+ opts.languageVersion = .version4_0+ return try device.makeLibrary(source: combined, options: opts)+ } catch {+ throw MetalError.libraryCompileFailed("\(error)")+ }+ }++ /// Compile a shader module separately from the shared runtime library.+ public static func moduleLibrary(device: MTLDevice, module: String) throws -> MTLLibrary {+ guard let url = shaderURL(module: module) else {+ throw MetalError.missingShaderResource(module)+ }+ let src = try String(contentsOf: url, encoding: .utf8)+ let opts = MTLCompileOptions()+ opts.languageVersion = .version4_0+ do {+ return try device.makeLibrary(source: src, options: opts)+ } catch {+ throw MetalError.libraryCompileFailed("\(error)")+ }+ }++ public func pipeline(_ name: String) throws -> MTLComputePipelineState {+ try pipeline(name, constants: [])+ }++ public func pipeline(_ name: String,+ constants: [MetalFunctionConstant]) throws -> MTLComputePipelineState {+ try pipeline(name, constants: constants, maxTotalThreadsPerThreadgroup: nil)+ }++ public func pipeline(_ name: String,+ constants: [MetalFunctionConstant],+ maxTotalThreadsPerThreadgroup hint: Int?) throws -> MTLComputePipelineState {+ if let hint {+ precondition(hint > 0, "maxTotalThreadsPerThreadgroup must be positive")+ }+ let sortedConstants = constants.sorted {+ if $0.index != $1.index { return $0.index < $1.index }+ return Self.constantSortKey($0.value) < Self.constantSortKey($1.value)+ }+ let key = PipelineCacheKey(name: name,+ constants: sortedConstants,+ maxTotalThreadsPerThreadgroup: hint)+ pipelineCacheLock.lock()+ let cached = pipelineCache[key]+ pipelineCacheLock.unlock()+ if let cached { return cached }++ guard library.functionNames.contains(name) else {+ throw MetalError.missingFunction(name)+ }++ let values = MTLFunctionConstantValues()+ for constant in sortedConstants {+ switch constant.value {+ case .bool(let value):+ var v = value+ values.setConstantValue(&v, type: .bool, index: constant.index)+ case .uint32(let value):+ var v = value+ values.setConstantValue(&v, type: .uint, index: constant.index)+ case .float(let value):+ var v = value+ values.setConstantValue(&v, type: .float, index: constant.index)+ }+ }++ let fn = try library.makeFunction(name: name, constantValues: values)+ let p: MTLComputePipelineState+ if let hint {+ let descriptor = MTLComputePipelineDescriptor()+ descriptor.computeFunction = fn+ descriptor.maxTotalThreadsPerThreadgroup = hint+ var reflection: MTLAutoreleasedComputePipelineReflection?+ p = try device.makeComputePipelineState(descriptor: descriptor,+ options: [],+ reflection: &reflection)+ } else {+ p = try device.makeComputePipelineState(function: fn)+ }+ pipelineCacheLock.lock()+ pipelineCache[key] = p+ pipelineCacheLock.unlock()+ return p+ }++ private static func constantSortKey(_ value: MetalFunctionConstant.Value) -> String {+ switch value {+ case .bool(let v): return "b:\(v ? 1 : 0)"+ case .uint32(let v): return "u:\(v)"+ case .float(let v): return "f:\(v.bitPattern)"+ }+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swiftnew file mode 100644index 00000000..c8848e65--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swift@@ -0,0 +1,160 @@+import Foundation++public struct ManifestFileEntry: Decodable, Equatable, Sendable {+ public let size: UInt64+ public let sha256: String+}++public struct ManifestArch: Decodable, Equatable, Sendable {+ public let hiddenSize: Int+ public let ffnIntermediate: Int+ public let moeIntermediateSize: Int+ public let numHeads: Int+ public let numKVHeads: Int+ public let numFullKVHeads: Int+ public let headDim: Int+ public let fullHeadDim: Int+ public let vocabSize: Int+ public let slidingWindow: Int+ public let finalLogitSoftcap: Double+ public let ropeTheta: Double+ public let fullRopeTheta: Double+ public let partialRotaryFactor: Double+ public let numLayers: Int+ public let numExperts: Int+ public let topKExperts: Int+ public let tieWordEmbeddings: Bool+ public let attentionKEqV: Bool+ public let hiddenActivation: String+ public let fullAttentionLayerMask: [Int]+}++public struct Manifest: Decodable, Equatable, Sendable {+ public let magic: String+ public let versionMajor: Int+ public let versionMinor: Int+ public let flags: [String: Bool]+ public let modelID: String+ public let arch: ManifestArch+ public let files: [String: ManifestFileEntry]+ public let expertsPerLayer: Int+ public let numLayers: Int+ public let expertStride: UInt64+}++public enum ManifestReader {+ public static let defaultMaxBytes: UInt64 = 4 * 1024 * 1024++ /// Recognized flag keys. Anything else in `manifest.flags` is an error.+ public static let knownFlags: Set<String> = [+ "streamingPresent", "turboQuantKV", "aneSharedExpert"+ ]++ /// Required file entries (relative to `model.gturbo/`). Layer files+ /// `packed_experts/layer_<L>.bin` for L in 0..<numLayers are checked+ /// after decode against `numLayers` (with the zero-padded "layer_%02d"+ /// naming the writer produces; falling back to plain "layer_<L>" when+ /// only the unpadded form is present, for toy synthetics).+ public static let requiredFiles: [String] = [+ "model_weights.bin",+ "packed_experts/layout.json",+ ]++ public static func load(directoryURL: URL,+ expecting: ArchConfig,+ maxBytes: UInt64 = defaultMaxBytes) throws -> Manifest {+ let manifestURL = directoryURL.appendingPathComponent("manifest.json")+ guard FileManager.default.fileExists(atPath: manifestURL.path) else {+ throw ModelError.partialInstall(path: directoryURL.path)+ }+ let size = try metadataFileSize(manifestURL, fileName: "manifest.json")+ guard size <= maxBytes else {+ throw ModelError.indexCorrupt(+ detail: "manifest.json size \(size) exceeds metadata cap \(maxBytes)")+ }+ let data = try Data(contentsOf: manifestURL)+ let manifest: Manifest+ do {+ manifest = try JSONDecoder().decode(Manifest.self, from: data)+ } catch {+ throw ModelError.indexCorrupt(detail: "manifest.json: \(error)")+ }++ try validate(manifest, against: expecting)+ return manifest+ }++ private static func metadataFileSize(_ url: URL,+ fileName: String) throws -> UInt64 {+ let attrs = try FileManager.default.attributesOfItem(atPath: url.path)+ guard let number = attrs[.size] as? NSNumber else {+ throw ModelError.indexCorrupt(detail: "\(fileName): file size unavailable")+ }+ return number.uint64Value+ }++ static func validate(_ m: Manifest,+ against expected: ArchConfig) throws {+ guard m.magic == "GTURBO" else { throw ModelError.notAGTurboDirectory }+ guard m.versionMajor == 1 else {+ throw ModelError.unsupportedVersion(major: m.versionMajor, minor: m.versionMinor)+ }+ for key in m.flags.keys {+ if !knownFlags.contains(key) {+ throw ModelError.unknownFlag(name: key)+ }+ }+ try validateArch(m.arch, expected: expected)+ let pageSize = UInt64(getpagesize())+ guard m.expertStride % pageSize == 0 else {+ throw ModelError.expertStrideNotPageAligned(stride: m.expertStride,+ pageSize: Int(pageSize))+ }+ for f in requiredFiles {+ if m.files[f] == nil { throw ModelError.missingFile(name: f) }+ }+ for L in 0..<m.numLayers {+ let padded = String(format: "packed_experts/layer_%02d.bin", L)+ let plain = "packed_experts/layer_\(L).bin"+ if m.files[padded] == nil && m.files[plain] == nil {+ throw ModelError.missingFile(name: padded)+ }+ }+ }++ private static func validateArch(_ a: ManifestArch,+ expected e: ArchConfig) throws {+ func check<T: Equatable & CustomStringConvertible>(+ _ field: String, _ actual: T, _ expected: T) throws {+ if actual != expected {+ throw ModelError.archMismatch(field: field,+ expected: "\(expected)",+ actual: "\(actual)")+ }+ }+ try check("hiddenSize", a.hiddenSize, e.hiddenSize)+ try check("ffnIntermediate", a.ffnIntermediate, e.intermediateSize)+ try check("moeIntermediateSize", a.moeIntermediateSize, e.moeIntermediateSize)+ try check("numHeads", a.numHeads, e.numHeads)+ try check("numKVHeads", a.numKVHeads, e.numKVHeads)+ try check("numFullKVHeads", a.numFullKVHeads, e.numFullKVHeads)+ try check("headDim", a.headDim, e.headDim)+ try check("fullHeadDim", a.fullHeadDim, e.fullHeadDim)+ try check("vocabSize", a.vocabSize, e.vocabSize)+ try check("slidingWindow", a.slidingWindow, e.slidingWindow)+ try check("finalLogitSoftcap", a.finalLogitSoftcap, e.finalLogitSoftcap)+ try check("ropeTheta", a.ropeTheta, e.ropeTheta)+ try check("fullRopeTheta", a.fullRopeTheta, e.fullRopeTheta)+ try check("partialRotaryFactor", a.partialRotaryFactor, e.partialRotaryFactor)+ try check("numLayers", a.numLayers, e.numLayers)+ try check("numExperts", a.numExperts, e.numExperts)+ try check("topKExperts", a.topKExperts, e.topKExperts)+ try check("tieWordEmbeddings", a.tieWordEmbeddings, e.tieWordEmbeddings)+ try check("attentionKEqV", a.attentionKEqV, e.attentionKEqV)+ try check("hiddenActivation", a.hiddenActivation, e.hiddenActivation)+ let actualMask = a.fullAttentionLayerMask.map { UInt8($0) }+ try check("fullAttentionLayerMask",+ actualMask.description,+ e.fullAttentionLayerMask.description)+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swiftnew file mode 100644index 00000000..adb33fe7--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swift@@ -0,0 +1,192 @@+import Foundation+import Metal++/// Compile-time architecture baseline. `manifest.json -> arch` must match this+/// field-by-field at load time; mismatches throw `ModelError.archMismatch`.+public struct ArchConfig: Sendable, Equatable {+ public let hiddenSize: Int+ public let intermediateSize: Int // shared expert FFN (== ffnIntermediate in manifest)+ public let moeIntermediateSize: Int // per-expert FFN+ public let numHeads: Int+ public let numKVHeads: Int+ public let numFullKVHeads: Int+ public let headDim: Int+ public let fullHeadDim: Int+ public let vocabSize: Int+ public let slidingWindow: Int+ public let finalLogitSoftcap: Double+ public let ropeTheta: Double+ public let fullRopeTheta: Double+ public let partialRotaryFactor: Double+ public let numLayers: Int+ public let numExperts: Int+ public let topKExperts: Int+ public let tieWordEmbeddings: Bool+ public let attentionKEqV: Bool+ public let fullAttentionLayerMask: [UInt8]+ public let hiddenActivation: String++ public init(+ hiddenSize: Int,+ intermediateSize: Int,+ moeIntermediateSize: Int,+ numHeads: Int,+ numKVHeads: Int,+ numFullKVHeads: Int,+ headDim: Int,+ fullHeadDim: Int,+ vocabSize: Int,+ slidingWindow: Int,+ finalLogitSoftcap: Double,+ ropeTheta: Double,+ fullRopeTheta: Double,+ partialRotaryFactor: Double,+ numLayers: Int,+ numExperts: Int,+ topKExperts: Int,+ tieWordEmbeddings: Bool,+ attentionKEqV: Bool,+ fullAttentionLayerMask: [UInt8],+ hiddenActivation: String+ ) {+ self.hiddenSize = hiddenSize+ self.intermediateSize = intermediateSize+ self.moeIntermediateSize = moeIntermediateSize+ self.numHeads = numHeads+ self.numKVHeads = numKVHeads+ self.numFullKVHeads = numFullKVHeads+ self.headDim = headDim+ self.fullHeadDim = fullHeadDim+ self.vocabSize = vocabSize+ self.slidingWindow = slidingWindow+ self.finalLogitSoftcap = finalLogitSoftcap+ self.ropeTheta = ropeTheta+ self.fullRopeTheta = fullRopeTheta+ self.partialRotaryFactor = partialRotaryFactor+ self.numLayers = numLayers+ self.numExperts = numExperts+ self.topKExperts = topKExperts+ self.tieWordEmbeddings = tieWordEmbeddings+ self.attentionKEqV = attentionKEqV+ self.fullAttentionLayerMask = fullAttentionLayerMask+ self.hiddenActivation = hiddenActivation+ }++ /// Canonical Gemma 4 26B-A4B baseline, checked against the installed+ /// model manifest.+ /// `intermediateSize = 2112` is the shared-expert FFN width (3 × moe).+ public static let gemma4_26B_A4B = ArchConfig(+ hiddenSize: 2816,+ intermediateSize: 2112,+ moeIntermediateSize: 704,+ numHeads: 16,+ numKVHeads: 8,+ numFullKVHeads: 2,+ headDim: 256,+ fullHeadDim: 512,+ vocabSize: 262144,+ slidingWindow: 1024,+ finalLogitSoftcap: 30.0,+ ropeTheta: 10_000.0,+ fullRopeTheta: 1_000_000.0,+ partialRotaryFactor: 0.25,+ numLayers: 30,+ numExperts: 128,+ topKExperts: 8,+ tieWordEmbeddings: true,+ attentionKEqV: true,+ fullAttentionLayerMask: Self.gemma4LayerMask(),+ hiddenActivation: "gelu_pytorch_tanh"+ )++ private static func gemma4LayerMask() -> [UInt8] {+ var mask = [UInt8](repeating: 0, count: 30)+ for i in stride(from: 5, to: 30, by: 6) { mask[i] = 1 }+ return mask+ }+}++/// Failure modes for the validation gates in `Model.load`.+enum ModelError: Error, CustomStringConvertible, Equatable {+ case partialInstall(path: String)+ case notAGTurboDirectory+ case unsupportedVersion(major: Int, minor: Int)+ case unknownFlag(name: String)+ case archMismatch(field: String, expected: String, actual: String)+ case expertStrideNotPageAligned(stride: UInt64, pageSize: Int)+ case missingFile(name: String)+ case checksumMismatch(file: String)+ case tensorNotFound(name: String)+ case tensorSizeMismatch(name: String, expected: UInt64, actual: UInt64)+ case residentBufferWrapFailed+ case indexCorrupt(detail: String)+ case posixFailed(call: String, errno: Int32)+ case trustedReceiptInvalid(detail: String)++ public var description: String {+ switch self {+ case .partialInstall(let p):+ return "model.gturbo directory at \(p) is missing manifest.json"+ case .notAGTurboDirectory:+ return "manifest.json magic does not equal \"GTURBO\""+ case .unsupportedVersion(let maj, let min):+ return "manifest version \(maj).\(min) is not supported (need 1.x)"+ case .unknownFlag(let n):+ return "manifest.flags contains unknown key \"\(n)\""+ case .archMismatch(let field, let exp, let act):+ return "manifest.arch.\(field) = \(act); expected \(exp)"+ case .expertStrideNotPageAligned(let s, let p):+ return "expertStride \(s) is not a multiple of page size \(p)"+ case .missingFile(let n):+ return "model.gturbo is missing required file \(n)"+ case .checksumMismatch(let f):+ return "SHA-256 of \(f) does not match manifest.files[\(f)].sha256"+ case .tensorNotFound(let n):+ return "no IndexEntry named \(n) in model_weights.bin"+ case .tensorSizeMismatch(let n, let e, let a):+ return "tensor \(n) size \(a) does not match expected \(e)"+ case .residentBufferWrapFailed:+ return "MTLDevice.makeBuffer(bytesNoCopy:...) returned nil"+ case .indexCorrupt(let d):+ return "resident index is corrupt: \(d)"+ case .posixFailed(let c, let e):+ return "\(c) failed with errno \(e)"+ case .trustedReceiptInvalid(let detail):+ return "trusted install receipt invalid: \(detail)"+ }+ }+}++/// View into a tensor that lives inside one of the loader's resident or+/// streamed `MTLBuffer`s. No `MTLBuffer` is allocated per tensor — the+/// `buffer` reference is shared across many `TensorView` instances and+/// addressed by byte offsets.+public struct TensorView: @unchecked Sendable {+ public let buffer: MTLBuffer+ public let offset: UInt64+ public let length: UInt64+ public let scaleOffset: UInt64+ public let scaleLength: UInt64+ public let biasOffset: UInt64+ public let biasLength: UInt64+ public let shape: (UInt32, UInt32, UInt32, UInt32)+ /// Dtype byte. 0 = U32, 1 = BF16, 2 = FP16, 3 = FP32.+ public let dtype: UInt8++ public init(buffer: MTLBuffer,+ offset: UInt64, length: UInt64,+ scaleOffset: UInt64, scaleLength: UInt64,+ biasOffset: UInt64, biasLength: UInt64,+ shape: (UInt32, UInt32, UInt32, UInt32),+ dtype: UInt8) {+ self.buffer = buffer+ self.offset = offset+ self.length = length+ self.scaleOffset = scaleOffset+ self.scaleLength = scaleLength+ self.biasOffset = biasOffset+ self.biasLength = biasLength+ self.shape = shape+ self.dtype = dtype+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/PackedExpertsLayout.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/PackedExpertsLayout.swiftnew file mode 100644index 00000000..0ee0628d--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/PackedExpertsLayout.swift@@ -0,0 +1,148 @@+import Foundation++struct SubTensorEntry: Sendable, Equatable {+ let offset: UInt64 // relative to the expert blob's start+}++struct ExpertEntry: Sendable {+ /// Logical routed-expert id used by the model/router.+ let expert: Int+ /// Absolute byte offset of this expert blob's start inside its layer file.+ let offset: UInt64+ /// Total bytes consumed by this expert blob (== `expertStride`).+ let size: UInt64+ /// Sub-tensors keyed by role (gate / up / down / shared) and component+ /// (raw, `_scales`, `_biases`).+ let subTensors: [String: SubTensorEntry]++ init(expert: Int,+ offset: UInt64,+ size: UInt64,+ subTensors: [String: SubTensorEntry]) {+ self.expert = expert+ self.offset = offset+ self.size = size+ self.subTensors = subTensors+ }+}++struct LayerLayout: Sendable {+ let layer: Int+ let file: String // basename, e.g. "layer_00.bin"+ let experts: [ExpertEntry]+}++struct PackedExpertsLayout: Sendable {+ let expertStride: UInt64+ let numLayers: Int+ let expertsPerLayer: Int+ let layers: [LayerLayout]++ /// Resolve `(layer, expert)` -> `ExpertEntry`. O(1).+ func expert(layer: Int, expert: Int) -> ExpertEntry {+ return layers[layer].experts[expert]+ }+}++enum PackedExpertsLayoutReader {+ static let defaultMaxBytes: UInt64 = 16 * 1024 * 1024++ static func load(directoryURL: URL,+ maxBytes: UInt64 = defaultMaxBytes) throws -> PackedExpertsLayout {+ let url = directoryURL+ .appendingPathComponent("packed_experts")+ .appendingPathComponent("layout.json")+ guard FileManager.default.fileExists(atPath: url.path) else {+ throw ModelError.missingFile(name: "packed_experts/layout.json")+ }+ let size = try metadataFileSize(url)+ guard size <= maxBytes else {+ throw ModelError.indexCorrupt(+ detail: "layout.json size \(size) exceeds metadata cap \(maxBytes)")+ }+ let data = try Data(contentsOf: url)+ let root: [String: Any]+ do {+ root = try (JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:]+ } catch {+ throw ModelError.indexCorrupt(detail: "layout.json: \(error)")+ }+ guard+ let expertStride = (root["expertStride"] as? NSNumber)?.uint64Value,+ let numLayers = root["numLayers"] as? Int,+ let expertsPerLayer = root["expertsPerLayer"] as? Int,+ let layersArr = root["layers"] as? [[String: Any]]+ else {+ throw ModelError.indexCorrupt(detail: "layout.json: missing top-level keys")+ }++ var layers: [LayerLayout] = []+ layers.reserveCapacity(layersArr.count)+ for layerObj in layersArr {+ guard+ let layerIdx = layerObj["layer"] as? Int,+ let file = layerObj["file"] as? String,+ let expertsArr = layerObj["experts"] as? [[String: Any]]+ else {+ throw ModelError.indexCorrupt(detail: "layout.json: malformed layer entry")+ }+ var experts = [ExpertEntry?](repeating: nil, count: expertsPerLayer)+ for expertObj in expertsArr {+ guard+ let offset = (expertObj["offset"] as? NSNumber)?.uint64Value,+ let size = (expertObj["size"] as? NSNumber)?.uint64Value,+ let tensorsObj = expertObj["tensors"] as? [String: [String: Any]]+ else {+ throw ModelError.indexCorrupt(detail: "layout.json: malformed expert entry")+ }+ var subTensors: [String: SubTensorEntry] = [:]+ for (role, t) in tensorsObj {+ guard+ let toff = (t["offset"] as? NSNumber)?.uint64Value,+ t["size"] is NSNumber,+ t["dtype"] is String,+ t["shape"] is [Int]+ else {+ throw ModelError.indexCorrupt(detail: "layout.json: malformed tensor \(role)")+ }+ if let bits = t["bits"], !(bits is Int) {+ throw ModelError.indexCorrupt(detail: "layout.json: malformed tensor bits \(role)")+ }+ subTensors[role] = SubTensorEntry(offset: toff)+ }+ let expertID = expertObj["expert"] as? Int ?? experts.compactMap { $0 }.count+ guard expertID >= 0 && expertID < expertsPerLayer else {+ throw ModelError.indexCorrupt(detail: "layout.json: expert id out of range")+ }+ let physicalRank = expertObj["physicalRank"] as? Int+ if let physicalRank,+ (physicalRank < 0 || physicalRank >= expertsPerLayer) {+ throw ModelError.indexCorrupt(detail: "layout.json: physicalRank out of range")+ }+ experts[expertID] = ExpertEntry(expert: expertID,+ offset: offset,+ size: size,+ subTensors: subTensors)+ }+ guard experts.allSatisfy({ $0 != nil }) else {+ throw ModelError.indexCorrupt(detail: "layout.json: missing expert entries")+ }+ layers.append(LayerLayout(layer: layerIdx,+ file: file,+ experts: experts.map { $0! }))+ }++ return PackedExpertsLayout(expertStride: expertStride,+ numLayers: numLayers,+ expertsPerLayer: expertsPerLayer,+ layers: layers)+ }++ private static func metadataFileSize(_ url: URL) throws -> UInt64 {+ let attrs = try FileManager.default.attributesOfItem(atPath: url.path)+ guard let number = attrs[.size] as? NSNumber else {+ throw ModelError.indexCorrupt(detail: "layout.json: file size unavailable")+ }+ return number.uint64Value+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/Quantization.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/Quantization.swiftnew file mode 100644index 00000000..8dbef9cb--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/Quantization.swift@@ -0,0 +1,192 @@+import Foundation++public enum Quantization {++ public static let groupSize: Int = 64++ // MARK: - BF16 helpers+ //+ // BF16 = top 16 bits of FP32 (8-bit exponent, 7-bit mantissa). Stored on+ // disk and on the GPU as the native `bfloat` type; in Swift we carry the+ // raw bits as `UInt16` and convert via this pair. Round-half-to-even on+ // encode matches the IEEE-754 default. No NaN/Inf special-case: fixtures+ // are bounded and finite, and the .gturbo importer copies BF16 bytes+ // through unchanged so we never call the encoder on weight data.++ @inline(__always)+ public static func bf16Bits(_ x: Float) -> UInt16 {+ let bits = x.bitPattern+ let lsb = (bits >> 16) & 1+ let roundingBias: UInt32 = 0x7FFF &+ lsb+ let rounded = (bits &+ roundingBias) >> 16+ return UInt16(truncatingIfNeeded: rounded)+ }++ @inline(__always)+ public static func bf16ToFloat(_ bits: UInt16) -> Float {+ Float(bitPattern: UInt32(bits) << 16)+ }++ // MARK: - INT4 affine++ /// MLX `affine` 4-bit row. Packed unsigned nibbles, BF16 scale + bias per+ /// group of 64. `scales` and `biases` carry BF16 bit patterns as `UInt16`+ /// so the same buffer can be uploaded to a Metal `device const bfloat*`.+ public struct Int4AffineRow {+ public let packed: [UInt8] // N / 2 bytes; low nibble = even index, high = odd+ public let scales: [UInt16] // N / 64 BF16 bits+ public let biases: [UInt16] // N / 64 BF16 bits++ public init(packed: [UInt8], scales: [UInt16], biases: [UInt16]) {+ self.packed = packed+ self.scales = scales+ self.biases = biases+ }+ }++ /// Affine 4-bit quantize: `q ∈ [0..15]`, `w ≈ q * scale + bias`.+ /// Scale and bias are computed from per-group min/max, then rounded to BF16.+ /// Test-fixture only — the runtime importer never calls this.+ public static func quantizeInt4Affine(_ row: [Float]) -> Int4AffineRow {+ precondition(row.count % groupSize == 0,+ "row length \(row.count) is not a multiple of \(groupSize)")++ let nGroups = row.count / groupSize+ var packed = [UInt8](repeating: 0, count: row.count / 2)+ var scales = [UInt16](repeating: 0, count: nGroups)+ var biases = [UInt16](repeating: 0, count: nGroups)++ for g in 0..<nGroups {+ var wmin: Float = .infinity+ var wmax: Float = -.infinity+ for k in 0..<groupSize {+ let w = row[g * groupSize + k]+ if w < wmin { wmin = w }+ if w > wmax { wmax = w }+ }+ // Constant group: scale=1, bias=value preserves exact reconstruction.+ let scaleF: Float+ let biasF: Float+ if wmax == wmin {+ scaleF = 1+ biasF = wmin+ } else {+ scaleF = (wmax - wmin) / 15.0+ biasF = wmin+ }+ // Round through BF16 first, then quantize against the rounded+ // values so the runtime decode (which reads BF16) reproduces the+ // same q the fixture stored.+ let sBits = bf16Bits(scaleF)+ let bBits = bf16Bits(biasF)+ scales[g] = sBits+ biases[g] = bBits+ let scale = bf16ToFloat(sBits)+ let bias = bf16ToFloat(bBits)+ let invScale = scale == 0 ? Float(0) : 1.0 / scale++ for k in 0..<groupSize {+ let w = row[g * groupSize + k]+ var q = Int(((w - bias) * invScale).rounded())+ q = max(0, min(15, q))+ let nibble = UInt8(q) & 0x0F+ let byteIdx = g * (groupSize / 2) + (k / 2)+ if (k & 1) == 0 {+ packed[byteIdx] = (packed[byteIdx] & 0xF0) | nibble+ } else {+ packed[byteIdx] = (packed[byteIdx] & 0x0F) | (nibble << 4)+ }+ }+ }+ return Int4AffineRow(packed: packed, scales: scales, biases: biases)+ }++ public static func dequantizeInt4Affine(_ r: Int4AffineRow, n: Int) -> [Float] {+ precondition(n == r.packed.count * 2)+ var out = [Float](repeating: 0, count: n)+ let nGroups = n / groupSize+ for g in 0..<nGroups {+ let scale = bf16ToFloat(r.scales[g])+ let bias = bf16ToFloat(r.biases[g])+ for k in 0..<groupSize {+ let byteIdx = g * (groupSize / 2) + (k / 2)+ let b = r.packed[byteIdx]+ let nibble: Int = (k & 1) == 0 ? Int(b & 0x0F) : Int(b >> 4)+ out[g * groupSize + k] = Float(nibble) * scale + bias+ }+ }+ return out+ }++ // MARK: - INT8 affine++ public struct Int8AffineRow {+ public let packed: [UInt8] // N unsigned bytes+ public let scales: [UInt16] // N / 64 BF16 bits+ public let biases: [UInt16] // N / 64 BF16 bits++ public init(packed: [UInt8], scales: [UInt16], biases: [UInt16]) {+ self.packed = packed+ self.scales = scales+ self.biases = biases+ }+ }++ public static func quantizeInt8Affine(_ row: [Float]) -> Int8AffineRow {+ precondition(row.count % groupSize == 0,+ "row length \(row.count) is not a multiple of \(groupSize)")++ let nGroups = row.count / groupSize+ var packed = [UInt8](repeating: 0, count: row.count)+ var scales = [UInt16](repeating: 0, count: nGroups)+ var biases = [UInt16](repeating: 0, count: nGroups)++ for g in 0..<nGroups {+ var wmin: Float = .infinity+ var wmax: Float = -.infinity+ for k in 0..<groupSize {+ let w = row[g * groupSize + k]+ if w < wmin { wmin = w }+ if w > wmax { wmax = w }+ }+ let scaleF: Float+ let biasF: Float+ if wmax == wmin {+ scaleF = 1+ biasF = wmin+ } else {+ scaleF = (wmax - wmin) / 255.0+ biasF = wmin+ }+ let sBits = bf16Bits(scaleF)+ let bBits = bf16Bits(biasF)+ scales[g] = sBits+ biases[g] = bBits+ let scale = bf16ToFloat(sBits)+ let bias = bf16ToFloat(bBits)+ let invScale = scale == 0 ? Float(0) : 1.0 / scale++ for k in 0..<groupSize {+ let w = row[g * groupSize + k]+ var q = Int(((w - bias) * invScale).rounded())+ q = max(0, min(255, q))+ packed[g * groupSize + k] = UInt8(q)+ }+ }+ return Int8AffineRow(packed: packed, scales: scales, biases: biases)+ }++ public static func dequantizeInt8Affine(_ r: Int8AffineRow, n: Int) -> [Float] {+ precondition(n == r.packed.count)+ var out = [Float](repeating: 0, count: n)+ let nGroups = n / groupSize+ for g in 0..<nGroups {+ let scale = bf16ToFloat(r.scales[g])+ let bias = bf16ToFloat(r.biases[g])+ for k in 0..<groupSize {+ out[g * groupSize + k] = Float(r.packed[g * groupSize + k]) * scale + bias+ }+ }+ return out+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swiftnew file mode 100644index 00000000..d7eb5216--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swift@@ -0,0 +1,59 @@+import Foundation+import Darwin+import Metal++/// `mmap`'d view of `model_weights.bin`'s tensor data region, wrapped in+/// one shared `MTLBuffer`. All resident `TensorView`s alias byte offsets+/// inside `buffer`.+final class ResidentBuffer {+ let buffer: MTLBuffer++ /// `mmap` the page-aligned window covering `[fileOffset, fileOffset + residentSize)`+ /// inside the file at `fileURL`. The wrapped `MTLBuffer` starts at the+ /// (sub-page) offset within the mapping so the resident bytes start at+ /// byte 0 of the buffer.+ init(fileURL: URL,+ fileOffset: UInt64,+ residentSize: UInt64,+ device: MTLDevice) throws {+ let pageSize = Int(getpagesize())++ let fd = open(fileURL.path, O_RDONLY)+ guard fd >= 0 else {+ throw ModelError.posixFailed(call: "open(\(fileURL.path))", errno: errno)+ }+ defer { close(fd) }++ let alignedOffset = (fileOffset / UInt64(pageSize)) * UInt64(pageSize)+ let sliceShift = Int(fileOffset - alignedOffset)+ let mappedLen = sliceShift + Int(residentSize)+ let mapped = mmap(nil, mappedLen, PROT_READ, MAP_PRIVATE,+ fd, off_t(alignedOffset))+ if mapped == MAP_FAILED {+ throw ModelError.posixFailed(call: "mmap", errno: errno)+ }+ let base = mapped!++ _ = posix_madvise(base, mappedLen, POSIX_MADV_RANDOM)++ let sliceStart = base.advanced(by: sliceShift)++ // Capture pointer + length for the deallocator. Do NOT capture self+ // here — that would create a retain cycle through the MTLBuffer.+ nonisolated(unsafe) let captureBase = base+ let captureLen = mappedLen+ guard let buf = device.makeBuffer(+ bytesNoCopy: sliceStart,+ length: Int(residentSize),+ options: .storageModeShared,+ deallocator: { _, _ in+ munmap(captureBase, captureLen)+ }+ ) else {+ munmap(base, mappedLen)+ throw ModelError.residentBufferWrapFailed+ }++ self.buffer = buf+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentIndex.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentIndex.swiftnew file mode 100644index 00000000..a013fe3b--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentIndex.swift@@ -0,0 +1,172 @@+import Foundation+import Darwin++/// On-disk header. `indexSize` is the full byte size of the leading index+/// region — it INCLUDES the 24-byte header itself, the entry table, the+/// string table, and the writer's 16 KB page padding. The resident tensor+/// region starts at file byte `indexSize`.+struct ResidentIndexHeader: Sendable, Equatable {+ let indexSize: UInt64+ let residentSize: UInt64+ let entryCount: UInt64+}++public struct ResidentIndexEntry: Sendable, Equatable {+ public let name: String+ public let dtype: UInt8+ /// Absolute file offset of the packed weight bytes (≥ `indexSize`).+ public let fileOffset: UInt64+ public let sizeBytes: UInt64+ public let shape: (UInt32, UInt32, UInt32, UInt32)+ public let scaleOffset: UInt64+ public let scaleSize: UInt64+ public let biasOffset: UInt64+ public let biasSize: UInt64++ public static func == (a: ResidentIndexEntry, b: ResidentIndexEntry) -> Bool {+ a.name == b.name && a.dtype == b.dtype+ && a.fileOffset == b.fileOffset && a.sizeBytes == b.sizeBytes+ && a.shape.0 == b.shape.0 && a.shape.1 == b.shape.1+ && a.shape.2 == b.shape.2 && a.shape.3 == b.shape.3+ && a.scaleOffset == b.scaleOffset && a.scaleSize == b.scaleSize+ && a.biasOffset == b.biasOffset && a.biasSize == b.biasSize+ }+}++/// Parsed resident index: header + name-keyed entries.+struct ResidentIndex: Sendable {+ let header: ResidentIndexHeader+ let entries: [String: ResidentIndexEntry]+}++enum ResidentIndexReader {++ static let headerBytes = 24+ static let entryBytes = 72++ /// `pread` the header + index region out of `model_weights.bin`. The+ /// tensor data region (starting at byte `header.indexSize`) is **not**+ /// read here — that's the resident-buffer materialization job.+ static func load(fileURL: URL) throws -> ResidentIndex {+ let fd = open(fileURL.path, O_RDONLY)+ guard fd >= 0 else {+ throw ModelError.posixFailed(call: "open(\(fileURL.path))", errno: errno)+ }+ defer { close(fd) }++ // -- header+ var headerBuf = [UInt8](repeating: 0, count: headerBytes)+ var got = 0+ headerBuf.withUnsafeMutableBufferPointer { p in+ got = pread(fd, p.baseAddress!, headerBytes, 0)+ }+ guard got == headerBytes else {+ throw ModelError.indexCorrupt(detail: "short read for IndexHeader (\(got)/\(headerBytes))")+ }+ let header = headerBuf.withUnsafeBytes { raw -> ResidentIndexHeader in+ let base = raw.baseAddress!+ return ResidentIndexHeader(+ indexSize: decodeU64LE(base, 0),+ residentSize: decodeU64LE(base, 8),+ entryCount: decodeU64LE(base, 16))+ }++ guard header.indexSize >= UInt64(headerBytes) else {+ throw ModelError.indexCorrupt(+ detail: "indexSize \(header.indexSize) < header size \(headerBytes)")+ }+ let expectedEntryTableEnd = UInt64(headerBytes) + UInt64(header.entryCount) * UInt64(entryBytes)+ guard expectedEntryTableEnd <= header.indexSize else {+ throw ModelError.indexCorrupt(+ detail: "header+entries (\(expectedEntryTableEnd)) > indexSize \(header.indexSize)")+ }++ // -- entire index region (header + entries + string table + padding)+ let regionLen = Int(header.indexSize)+ var indexBuf = [UInt8](repeating: 0, count: regionLen)+ indexBuf.withUnsafeMutableBufferPointer { p in+ got = pread(fd, p.baseAddress!, regionLen, 0)+ }+ guard got == regionLen else {+ throw ModelError.indexCorrupt(detail: "short read for index region (\(got)/\(regionLen))")+ }++ // -- parse entries. Each IndexEntry stores `nameOffset` as an+ // absolute file offset; since we read the leading region starting+ // at file offset 0, that's also the buffer offset.+ var entries: [String: ResidentIndexEntry] = [:]+ entries.reserveCapacity(Int(header.entryCount))+ try indexBuf.withUnsafeBytes { raw in+ let base = raw.baseAddress!+ for i in 0..<Int(header.entryCount) {+ let p = base.advanced(by: headerBytes + i * entryBytes)+ let nameOffset = Int(decodeU32LE(p, 0))+ let nameLength = Int(decodeU16LE(p, 4))+ let dtype = decodeU8(p, 6)+ // byte 7 is reserved+ let fileOffset = decodeU64LE(p, 8)+ let sizeBytes = decodeU64LE(p, 16)+ let s0 = decodeU32LE(p, 24)+ let s1 = decodeU32LE(p, 28)+ let s2 = decodeU32LE(p, 32)+ let s3 = decodeU32LE(p, 36)+ let scaleOffset = decodeU64LE(p, 40)+ let scaleSize = decodeU64LE(p, 48)+ let biasOffset = decodeU64LE(p, 56)+ let biasSize = decodeU64LE(p, 64)++ guard nameOffset >= headerBytes,+ nameOffset + nameLength <= regionLen else {+ throw ModelError.indexCorrupt(+ detail: "entry \(i) name range [\(nameOffset), \(nameOffset + nameLength)) " ++ "out of index region [\(headerBytes), \(regionLen))")+ }+ let namePtr = base.advanced(by: nameOffset)+ let name = String(decoding: UnsafeRawBufferPointer(+ start: namePtr, count: nameLength), as: UTF8.self)++ let entry = ResidentIndexEntry(+ name: name, dtype: dtype,+ fileOffset: fileOffset, sizeBytes: sizeBytes,+ shape: (s0, s1, s2, s3),+ scaleOffset: scaleOffset, scaleSize: scaleSize,+ biasOffset: biasOffset, biasSize: biasSize)+ if entries[name] != nil {+ throw ModelError.indexCorrupt(detail: "duplicate tensor name \(name)")+ }+ entries[name] = entry+ }+ }++ return ResidentIndex(header: header, entries: entries)+ }++ // MARK: - little-endian primitives++ @inline(__always)+ static func decodeU64LE(_ base: UnsafeRawPointer, _ off: Int) -> UInt64 {+ let p = base.advanced(by: off).assumingMemoryBound(to: UInt8.self)+ var v: UInt64 = 0+ for i in (0..<8).reversed() { v = (v << 8) | UInt64(p[i]) }+ return v+ }++ @inline(__always)+ static func decodeU32LE(_ base: UnsafeRawPointer, _ off: Int) -> UInt32 {+ let p = base.advanced(by: off).assumingMemoryBound(to: UInt8.self)+ var v: UInt32 = 0+ for i in (0..<4).reversed() { v = (v << 8) | UInt32(p[i]) }+ return v+ }++ @inline(__always)+ static func decodeU16LE(_ base: UnsafeRawPointer, _ off: Int) -> UInt16 {+ let p = base.advanced(by: off).assumingMemoryBound(to: UInt8.self)+ return UInt16(p[0]) | (UInt16(p[1]) << 8)+ }++ @inline(__always)+ static func decodeU8(_ base: UnsafeRawPointer, _ off: Int) -> UInt8 {+ base.advanced(by: off).assumingMemoryBound(to: UInt8.self)[0]+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/Sha256Verifier.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/Sha256Verifier.swiftnew file mode 100644index 00000000..da79b5db--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/Sha256Verifier.swift@@ -0,0 +1,66 @@+import Foundation+import CommonCrypto+import Darwin++public enum Sha256Verifier {++ /// Compute the lowercase-hex SHA-256 of the entire file at `fileURL` by+ /// streaming through a fixed-size scratch read. Does not allocate the+ /// whole file.+ public static func hashFile(at fileURL: URL,+ chunkBytes: Int = 1 << 20) throws -> String {+ let fd = open(fileURL.path, O_RDONLY)+ guard fd >= 0 else {+ throw ModelError.posixFailed(call: "open(\(fileURL.path))", errno: errno)+ }+ defer { close(fd) }++ var ctx = CC_SHA256_CTX()+ CC_SHA256_Init(&ctx)+ var buf = [UInt8](repeating: 0, count: chunkBytes)+ while true {+ let got: Int = buf.withUnsafeMutableBytes { raw -> Int in+ return read(fd, raw.baseAddress!, chunkBytes)+ }+ if got == 0 { break }+ if got < 0 {+ throw ModelError.posixFailed(call: "read", errno: errno)+ }+ buf.withUnsafeBytes { raw in+ _ = CC_SHA256_Update(&ctx, raw.baseAddress!, CC_LONG(got))+ }+ }+ var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))+ digest.withUnsafeMutableBytes { raw in+ _ = CC_SHA256_Final(raw.baseAddress!.assumingMemoryBound(to: UInt8.self), &ctx)+ }+ return digest.map { String(format: "%02x", $0) }.joined()+ }++ public static func hashData(_ data: Data) -> String {+ var ctx = CC_SHA256_CTX()+ CC_SHA256_Init(&ctx)+ data.withUnsafeBytes { raw in+ if let base = raw.baseAddress, raw.count > 0 {+ _ = CC_SHA256_Update(&ctx, base, CC_LONG(raw.count))+ }+ }+ var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))+ digest.withUnsafeMutableBytes { raw in+ _ = CC_SHA256_Final(raw.baseAddress!.assumingMemoryBound(to: UInt8.self), &ctx)+ }+ return digest.map { String(format: "%02x", $0) }.joined()+ }++ /// Throw `ModelError.checksumMismatch(file)` if the on-disk file's+ /// SHA-256 does not match `expectedHex`. Hex comparison is+ /// case-insensitive on the expected side (writer outputs lowercase).+ public static func verifyFile(at fileURL: URL,+ named name: String,+ expectedHex: String) throws {+ let actual = try hashFile(at: fileURL)+ if actual.lowercased() != expectedHex.lowercased() {+ throw ModelError.checksumMismatch(file: name)+ }+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/VerifiedInstallReceipt.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/VerifiedInstallReceipt.swiftnew file mode 100644index 00000000..8646c73f--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/VerifiedInstallReceipt.swift@@ -0,0 +1,136 @@+import Foundation++public enum ModelIntegrityPolicy: Sendable, Equatable {+ case fullSha256+ case sizeCheckTrustedReceipt+}++public struct VerifiedInstallReceipt: Codable, Equatable, Sendable {+ public struct FileEntry: Codable, Equatable, Sendable {+ public let size: UInt64+ public let sha256: String++ public init(size: UInt64, sha256: String) {+ self.size = size+ self.sha256 = sha256+ }+ }++ public let schemaVersion: Int+ public let manifestSha256: String+ public let modelDirectoryPath: String+ public let sourceRepoID: String?+ public let sourceRevision: String?+ public let verificationTimestamp: String+ public let toolVersion: String+ public let files: [String: FileEntry]++ public init(schemaVersion: Int = 1,+ manifestSha256: String,+ modelDirectoryPath: String,+ sourceRepoID: String? = nil,+ sourceRevision: String? = nil,+ verificationTimestamp: String,+ toolVersion: String,+ files: [String: FileEntry]) {+ self.schemaVersion = schemaVersion+ self.manifestSha256 = manifestSha256+ self.modelDirectoryPath = modelDirectoryPath+ self.sourceRepoID = sourceRepoID+ self.sourceRevision = sourceRevision+ self.verificationTimestamp = verificationTimestamp+ self.toolVersion = toolVersion+ self.files = files+ }+}++public enum VerifiedInstallReceiptReader {+ public static let fileName = "verified-install.json"+ public static let defaultMaxBytes: UInt64 = 4 * 1024 * 1024++ public static func load(directoryURL: URL,+ maxBytes: UInt64 = defaultMaxBytes) throws -> VerifiedInstallReceipt {+ let url = directoryURL.appendingPathComponent(fileName)+ guard FileManager.default.fileExists(atPath: url.path) else {+ throw ModelError.trustedReceiptInvalid(detail: "\(fileName) is missing")+ }+ do {+ let size = try fileSize(url)+ guard size <= maxBytes else {+ throw ModelError.trustedReceiptInvalid(+ detail: "\(fileName) size \(size) exceeds metadata cap \(maxBytes)")+ }+ let data = try Data(contentsOf: url)+ return try JSONDecoder().decode(VerifiedInstallReceipt.self, from: data)+ } catch let error as ModelError {+ throw error+ } catch {+ throw ModelError.trustedReceiptInvalid(detail: "\(fileName): \(error)")+ }+ }++ private static func fileSize(_ url: URL) throws -> UInt64 {+ let attrs = try FileManager.default.attributesOfItem(atPath: url.path)+ guard let number = attrs[.size] as? NSNumber else {+ throw ModelError.trustedReceiptInvalid(detail: "\(fileName) size unavailable")+ }+ return number.uint64Value+ }++ public static func validate(_ receipt: VerifiedInstallReceipt,+ directoryURL: URL,+ manifest: Manifest,+ manifestSha256: String,+ manifestSize: UInt64) throws {+ try validateManifestBinding(receipt,+ directoryURL: directoryURL,+ manifestSha256: manifestSha256)+ var expectedFiles = Set(manifest.files.keys)+ expectedFiles.insert("manifest.json")+ let receiptFiles = Set(receipt.files.keys)+ guard receiptFiles == expectedFiles else {+ let missing = expectedFiles.subtracting(receiptFiles).sorted()+ let extra = receiptFiles.subtracting(expectedFiles).sorted()+ throw ModelError.trustedReceiptInvalid(+ detail: "receipt file set mismatch missing=\(missing) extra=\(extra)")+ }+ guard let manifestReceiptEntry = receipt.files["manifest.json"] else {+ throw ModelError.trustedReceiptInvalid(detail: "receipt missing manifest.json")+ }+ guard manifestReceiptEntry.size == manifestSize else {+ throw ModelError.trustedReceiptInvalid(detail: "manifest.json size mismatch")+ }+ guard manifestReceiptEntry.sha256.lowercased() == manifestSha256.lowercased() else {+ throw ModelError.trustedReceiptInvalid(detail: "manifest.json SHA mismatch")+ }++ for (rel, manifestEntry) in manifest.files {+ guard let receiptEntry = receipt.files[rel] else {+ throw ModelError.trustedReceiptInvalid(detail: "receipt missing \(rel)")+ }+ guard receiptEntry.size == manifestEntry.size else {+ throw ModelError.trustedReceiptInvalid(detail: "receipt size mismatch for \(rel)")+ }+ guard receiptEntry.sha256.lowercased() == manifestEntry.sha256.lowercased() else {+ throw ModelError.trustedReceiptInvalid(detail: "receipt SHA mismatch for \(rel)")+ }+ }+ }++ public static func validateManifestBinding(_ receipt: VerifiedInstallReceipt,+ directoryURL: URL,+ manifestSha256: String) throws {+ guard receipt.schemaVersion == 1 else {+ throw ModelError.trustedReceiptInvalid(+ detail: "unsupported schemaVersion \(receipt.schemaVersion)")+ }+ guard receipt.manifestSha256.lowercased() == manifestSha256.lowercased() else {+ throw ModelError.trustedReceiptInvalid(detail: "manifest SHA mismatch")+ }++ let actualPath = directoryURL.standardizedFileURL.path+ guard receipt.modelDirectoryPath == actualPath else {+ throw ModelError.trustedReceiptInvalid(detail: "model directory mismatch")+ }+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/Streaming/ExpertStreamer.swift b/Sources/TurboFieldfare/Infrastructure/Streaming/ExpertStreamer.swiftnew file mode 100644index 00000000..6af86cae--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/Streaming/ExpertStreamer.swift@@ -0,0 +1,63 @@+import Foundation++enum StreamerError: Error, CustomStringConvertible {+ case openFailed(path: String, errno: Int32)+ case sizeMismatch(expected: UInt64, actual: UInt64)+ case offsetOutOfRange(UInt64)+ case bufferWrapFailed+ case preadFailed(errno: Int32)+ case allocFailed(errno: Int32)+ case slotOutOfRange(Int)++ public var description: String {+ switch self {+ case .openFailed(let path, let error):+ return "open(\(path)) failed: errno \(error)"+ case .sizeMismatch(let expected, let actual):+ return "file size mismatch: expected \(expected), got \(actual)"+ case .offsetOutOfRange(let offset):+ return "offset \(offset) is outside the streamed range"+ case .bufferWrapFailed:+ return "failed to wrap expert cache memory in an MTLBuffer"+ case .preadFailed(let error):+ return "pread failed: errno \(error)"+ case .allocFailed(let error):+ return "posix_memalign failed: errno \(error)"+ case .slotOutOfRange(let slot):+ return "expert cache slot \(slot) is out of range"+ }+ }+}++/// Byte layout of one routed-expert layer file.+public struct StreamLayout: Sendable {+ public let path: String+ public let streamOffset: UInt64+ public let streamSize: UInt64+ public let expertsPerLayer: Int+ public let expertStride: UInt64+ public let expertOffsets: [UInt64]?++ public init(path: String,+ streamOffset: UInt64,+ streamSize: UInt64,+ expertsPerLayer: Int,+ expertStride: UInt64,+ expertOffsets: [UInt64]? = nil) {+ self.path = path+ self.streamOffset = streamOffset+ self.streamSize = streamSize+ self.expertsPerLayer = expertsPerLayer+ self.expertStride = expertStride+ self.expertOffsets = expertOffsets+ }++ @inline(__always)+ public func expertOffset(layer: Int, expert: Int) -> UInt64 {+ if layer == 0, let expertOffsets, expert >= 0, expert < expertOffsets.count {+ return expertOffsets[expert]+ }+ let perLayer = UInt64(expertsPerLayer) * expertStride+ return UInt64(layer) * perLayer + UInt64(expert) * expertStride+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift b/Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swiftnew file mode 100644index 00000000..6581d5b8--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift@@ -0,0 +1,390 @@+import Darwin+import Foundation+import Metal++public struct ExpertIOAdviceResult: Sendable, Equatable {+ public let requested: Int+ public let failed: Int+ public let calls: Int+ public let bytes: UInt64+ public let skipped: Int+ public let maxCallNanos: UInt64++ public init(requested: Int,+ failed: Int,+ calls: Int? = nil,+ bytes: UInt64 = 0,+ skipped: Int = 0,+ maxCallNanos: UInt64 = 0) {+ self.requested = requested+ self.failed = failed+ self.calls = calls ?? requested+ self.bytes = bytes+ self.skipped = skipped+ self.maxCallNanos = maxCallNanos+ }++ public static func skipped(requested: Int, bytes: UInt64 = 0) -> ExpertIOAdviceResult {+ ExpertIOAdviceResult(requested: requested,+ failed: 0,+ calls: 0,+ bytes: bytes,+ skipped: requested)+ }++}++public struct ExpertCachePlan: Sendable, Equatable {+ public let experts: [Int]+ public let assignedSlots: [Int]+ public let misses: [Int]+ public let hits: Int++ public init(experts: [Int], assignedSlots: [Int], misses: [Int], hits: Int) {+ self.experts = experts+ self.assignedSlots = assignedSlots+ self.misses = misses+ self.hits = hits+ }+}++public enum ExpertCachePolicy: String, Sendable {+ case lru+ case lfu+}++/// `pread`-based routed-expert streamer with a fixed per-layer slot cache.+public final class PreadExpertStreamer: @unchecked Sendable {+ public static let scratchAlignment = 2 * 1024 * 1024+ public static var cachePolicyDefault: ExpertCachePolicy { .lfu }++ public let layout: StreamLayout+ public let slotCount: Int+ public let cachePolicy: ExpertCachePolicy++ private let fd: Int32+ private let slotPointers: [UnsafeMutableRawPointer]+ private let slotBuffers: [MTLBuffer]++ private var nextSlot = 0+ private let cursorLock = NSLock()++ private var slotExpert: [Int]+ private var slotLastUse: [Int]+ private var expertUseCount: [Int]+ private var useClock = 0+ private let cacheLock = NSLock()++ public init(layout: StreamLayout,+ device: MTLDevice,+ slotCount: Int,+ cachePolicy: ExpertCachePolicy = .lfu) throws {+ precondition(slotCount > 0, "slotCount must be positive")+ self.layout = layout+ self.slotCount = slotCount+ self.cachePolicy = cachePolicy+ let pageSize = Int(getpagesize())++ let openedFD = open(layout.path, O_RDONLY)+ guard openedFD >= 0 else {+ throw StreamerError.openFailed(path: layout.path, errno: errno)+ }+ self.fd = openedFD++ var fileStats = stat()+ if fstat(openedFD, &fileStats) == 0 {+ let required = layout.streamOffset + layout.streamSize+ if UInt64(fileStats.st_size) < required {+ close(openedFD)+ throw StreamerError.sizeMismatch(+ expected: required,+ actual: UInt64(fileStats.st_size))+ }+ }++ let allocationSize = ((Int(layout.expertStride) + pageSize - 1) / pageSize) * pageSize+ var pointers: [UnsafeMutableRawPointer] = []+ var buffers: [MTLBuffer] = []+ pointers.reserveCapacity(slotCount)+ buffers.reserveCapacity(slotCount)++ func unwind() {+ for index in buffers.count..<pointers.count {+ free(pointers[index])+ }+ close(openedFD)+ }++ for _ in 0..<slotCount {+ var raw: UnsafeMutableRawPointer?+ let result = posix_memalign(&raw, Self.scratchAlignment, allocationSize)+ guard result == 0, let pointer = raw else {+ unwind()+ throw StreamerError.allocFailed(errno: result)+ }+ pointers.append(pointer)+ nonisolated(unsafe) let capturedPointer = pointer+ guard let buffer = device.makeBuffer(+ bytesNoCopy: pointer,+ length: allocationSize,+ options: .storageModeShared,+ deallocator: { _, _ in free(capturedPointer) })+ else {+ unwind()+ throw StreamerError.bufferWrapFailed+ }+ buffers.append(buffer)+ }++ self.slotPointers = pointers+ self.slotBuffers = buffers+ self.slotExpert = [Int](repeating: -1, count: slotCount)+ self.slotLastUse = [Int](repeating: 0, count: slotCount)+ self.expertUseCount = [Int](repeating: 0, count: max(1, layout.expertsPerLayer))+ }++ deinit {+ close(fd)+ }++ public func loadExpert(layer: Int, expert: Int) throws+ -> (buffer: MTLBuffer, offset: UInt64, size: UInt64) {+ cursorLock.lock()+ let slot = nextSlot+ nextSlot = (nextSlot + 1) % slotCount+ cursorLock.unlock()+ return try loadExpert(layer: layer, expert: expert, slot: slot)+ }++ public func loadExpert(layer: Int, expert: Int, slot: Int) throws+ -> (buffer: MTLBuffer, offset: UInt64, size: UInt64) {+ guard slot >= 0 && slot < slotCount else {+ throw StreamerError.slotOutOfRange(slot)+ }+ let regionOffset = layout.expertOffset(layer: layer, expert: expert)+ guard regionOffset + layout.expertStride <= layout.streamSize else {+ throw StreamerError.offsetOutOfRange(regionOffset)+ }+ try readFull(+ into: slotPointers[slot],+ fileOffset: layout.streamOffset + regionOffset,+ count: Int(layout.expertStride))+ return (slotBuffers[slot], 0, layout.expertStride)+ }++ public func loadExpertsCached(experts: [Int]) throws+ -> [(buffer: MTLBuffer, offset: UInt64, size: UInt64)] {+ try executeExpertCachePlan(planExpertsCached(experts: experts))+ }++ public func planExpertsCached(experts: [Int],+ avoidingSlots: Set<Int> = []) -> ExpertCachePlan {+ guard let plan = makeExpertCachePlan(experts: experts, avoidingSlots: avoidingSlots) else {+ preconditionFailure("expert cache cannot place requested misses")+ }+ return plan+ }++ public func planExpertsCachedIfPossible(experts: [Int],+ avoidingSlots: Set<Int> = []) -> ExpertCachePlan? {+ makeExpertCachePlan(experts: experts, avoidingSlots: avoidingSlots)+ }++ private func makeExpertCachePlan(experts: [Int],+ avoidingSlots rawAvoidingSlots: Set<Int>) -> ExpertCachePlan? {+ precondition(experts.count <= slotCount,+ "expert cache needs at least \(experts.count) slots")+ let avoidingSlots = Set(rawAvoidingSlots.filter { $0 >= 0 && $0 < slotCount })++ cacheLock.lock()+ defer { cacheLock.unlock() }++ let clock = useClock + 1+ var assignedSlots = [Int](repeating: -1, count: experts.count)+ var reserved = [Bool](repeating: false, count: slotCount)++ for index in experts.indices {+ for slot in 0..<slotCount+ where !reserved[slot] && slotExpert[slot] == experts[index] {+ assignedSlots[index] = slot+ reserved[slot] = true+ break+ }+ }+ for slot in avoidingSlots where !reserved[slot] {+ reserved[slot] = true+ }++ let misses = experts.indices.filter { assignedSlots[$0] == -1 }+ let evictable = (0..<slotCount)+ .filter { !reserved[$0] }+ .sorted { shouldEvictSlot($0, before: $1) }+ guard misses.count <= evictable.count else { return nil }++ useClock = clock+ for expert in experts where expert >= 0 && expert < expertUseCount.count {+ expertUseCount[expert] &+= 1+ }+ for slot in assignedSlots where slot >= 0 {+ slotLastUse[slot] = clock+ }+ for (offset, index) in misses.enumerated() {+ let slot = evictable[offset]+ assignedSlots[index] = slot+ reserved[slot] = true+ slotExpert[slot] = -1+ slotLastUse[slot] = clock+ }++ return ExpertCachePlan(+ experts: experts,+ assignedSlots: assignedSlots,+ misses: misses,+ hits: experts.count - misses.count)+ }++ public func executeExpertCachePlan(_ plan: ExpertCachePlan) throws+ -> [(buffer: MTLBuffer, offset: UInt64, size: UInt64)] {+ precondition(plan.experts.count <= slotCount,+ "expert cache plan exceeds slot count")+ precondition(plan.assignedSlots.count == plan.experts.count,+ "expert cache plan slot count mismatch")++ let errorLock = NSLock()+ nonisolated(unsafe) var firstError: Error?+ DispatchQueue.concurrentPerform(iterations: plan.misses.count) { missOffset in+ let index = plan.misses[missOffset]+ do {+ _ = try self.loadExpert(+ layer: 0,+ expert: plan.experts[index],+ slot: plan.assignedSlots[index])+ } catch {+ errorLock.lock()+ if firstError == nil { firstError = error }+ errorLock.unlock()+ }+ }+ if let firstError { throw firstError }++ cacheLock.lock()+ for index in plan.misses {+ slotExpert[plan.assignedSlots[index]] = plan.experts[index]+ }+ cacheLock.unlock()++ return expertCachePlanBuffers(plan)+ }++ public func expertCachePlanBuffers(_ plan: ExpertCachePlan)+ -> [(buffer: MTLBuffer, offset: UInt64, size: UInt64)] {+ precondition(plan.assignedSlots.count == plan.experts.count,+ "expert cache plan slot count mismatch")+ return plan.assignedSlots.map { slot in+ (slotBuffers[slot], UInt64(0), layout.expertStride)+ }+ }++ public func adviseExpertCachePlanMisses(_ plan: ExpertCachePlan) -> ExpertIOAdviceResult {+ let experts = plan.misses.map { plan.experts[$0] }+ return adviseRanges(expertAdviceRanges(experts: experts), requested: experts.count)+ }++ public func adviseExperts(experts: [Int]) -> ExpertIOAdviceResult {+ adviseRanges(expertAdviceRanges(experts: experts), requested: experts.count)+ }++ public func adviseExpertMisses(experts: [Int]) -> ExpertIOAdviceResult {+ cacheLock.lock()+ let misses = experts.filter { !slotExpert.contains($0) }+ cacheLock.unlock()+ return adviseRanges(expertAdviceRanges(experts: misses), requested: misses.count)+ }++ static func coalescedAdjacentAdviceRanges(_ ranges: [(offset: UInt64, count: UInt64)])+ -> [(offset: UInt64, count: UInt64)] {+ let sorted = ranges.filter { $0.count > 0 }.sorted {+ $0.offset == $1.offset ? $0.count < $1.count : $0.offset < $1.offset+ }+ var result: [(offset: UInt64, count: UInt64)] = []+ for range in sorted {+ guard var last = result.popLast() else {+ result.append(range)+ continue+ }+ let lastEnd = last.offset &+ last.count+ let rangeEnd = range.offset &+ range.count+ if range.offset <= lastEnd {+ last.count = max(lastEnd, rangeEnd) - last.offset+ result.append(last)+ } else {+ result.append(last)+ result.append(range)+ }+ }+ return result+ }++ private func shouldEvictSlot(_ lhs: Int, before rhs: Int) -> Bool {+ if cachePolicy == .lru {+ return slotLastUse[lhs] < slotLastUse[rhs]+ }+ let lhsExpert = slotExpert[lhs]+ let rhsExpert = slotExpert[rhs]+ if lhsExpert < 0 || rhsExpert < 0 {+ return lhsExpert < rhsExpert+ }+ let lhsCount = lhsExpert < expertUseCount.count ? expertUseCount[lhsExpert] : 0+ let rhsCount = rhsExpert < expertUseCount.count ? expertUseCount[rhsExpert] : 0+ if lhsCount != rhsCount { return lhsCount < rhsCount }+ return slotLastUse[lhs] < slotLastUse[rhs]+ }++ private func expertAdviceRanges(experts: [Int]) -> [(offset: UInt64, count: UInt64)] {+ experts.compactMap { expert in+ let regionOffset = layout.expertOffset(layer: 0, expert: expert)+ guard regionOffset + layout.expertStride <= layout.streamSize else { return nil }+ return (layout.streamOffset + regionOffset, layout.expertStride)+ }+ }++ private func adviseRanges(_ ranges: [(offset: UInt64, count: UInt64)],+ requested: Int) -> ExpertIOAdviceResult {+ let coalesced = Self.coalescedAdjacentAdviceRanges(ranges)+ var failed = 0+ var bytes: UInt64 = 0+ var maxCallNanos: UInt64 = 0+ for range in coalesced {+ let result = RDAdvice.call(fd: fd, offset: range.offset, byteCount: range.count)+ if !result.succeeded { failed += 1 }+ bytes &+= result.requestedBytes+ maxCallNanos = max(maxCallNanos, result.elapsedNanos)+ }+ return ExpertIOAdviceResult(+ requested: requested,+ failed: failed,+ calls: coalesced.count,+ bytes: bytes,+ maxCallNanos: maxCallNanos)+ }++ private func readFull(into destination: UnsafeMutableRawPointer,+ fileOffset: UInt64,+ count: Int) throws {+ var filled = 0+ while filled < count {+ let readCount = pread(+ fd,+ destination.advanced(by: filled),+ count - filled,+ off_t(fileOffset) + off_t(filled))+ if readCount < 0 {+ throw StreamerError.preadFailed(errno: errno)+ }+ if readCount == 0 {+ throw StreamerError.sizeMismatch(expected: UInt64(count), actual: UInt64(filled))+ }+ filled += readCount+ }+ }+}diff --git a/Sources/TurboFieldfare/Infrastructure/Streaming/RDAdvice.swift b/Sources/TurboFieldfare/Infrastructure/Streaming/RDAdvice.swiftnew file mode 100644index 00000000..2ba21a9f--- /dev/null+++ b/Sources/TurboFieldfare/Infrastructure/Streaming/RDAdvice.swift@@ -0,0 +1,46 @@+import Darwin+import Foundation++struct RDAdviceCallResult: Sendable, Equatable {+ let requestedBytes: UInt64+ let errnoValue: CInt+ let elapsedNanos: UInt64++ init(requestedBytes: UInt64, errnoValue: CInt, elapsedNanos: UInt64) {+ self.requestedBytes = requestedBytes+ self.errnoValue = errnoValue+ self.elapsedNanos = elapsedNanos+ }++ var succeeded: Bool { errnoValue == 0 }+}++enum RDAdvice {+ static func clippedByteCount(_ byteCount: UInt64) -> UInt64 {+ min(byteCount, UInt64(Int32.max))+ }++ static func call(fd: CInt,+ offset: UInt64,+ byteCount: UInt64) -> RDAdviceCallResult {+ let clippedCount = clippedByteCount(byteCount)+ let start = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ var errnoValue: CInt = 0++ #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)+ var advice = radvisory(+ ra_offset: off_t(offset),+ ra_count: Int32(clippedCount))+ if fcntl(fd, F_RDADVISE, &advice) != 0 {+ errnoValue = errno+ }+ #else+ errnoValue = ENOTSUP+ #endif++ return RDAdviceCallResult(+ requestedBytes: clippedCount,+ errnoValue: errnoValue,+ elapsedNanos: clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - start)+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Attention/Attention.swift b/Sources/TurboFieldfare/Kernels/Attention/Attention.swiftnew file mode 100644index 00000000..788f0886--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Attention/Attention.swift@@ -0,0 +1,631 @@+import Foundation+import Metal++struct AttentionTurboQuantKVParams {+ var headDim: UInt32+ var numQHeads: UInt32+ var numKVHeads: UInt32+ var seqLen: UInt32+ var kvStart: UInt32+ var scale: Float+ var layer: UInt32+ var rotationSeed: UInt32+ var keyBytesPerHead: UInt32+ var keyPackedOffset: UInt32+ var keyScaleOffset: UInt32+ var valueBytesPerHead: UInt32+ var valuePackedOffset: UInt32+ var valueScaleOffset: UInt32+ var qPretransformed: UInt32++ init(headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ seqLen: UInt32,+ kvStart: UInt32,+ scale: Float,+ layer: UInt32,+ rotationSeed: UInt32,+ keyLayout: TurboQuantKVRoleLayout,+ valueLayout: TurboQuantKVRoleLayout) {+ self.headDim = headDim+ self.numQHeads = numQHeads+ self.numKVHeads = numKVHeads+ self.seqLen = seqLen+ self.kvStart = kvStart+ self.scale = scale+ self.layer = layer+ self.rotationSeed = rotationSeed+ self.keyBytesPerHead = UInt32(keyLayout.bytesPerHead)+ self.keyPackedOffset = UInt32(keyLayout.packedOffsetPerHead)+ self.keyScaleOffset = UInt32(keyLayout.scaleOffsetPerHead)+ self.valueBytesPerHead = UInt32(valueLayout.bytesPerHead)+ self.valuePackedOffset = UInt32(valueLayout.packedOffsetPerHead)+ self.valueScaleOffset = UInt32(valueLayout.scaleOffsetPerHead)+ self.qPretransformed = 0+ }+}++struct AttentionSplitGeometry: Sendable, Equatable {+ let effectiveLength: Int+ let numChunks: Int+ let chunkLength: Int+ let partialThreadgroups: Int+ let useSWAGroupedPartial: Bool+}++struct AttentionTurboQuantSplitGeometry: Sendable, Equatable {+ let chunkLen: Int+ let numChunks: Int+ let partialThreadgroups: Int+ let useGQAPartial: Bool+}++/// Swift wrapper for sliding-window and full-causal decode attention.+///+/// The kernels assume a single decoded query token (`M_q = 1`) and a+/// contiguous KV cache of length `seqLen`. The MPP-tensor-core prefill path+/// (`M_q > 1`) is separate.+///+/// Buffer contracts (FP16 throughout):+/// - `q` : `[numQHeads, headDim]`+/// - `k` : `[seqLen, numKVHeads, headDim]`+/// - `v` : same shape as `k`. Full-layer K and V must remain distinct after+/// their separate per-head normalization and RoPE paths.+/// - `out` : `[numQHeads, headDim]`+final class Attention {+ private let ctx: MetalContext+ private let psoPartial: MTLComputePipelineState+ private let psoGQAPartial: MTLComputePipelineState+ private let psoCombine: MTLComputePipelineState+ private let psoMLXGeometryFullV2: MTLComputePipelineState+ private let psoPartialSWA: MTLComputePipelineState+ private let psoPartialFull: MTLComputePipelineState+ private let psoGQAPartialSWA: MTLComputePipelineState+ private let psoGQAPartialSWAChunks16: MTLComputePipelineState+ private let psoPartialFullChunks16: MTLComputePipelineState+ private let psoCombineSWA: MTLComputePipelineState+ private let psoCombineFull: MTLComputePipelineState+ private let psoCombineSWAChunks16: MTLComputePipelineState+ private let psoCombineFullChunks16: MTLComputePipelineState+ private let psoTurboQuantQTransformK4V4: MTLComputePipelineState+ private let psoTurboQuantPartialK4V4: MTLComputePipelineState+ private let psoTurboQuantGQAPartialK4V4: MTLComputePipelineState+ private let psoTurboQuantCombineK4V4: MTLComputePipelineState++ /// Mirrors `kAttnThreads` in `attention.metal`. The kernel was authored+ /// with a hardcoded 256-thread group so its threadgroup-memory scratch+ /// (q_smem[512] + reduce[8] + bcast) sizes are correct.+ static let threadsPerGroup: Int = 256++ /// Project ceilings for the split-KV partial scratch. `kAttnMaxHeadDim` in+ /// attention.metal is 512; the model has 16 Q heads; `maxChunks` bounds the+ /// split factor (and therefore the scratch size: 16·64·512 FP32 ≈ 2 MB).+ static let maxQHeads = 16+ static let maxHeadDim = 512+ static let maxChunks = 64+ /// Full attention uses 16 base chunks by default.+ private static let defaultFullChunks = 16+ private static let defaultGQASWAChunks = 8+ private static let defaultTurboQuantGQASWAChunks = 8++ // Partial state written by pass 1, read by pass 2. One shared allocation:+ // attention runs once per layer, serially, and pass 2 hazard-tracks pass 1+ // within the same command buffer — no race (mirrors MoE.routerLogits).+ private let mPartial: MTLBuffer+ private let dPartial: MTLBuffer+ private let oPartial: MTLBuffer+ private let qTurboQuant: MTLBuffer++ init(context: MetalContext) throws {+ self.ctx = context+ self.psoPartial = try context.pipeline("attention_decode_partial")+ self.psoGQAPartial = try context.pipeline("attention_decode_gqa_swa_partial")+ self.psoCombine = try context.pipeline("attention_decode_combine")+ self.psoMLXGeometryFullV2 = try context.pipeline("attention_decode_mlx_geometry_full_v2")+ self.psoTurboQuantQTransformK4V4 = try context.pipeline("attention_turboquant_q_rht")+ self.psoTurboQuantPartialK4V4 = try context.pipeline("attention_turboquant_decode_partial")+ self.psoTurboQuantGQAPartialK4V4 = try context.pipeline("attention_turboquant_decode_gqa_swa_partial")+ self.psoTurboQuantCombineK4V4 = try context.pipeline("attention_turboquant_decode_combine")+ self.psoPartialSWA = try Self.specializedPipeline(context,+ "attention_decode_partial",+ headDim: 256,+ numQHeads: 16,+ numKVHeads: 8)+ self.psoPartialFull = try Self.specializedPipeline(context,+ "attention_decode_partial",+ headDim: 512,+ numQHeads: 16,+ numKVHeads: 2)+ self.psoGQAPartialSWA = try Self.specializedPipeline(context,+ "attention_decode_gqa_swa_partial",+ headDim: 256,+ numQHeads: 16,+ numKVHeads: 8)+ self.psoGQAPartialSWAChunks16 = try Self.specializedPipeline(context,+ "attention_decode_gqa_swa_partial",+ headDim: 256,+ numQHeads: 16,+ numKVHeads: 8,+ numChunks: 16)+ self.psoPartialFullChunks16 = try Self.specializedPipeline(context,+ "attention_decode_partial",+ headDim: 512,+ numQHeads: 16,+ numKVHeads: 2,+ numChunks: 16)+ self.psoCombineSWA = try Self.specializedPipeline(context,+ "attention_decode_combine",+ headDim: 256,+ numQHeads: 16,+ numKVHeads: 8)+ self.psoCombineFull = try Self.specializedPipeline(context,+ "attention_decode_combine",+ headDim: 512,+ numQHeads: 16,+ numKVHeads: 2)+ self.psoCombineSWAChunks16 = try Self.specializedPipeline(context,+ "attention_decode_combine",+ headDim: 256,+ numQHeads: 16,+ numKVHeads: 8,+ numChunks: 16)+ self.psoCombineFullChunks16 = try Self.specializedPipeline(context,+ "attention_decode_combine",+ headDim: 512,+ numQHeads: 16,+ numKVHeads: 2,+ numChunks: 16)+ let md = Self.maxQHeads * Self.maxChunks+ guard let m = context.device.makeBuffer(length: md * MemoryLayout<Float>.size,+ options: .storageModeShared),+ let d = context.device.makeBuffer(length: md * MemoryLayout<Float>.size,+ options: .storageModeShared),+ let o = context.device.makeBuffer(length: md * Self.maxHeadDim * MemoryLayout<Float>.size,+ options: .storageModeShared),+ let tq = context.device.makeBuffer(length: Self.maxQHeads * Self.maxHeadDim * MemoryLayout<Float16>.size,+ options: .storageModeShared) else {+ throw MetalError.missingFunction("attention split-KV scratch")+ }+ self.mPartial = m; self.dPartial = d; self.oPartial = o+ self.qTurboQuant = tq+ }++ /// Number of K/V chunks for a range of `effLen` positions — the split+ /// factor used by the production split path.+ static func chunkCount(effLen: Int, preferGQASWA: Bool = false) -> Int {+ let eff = max(1, effLen)+ let defaultChunks = preferGQASWA ? defaultGQASWAChunks : defaultFullChunks+ return max(1, min(defaultChunks, min(maxChunks, eff)))+ }++ static func splitGeometry(numQHeads: UInt32,+ numKVHeads: UInt32,+ seqLen: UInt32,+ kvStart: UInt32,+ preferGQASWA: Bool) -> AttentionSplitGeometry {+ let qPerKV = Int(numQHeads / numKVHeads)+ let useSWAGQAPartial = preferGQASWA && qPerKV <= 2+ let effectiveLength = Int(seqLen) - Int(kvStart)+ let baseChunks = Self.chunkCount(effLen: effectiveLength,+ preferGQASWA: useSWAGQAPartial)+ let numChunks = useSWAGQAPartial+ ? max(baseChunks, min(Self.maxChunks, baseChunks * qPerKV))+ : baseChunks+ let chunkLength = (max(1, effectiveLength) + numChunks - 1) / numChunks+ let partialHeadGroups = useSWAGQAPartial ? Int(numKVHeads) : Int(numQHeads)+ return AttentionSplitGeometry(effectiveLength: effectiveLength,+ numChunks: numChunks,+ chunkLength: chunkLength,+ partialThreadgroups: partialHeadGroups * numChunks,+ useSWAGroupedPartial: useSWAGQAPartial)+ }++ static func turboQuantChunkCount(effLen: Int, preferGQASWA: Bool = false) -> Int {+ let eff = max(1, effLen)+ let defaultChunks = preferGQASWA ? defaultTurboQuantGQASWAChunks : defaultFullChunks+ return max(1, min(defaultChunks, min(maxChunks, eff)))+ }++ static func turboQuantSplitGeometry(+ params: AttentionTurboQuantKVParams+ ) -> AttentionTurboQuantSplitGeometry {+ precondition(params.numQHeads % params.numKVHeads == 0,+ "numQHeads must be a multiple of numKVHeads for GQA")+ let qPerKV = Int(params.numQHeads / params.numKVHeads)+ let useGQAPartial = qPerKV <= 2+ let effLen = Int(params.seqLen - params.kvStart)+ let baseChunks = Self.turboQuantChunkCount(effLen: effLen,+ preferGQASWA: useGQAPartial)+ let nChunks = useGQAPartial+ ? max(baseChunks, min(Self.maxChunks, baseChunks * qPerKV))+ : baseChunks+ let chunkLen = (max(1, effLen) + nChunks - 1) / nChunks+ let partialGroups = (useGQAPartial ? Int(params.numKVHeads) : Int(params.numQHeads)) * nChunks+ return AttentionTurboQuantSplitGeometry(chunkLen: chunkLen,+ numChunks: nChunks,+ partialThreadgroups: partialGroups,+ useGQAPartial: useGQAPartial)+ }++ /// Sliding-window attention. `window` caps the K/V positions to the most+ /// recent `window` entries (`[max(0, seqLen-window), seqLen)`).+ /// `scale` defaults to `rsqrt(head_dim)` for generic callers;+ /// Gemma 4 callers pass 1.0 because the model's configured attention scale+ /// is 1.0.+ func encodeSWA(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer, qOffset: Int = 0,+ k: MTLBuffer, kOffset: Int = 0,+ v: MTLBuffer, vOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ seqLen: UInt32,+ window: UInt32,+ scale: Float? = nil,+ ringCapacity: UInt32 = 0) {+ precondition(numQHeads % numKVHeads == 0,+ "numQHeads must be a multiple of numKVHeads for GQA")+ precondition(headDim <= 512,+ "head_dim must be <= 512 (kernel scratch is sized for the full-attn case)")+ let sc = scale ?? Self.defaultScale(headDim: headDim)+ let kvStart = seqLen > window ? seqLen - window : 0++ encodeSplit(commandBuffer: commandBuffer,+ q: q, qOffset: qOffset, k: k, kOffset: kOffset,+ v: v, vOffset: vOffset, out: out, outOffset: outOffset,+ headDim: headDim, numQHeads: numQHeads, numKVHeads: numKVHeads,+ seqLen: seqLen, kvStart: kvStart, scale: sc,+ preferGQASWA: true,+ ringCapacity: ringCapacity)+ }++ /// Full attention. Gemma 4 reuses the raw K projection as raw V input, but+ /// separate normalization and RoPE make the cache streams distinct here.+ /// `scale` mirrors `encodeSWA`.+ func encodeFull(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer, qOffset: Int = 0,+ k: MTLBuffer, kOffset: Int = 0,+ v: MTLBuffer, vOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ seqLen: UInt32,+ scale: Float? = nil) {+ precondition(numQHeads % numKVHeads == 0,+ "numQHeads must be a multiple of numKVHeads for GQA")+ precondition(headDim <= 512,+ "head_dim must be <= 512 (kernel scratch is sized for the full-attn case)")+ precondition(seqLen > 0, "full attention requires at least one KV position")+ let sc = scale ?? Self.defaultScale(headDim: headDim)++ if headDim == 512,+ numQHeads == 16,+ numKVHeads == 2,+ sc == 1.0,+ psoMLXGeometryFullV2.maxTotalThreadsPerThreadgroup >= 1024 {+ encodeMLXGeometryFullV2(commandBuffer: commandBuffer,+ pipeline: psoMLXGeometryFullV2,+ q: q, qOffset: qOffset,+ k: k, kOffset: kOffset,+ v: v, vOffset: vOffset,+ out: out, outOffset: outOffset,+ seqLen: seqLen,+ scale: sc)+ return+ }++ encodeSplit(commandBuffer: commandBuffer,+ q: q, qOffset: qOffset, k: k, kOffset: kOffset,+ v: v, vOffset: vOffset, out: out, outOffset: outOffset,+ headDim: headDim, numQHeads: numQHeads, numKVHeads: numKVHeads,+ seqLen: seqLen, kvStart: 0, scale: sc,+ preferGQASWA: false)+ }++ private func encodeMLXGeometryFullV2(commandBuffer: MTLCommandBuffer,+ pipeline: MTLComputePipelineState,+ q: MTLBuffer, qOffset: Int,+ k: MTLBuffer, kOffset: Int,+ v: MTLBuffer, vOffset: Int,+ out: MTLBuffer, outOffset: Int,+ seqLen: UInt32,+ scale: Float) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pipeline)+ enc.setBuffer(q, offset: qOffset, index: 0)+ enc.setBuffer(k, offset: kOffset, index: 1)+ enc.setBuffer(v, offset: vOffset, index: 2)+ enc.setBuffer(out, offset: outOffset, index: 3)+ var length = seqLen+ var scoreScale = scale+ enc.setBytes(&length, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&scoreScale, length: MemoryLayout<Float>.size, index: 5)+ enc.dispatchThreadgroups(MTLSize(width: 16, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 1024,+ height: 1,+ depth: 1))+ enc.endEncoding()+ }++ /// Split-KV packed-TurboQuant attention. Pass 1 computes per-chunk online+ /// softmax state in RHT domain; pass 2 merges chunks and inverse-RHTs once.+ func encodeTurboQuantSplit(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer, qOffset: Int = 0,+ keyCache: MTLBuffer, keyCacheOffset: Int = 0,+ valueCache: MTLBuffer, valueCacheOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ params: AttentionTurboQuantKVParams) {+ precondition(params.numQHeads % params.numKVHeads == 0,+ "numQHeads must be a multiple of numKVHeads for GQA")+ precondition(Int(params.numQHeads) <= Self.maxQHeads,+ "numQHeads \(params.numQHeads) exceeds split-KV scratch (max \(Self.maxQHeads))")+ precondition(Int(params.headDim) <= Self.maxHeadDim,+ "head_dim \(params.headDim) exceeds split-KV scratch (max \(Self.maxHeadDim))")+ precondition(params.kvStart <= params.seqLen,+ "kvStart must be inside the KV range")++ let geometry = Self.turboQuantSplitGeometry(params: params)++ encodeTurboQuantQTransform(commandBuffer: commandBuffer,+ q: q,+ qOffset: qOffset,+ params: params)++ encodeTurboQuantPartial(commandBuffer: commandBuffer,+ keyCache: keyCache,+ keyCacheOffset: keyCacheOffset,+ valueCache: valueCache,+ valueCacheOffset: valueCacheOffset,+ params: params,+ geometry: geometry)++ encodeTurboQuantCombine(commandBuffer: commandBuffer,+ out: out,+ outOffset: outOffset,+ params: params,+ geometry: geometry)+ }++ func encodeTurboQuantQTransform(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer,+ qOffset: Int = 0,+ params: AttentionTurboQuantKVParams) {+ guard let qEnc = commandBuffer.makeComputeCommandEncoder() else { return }+ let qTransformPSO = psoTurboQuantQTransformK4V4+ qEnc.setComputePipelineState(qTransformPSO)+ qEnc.setBuffer(q, offset: qOffset, index: 0)+ qEnc.setBuffer(qTurboQuant, offset: 0, index: 1)+ var qParams = params+ qEnc.setBytes(&qParams, length: MemoryLayout<AttentionTurboQuantKVParams>.size, index: 2)+ let qTGWidth = min(Self.threadsPerGroup,+ Int(qTransformPSO.maxTotalThreadsPerThreadgroup))+ qEnc.dispatchThreadgroups(MTLSize(width: Int(params.numQHeads), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: qTGWidth,+ height: 1,+ depth: 1))+ qEnc.endEncoding()+ }++ func encodeTurboQuantPartial(commandBuffer: MTLCommandBuffer,+ keyCache: MTLBuffer,+ keyCacheOffset: Int = 0,+ valueCache: MTLBuffer,+ valueCacheOffset: Int = 0,+ params: AttentionTurboQuantKVParams,+ geometry: AttentionTurboQuantSplitGeometry) {+ guard let p1 = commandBuffer.makeComputeCommandEncoder() else { return }+ p1.setComputePipelineState(+ geometry.useGQAPartial ? psoTurboQuantGQAPartialK4V4 : psoTurboQuantPartialK4V4)+ p1.setBuffer(qTurboQuant, offset: 0, index: 0)+ p1.setBuffer(keyCache, offset: keyCacheOffset, index: 1)+ p1.setBuffer(valueCache, offset: valueCacheOffset, index: 2)+ p1.setBuffer(mPartial, offset: 0, index: 3)+ p1.setBuffer(dPartial, offset: 0, index: 4)+ p1.setBuffer(oPartial, offset: 0, index: 5)+ var p = params+ p.qPretransformed = 1+ var cl = UInt32(geometry.chunkLen)+ var nc = UInt32(geometry.numChunks)+ p1.setBytes(&p, length: MemoryLayout<AttentionTurboQuantKVParams>.size, index: 6)+ p1.setBytes(&cl, length: MemoryLayout<UInt32>.size, index: 7)+ p1.setBytes(&nc, length: MemoryLayout<UInt32>.size, index: 8)+ let partialTGWidth = min(Self.threadsPerGroup,+ Int(psoTurboQuantPartialK4V4.maxTotalThreadsPerThreadgroup))+ p1.dispatchThreadgroups(MTLSize(width: geometry.partialThreadgroups,+ height: 1,+ depth: 1),+ threadsPerThreadgroup: MTLSize(width: partialTGWidth,+ height: 1,+ depth: 1))+ p1.endEncoding()+ }++ func encodeTurboQuantCombine(commandBuffer: MTLCommandBuffer,+ out: MTLBuffer,+ outOffset: Int = 0,+ params: AttentionTurboQuantKVParams,+ geometry: AttentionTurboQuantSplitGeometry) {+ guard let p2 = commandBuffer.makeComputeCommandEncoder() else { return }+ let combinePSO = psoTurboQuantCombineK4V4+ p2.setComputePipelineState(combinePSO)+ p2.setBuffer(mPartial, offset: 0, index: 0)+ p2.setBuffer(dPartial, offset: 0, index: 1)+ p2.setBuffer(oPartial, offset: 0, index: 2)+ p2.setBuffer(out, offset: outOffset, index: 3)+ var p = params+ p.qPretransformed = 1+ var nc = UInt32(geometry.numChunks)+ p2.setBytes(&p, length: MemoryLayout<AttentionTurboQuantKVParams>.size, index: 4)+ p2.setBytes(&nc, length: MemoryLayout<UInt32>.size, index: 5)+ let combineTGWidth = min(Self.threadsPerGroup,+ Int(combinePSO.maxTotalThreadsPerThreadgroup))+ p2.dispatchThreadgroups(MTLSize(width: Int(params.numQHeads), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: combineTGWidth,+ height: 1,+ depth: 1))+ p2.endEncoding()+ }++ /// Two-pass split-KV (Flash-Decoding) dispatch shared by SWA and full+ /// attention — they differ only by `kvStart`. Pass 1 fans the head's+ /// `[kvStart, seqLen)` range across `chunkCount` threadgroups per head;+ /// pass 2 merges the partials. Both encoders go on the same command buffer+ /// so pass 2 hazard-tracks the partial scratch written by pass 1.+ private func encodeSplit(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer, qOffset: Int,+ k: MTLBuffer, kOffset: Int,+ v: MTLBuffer, vOffset: Int,+ out: MTLBuffer, outOffset: Int,+ headDim: UInt32, numQHeads: UInt32, numKVHeads: UInt32,+ seqLen: UInt32, kvStart: UInt32, scale: Float,+ preferGQASWA: Bool,+ ringCapacity: UInt32 = 0) {+ precondition(Int(numQHeads) <= Self.maxQHeads,+ "numQHeads \(numQHeads) exceeds split-KV scratch (max \(Self.maxQHeads))")+ precondition(Int(headDim) <= Self.maxHeadDim,+ "head_dim \(headDim) exceeds split-KV scratch (max \(Self.maxHeadDim))")+ precondition(ringCapacity == 0 || preferGQASWA,+ "FP16 KV ring is only valid for SWA attention")+ let geometry = Self.splitGeometry(numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ seqLen: seqLen,+ kvStart: kvStart,+ preferGQASWA: preferGQASWA)+ let useSWAGQAPartial = geometry.useSWAGroupedPartial+ let nChunks = geometry.numChunks+ let chunkLen = geometry.chunkLength+ let partialPSO = partialPipeline(headDim: headDim,+ numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ numChunks: nChunks,+ useGQAPartial: useSWAGQAPartial,+ ringCapacity: ringCapacity)+ let tgWidth = min(Self.threadsPerGroup, Int(partialPSO.maxTotalThreadsPerThreadgroup))++ guard let p1 = commandBuffer.makeComputeCommandEncoder() else { return }+ p1.setComputePipelineState(partialPSO)+ p1.setBuffer(q, offset: qOffset, index: 0)+ p1.setBuffer(k, offset: kOffset, index: 1)+ p1.setBuffer(v, offset: vOffset, index: 2)+ p1.setBuffer(mPartial, offset: 0, index: 3)+ p1.setBuffer(dPartial, offset: 0, index: 4)+ p1.setBuffer(oPartial, offset: 0, index: 5)+ var hd = headDim, nq = numQHeads, nkv = numKVHeads, sl = seqLen, ks = kvStart+ var cl = UInt32(chunkLen), nc = UInt32(nChunks), sc = scale+ p1.setBytes(&hd, length: MemoryLayout<UInt32>.size, index: 6)+ p1.setBytes(&nq, length: MemoryLayout<UInt32>.size, index: 7)+ p1.setBytes(&nkv, length: MemoryLayout<UInt32>.size, index: 8)+ p1.setBytes(&sl, length: MemoryLayout<UInt32>.size, index: 9)+ p1.setBytes(&ks, length: MemoryLayout<UInt32>.size, index: 10)+ p1.setBytes(&cl, length: MemoryLayout<UInt32>.size, index: 11)+ p1.setBytes(&nc, length: MemoryLayout<UInt32>.size, index: 12)+ p1.setBytes(&sc, length: MemoryLayout<Float>.size, index: 13)+ let partialGroups = geometry.partialThreadgroups+ p1.dispatchThreadgroups(MTLSize(width: partialGroups, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: tgWidth, height: 1, depth: 1))+ p1.endEncoding()++ guard let p2 = commandBuffer.makeComputeCommandEncoder() else { return }+ let combinePSO = combinePipeline(headDim: headDim,+ numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ numChunks: nChunks)+ p2.setComputePipelineState(combinePSO)+ p2.setBuffer(mPartial, offset: 0, index: 0)+ p2.setBuffer(dPartial, offset: 0, index: 1)+ p2.setBuffer(oPartial, offset: 0, index: 2)+ p2.setBuffer(out, offset: outOffset, index: 3)+ var hd2 = headDim, nc2 = UInt32(nChunks)+ p2.setBytes(&hd2, length: MemoryLayout<UInt32>.size, index: 4)+ p2.setBytes(&nc2, length: MemoryLayout<UInt32>.size, index: 5)+ let combineTGWidth = min(Self.threadsPerGroup,+ Int(combinePSO.maxTotalThreadsPerThreadgroup))+ p2.dispatchThreadgroups(MTLSize(width: Int(numQHeads), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: combineTGWidth, height: 1, depth: 1))+ p2.endEncoding()+ }++ /// `1 / sqrt(head_dim)` — the classic transformer scaling. Used as the+ /// default for non-Gemma callers (and for the existing tests that pre-date+ /// the runtime scale arg).+ static func defaultScale(headDim: UInt32) -> Float {+ Float(1.0) / Float(headDim).squareRoot()+ }++ private static func specializedPipeline(_ context: MetalContext,+ _ name: String,+ headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ numChunks: UInt32? = nil,+ ringCapacity: UInt32? = nil) throws -> MTLComputePipelineState {+ var constants = [+ MetalFunctionConstant(index: 60, value: .uint32(headDim)),+ MetalFunctionConstant(index: 61, value: .uint32(numQHeads)),+ MetalFunctionConstant(index: 62, value: .uint32(numKVHeads)),+ MetalFunctionConstant(index: 63, value: .bool(true)),+ ]+ if let numChunks {+ constants.append(MetalFunctionConstant(index: 65, value: .uint32(numChunks)))+ }+ if let ringCapacity {+ constants.append(MetalFunctionConstant(index: 69, value: .uint32(ringCapacity)))+ }+ return try context.pipeline(name, constants: constants)+ }++ private func partialPipeline(headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ numChunks: Int,+ useGQAPartial: Bool,+ ringCapacity: UInt32 = 0) -> MTLComputePipelineState {+ if ringCapacity > 0 {+ let name = useGQAPartial ? "attention_decode_gqa_swa_partial" : "attention_decode_partial"+ let specializedChunks = numChunks == 16 ? Optional(UInt32(numChunks)) : nil+ do {+ return try Self.specializedPipeline(ctx,+ name,+ headDim: headDim,+ numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ numChunks: specializedChunks,+ ringCapacity: ringCapacity)+ } catch {+ preconditionFailure("failed to build FP16 KV ring attention pipeline: \(error)")+ }+ }+ if useGQAPartial && headDim == 256 && numQHeads == 16 && numKVHeads == 8 {+ if numChunks == 16 {+ return psoGQAPartialSWAChunks16+ }+ return psoGQAPartialSWA+ }+ if !useGQAPartial && headDim == 256 && numQHeads == 16 && numKVHeads == 8 {+ return psoPartialSWA+ }+ if !useGQAPartial && headDim == 512 && numQHeads == 16 && numKVHeads == 2 {+ if numChunks == 16 {+ return psoPartialFullChunks16+ }+ return psoPartialFull+ }+ return useGQAPartial ? psoGQAPartial : psoPartial+ }++ private func combinePipeline(headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ numChunks: Int) -> MTLComputePipelineState {+ if headDim == 256 && numQHeads == 16 && numKVHeads == 8 {+ return numChunks == 16 ? psoCombineSWAChunks16 : psoCombineSWA+ }+ if headDim == 512 && numQHeads == 16 && numKVHeads == 2 {+ return numChunks == 16 ? psoCombineFullChunks16 : psoCombineFull+ }+ return psoCombine+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swiftnew file mode 100644index 00000000..fcd7fafd--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift@@ -0,0 +1,205 @@+import Foundation+import Metal++struct PrefillAttentionParams: Sendable, Equatable {+ var startPosition: UInt32+ var queryCount: UInt32+ var headDim: UInt32+ var numQHeads: UInt32+ var numKVHeads: UInt32+ var kvValidCount: UInt32+ var slidingWindow: UInt32+ var kvTokenStrideElements: UInt32+ var qTokenStrideElements: UInt32+ var oTokenStrideElements: UInt32+ var scale: Float++ init(startPosition: UInt32,+ queryCount: UInt32,+ headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ kvValidCount: UInt32,+ slidingWindow: UInt32,+ kvTokenStrideElements: UInt32,+ qTokenStrideElements: UInt32,+ oTokenStrideElements: UInt32,+ scale: Float) {+ self.startPosition = startPosition+ self.queryCount = queryCount+ self.headDim = headDim+ self.numQHeads = numQHeads+ self.numKVHeads = numKVHeads+ self.kvValidCount = kvValidCount+ self.slidingWindow = slidingWindow+ self.kvTokenStrideElements = kvTokenStrideElements+ self.qTokenStrideElements = qTokenStrideElements+ self.oTokenStrideElements = oTokenStrideElements+ self.scale = scale+ }+}++struct PrefillTurboQuantAttentionParams: Sendable, Equatable {+ var startPosition: UInt32+ var queryCount: UInt32+ var headDim: UInt32+ var numQHeads: UInt32+ var numKVHeads: UInt32+ var kvValidCount: UInt32+ var slidingWindow: UInt32+ var qTokenStrideElements: UInt32+ var oTokenStrideElements: UInt32+ var scale: Float+ var layer: UInt32+ var rotationSeed: UInt32+ var keyBytesPerHead: UInt32+ var keyPackedOffset: UInt32+ var keyScaleOffset: UInt32+ var valueBytesPerHead: UInt32+ var valuePackedOffset: UInt32+ var valueScaleOffset: UInt32++ init(prefill: PrefillAttentionParams,+ layer: UInt32,+ rotationSeed: UInt32,+ keyLayout: TurboQuantKVRoleLayout,+ valueLayout: TurboQuantKVRoleLayout) {+ self.startPosition = prefill.startPosition+ self.queryCount = prefill.queryCount+ self.headDim = prefill.headDim+ self.numQHeads = prefill.numQHeads+ self.numKVHeads = prefill.numKVHeads+ self.kvValidCount = prefill.kvValidCount+ self.slidingWindow = prefill.slidingWindow+ self.qTokenStrideElements = prefill.qTokenStrideElements+ self.oTokenStrideElements = prefill.oTokenStrideElements+ self.scale = prefill.scale+ self.layer = layer+ self.rotationSeed = rotationSeed+ self.keyBytesPerHead = UInt32(keyLayout.bytesPerHead)+ self.keyPackedOffset = UInt32(keyLayout.packedOffsetPerHead)+ self.keyScaleOffset = UInt32(keyLayout.scaleOffsetPerHead)+ self.valueBytesPerHead = UInt32(valueLayout.bytesPerHead)+ self.valuePackedOffset = UInt32(valueLayout.packedOffsetPerHead)+ self.valueScaleOffset = UInt32(valueLayout.scaleOffsetPerHead)+ }+}++final class PrefillAttention {+ private let context: MetalContext+ private let psoCausalTiled: MTLComputePipelineState+ private let psoCausalTurboQuantTiled: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.context = context+ self.psoCausalTiled = try context.pipeline("attention_prefill_causal_tiled")+ self.psoCausalTurboQuantTiled = try context.pipeline("attention_prefill_turboquant_causal_tiled")+ }++ func encodeCausal(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer, qOffset: Int = 0,+ k: MTLBuffer, kOffset: Int = 0,+ v: MTLBuffer, vOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ params: PrefillAttentionParams,+ kvRingCapacity: UInt32 = 0) {+ validate(params)++ let pipeline = causalTiledPipeline(kvRingCapacity: kvRingCapacity)+ let headDim = Int(params.headDim)+ let threadWidth = max(1, pipeline.threadExecutionWidth)+ let threadCount = roundUp(max(threadWidth, headDim), toMultipleOf: threadWidth)+ precondition(threadCount <= pipeline.maxTotalThreadsPerThreadgroup,+ "tiled prefill attention requires headDim <= maxTotalThreadsPerThreadgroup")++ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pipeline)+ enc.setBuffer(q, offset: qOffset, index: 0)+ enc.setBuffer(k, offset: kOffset, index: 1)+ enc.setBuffer(v, offset: vOffset, index: 2)+ enc.setBuffer(out, offset: outOffset, index: 3)+ var p = params+ enc.setBytes(&p, length: MemoryLayout<PrefillAttentionParams>.stride, index: 4)+ enc.dispatchThreadgroups(+ MTLSize(width: Int(params.queryCount), height: Int(params.numQHeads), depth: 1),+ threadsPerThreadgroup: MTLSize(width: threadCount, height: 1, depth: 1))+ enc.endEncoding()+ }++ func encodeTurboQuantCausal(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer, qOffset: Int = 0,+ keyCache: MTLBuffer, keyCacheOffset: Int = 0,+ valueCache: MTLBuffer, valueCacheOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ params: PrefillTurboQuantAttentionParams) {+ validateTurboQuant(params)++ let threadWidth = max(1, psoCausalTurboQuantTiled.threadExecutionWidth)+ let threadCount = roundUp(max(threadWidth, min(Int(params.headDim), 256)),+ toMultipleOf: threadWidth)+ precondition(threadCount <= psoCausalTurboQuantTiled.maxTotalThreadsPerThreadgroup,+ "TurboQuant prefill attention requires headDim <= maxTotalThreadsPerThreadgroup")++ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(psoCausalTurboQuantTiled)+ enc.setBuffer(q, offset: qOffset, index: 0)+ enc.setBuffer(keyCache, offset: keyCacheOffset, index: 1)+ enc.setBuffer(valueCache, offset: valueCacheOffset, index: 2)+ enc.setBuffer(out, offset: outOffset, index: 3)+ var p = params+ enc.setBytes(&p, length: MemoryLayout<PrefillTurboQuantAttentionParams>.stride, index: 4)+ enc.dispatchThreadgroups(+ MTLSize(width: Int(params.queryCount), height: Int(params.numQHeads), depth: 1),+ threadsPerThreadgroup: MTLSize(width: threadCount, height: 1, depth: 1))+ enc.endEncoding()+ }++ private func validate(_ params: PrefillAttentionParams) {+ precondition(params.headDim > 0, "headDim must be positive")+ precondition(params.queryCount > 0, "queryCount must be positive")+ precondition(params.numQHeads > 0, "numQHeads must be positive")+ precondition(params.numKVHeads > 0, "numKVHeads must be positive")+ precondition(params.numQHeads % params.numKVHeads == 0,+ "numQHeads must be divisible by numKVHeads")+ precondition(params.qTokenStrideElements >= params.numQHeads * params.headDim,+ "q token stride is too small")+ precondition(params.oTokenStrideElements >= params.numQHeads * params.headDim,+ "output token stride is too small")+ precondition(params.kvTokenStrideElements >= params.numKVHeads * params.headDim,+ "KV token stride is too small")+ precondition(params.startPosition + params.queryCount <= params.kvValidCount,+ "kvValidCount must include all in-flight query rows")+ }++ private func validateTurboQuant(_ params: PrefillTurboQuantAttentionParams) {+ precondition(params.headDim > 0, "headDim must be positive")+ precondition(params.queryCount > 0, "queryCount must be positive")+ precondition(params.numQHeads > 0, "numQHeads must be positive")+ precondition(params.numKVHeads > 0, "numKVHeads must be positive")+ precondition(params.numQHeads % params.numKVHeads == 0,+ "numQHeads must be divisible by numKVHeads")+ precondition(params.qTokenStrideElements >= params.numQHeads * params.headDim,+ "q token stride is too small")+ precondition(params.oTokenStrideElements >= params.numQHeads * params.headDim,+ "output token stride is too small")+ precondition(params.keyBytesPerHead > 0, "key bytes per head must be positive")+ precondition(params.valueBytesPerHead > 0, "value bytes per head must be positive")+ precondition(params.startPosition + params.queryCount <= params.kvValidCount,+ "kvValidCount must include all in-flight query rows")+ }++ private func roundUp(_ value: Int, toMultipleOf multiple: Int) -> Int {+ ((value + multiple - 1) / multiple) * multiple+ }++ private func causalTiledPipeline(kvRingCapacity: UInt32) -> MTLComputePipelineState {+ guard kvRingCapacity > 0 else { return psoCausalTiled }+ do {+ return try context.pipeline(+ "attention_prefill_causal_tiled",+ constants: [MetalFunctionConstant(index: 76, value: .uint32(kvRingCapacity))])+ } catch {+ preconditionFailure("failed to build FP16 KV ring prefill attention pipeline: \(error)")+ }+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Fusions/FusedLayerTail.swift b/Sources/TurboFieldfare/Kernels/Fusions/FusedLayerTail.swiftnew file mode 100644index 00000000..c254322b--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Fusions/FusedLayerTail.swift@@ -0,0 +1,57 @@+import Foundation+import Metal++/// Single-kernel Gemma 4 decoder-layer tail.+///+/// Equivalent to:+/// h2 = rmsnorm_bf16w(h2, post_feedforward_layernorm_2)+/// h12 = h1 + h2+/// h12 = rmsnorm_bf16w(h12, post_feedforward_layernorm)+/// hidden = (hidden + h12) * layer_scalar+final class FusedLayerTail {+ private let pso: MTLComputePipelineState+ private let specializedPSO: MTLComputePipelineState?++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("fused_layer_tail")+ self.specializedPSO = try? context.pipeline(+ "fused_layer_tail",+ constants: [+ MetalFunctionConstant(index: 80, value: .uint32(2816)),+ MetalFunctionConstant(index: 86, value: .bool(true)),+ ])+ }++ func encode(commandBuffer cb: MTLCommandBuffer,+ h2: MTLBuffer,+ h1: MTLBuffer,+ hidden: MTLBuffer,+ postFFN2Weight: MTLBuffer,+ postFFN2WeightOffset: Int = 0,+ postFFNWeight: MTLBuffer,+ postFFNWeightOffset: Int = 0,+ d: UInt32,+ eps: Float,+ layerScalar: Float) {+ precondition(d <= 4096,+ "D > 4096 exceeds the fused-tail threadgroup scratch (kFusedMaxD)")+ guard let enc = cb.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState((d == 2816 ? specializedPSO : nil) ?? pso)+ enc.setBuffer(h2, offset: 0, index: 0)+ enc.setBuffer(h1, offset: 0, index: 1)+ enc.setBuffer(hidden, offset: 0, index: 2)+ enc.setBuffer(postFFN2Weight, offset: postFFN2WeightOffset, index: 3)+ enc.setBuffer(postFFNWeight, offset: postFFNWeightOffset, index: 4)+ var dVar = d+ var epsVar = eps+ var scaleVar = layerScalar+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 6)+ enc.setBytes(&scaleVar, length: MemoryLayout<Float>.size, index: 7)++ let threads = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ enc.dispatchThreads(MTLSize(width: threads, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Fusions/FusedPostAttentionSetup.swift b/Sources/TurboFieldfare/Kernels/Fusions/FusedPostAttentionSetup.swiftnew file mode 100644index 00000000..15bb4274--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Fusions/FusedPostAttentionSetup.swift@@ -0,0 +1,62 @@+import Foundation+import Metal++/// Single-kernel Gemma 4 post-attention setup.+///+/// Equivalent to:+/// attn = rmsnorm_bf16w(attn, post_attention_norm)+/// hidden = hidden + attn+/// dense_x = rmsnorm_bf16w(hidden, pre_feedforward_layernorm)+/// routed_x = rmsnorm_bf16w(hidden, pre_feedforward_layernorm_2)+/// router_x = rmsnorm_no_scale(hidden)+final class FusedPostAttentionSetup {+ private let pso: MTLComputePipelineState+ private let specializedPSO: MTLComputePipelineState?++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("fused_post_attn_setup")+ self.specializedPSO = try? context.pipeline(+ "fused_post_attn_setup",+ constants: [+ MetalFunctionConstant(index: 80, value: .uint32(2816)),+ MetalFunctionConstant(index: 86, value: .bool(true)),+ ])+ }++ func encode(commandBuffer cb: MTLCommandBuffer,+ hidden: MTLBuffer,+ attn: MTLBuffer,+ denseX: MTLBuffer,+ routedX: MTLBuffer,+ routerX: MTLBuffer,+ postAttentionWeight: MTLBuffer,+ postAttentionWeightOffset: Int = 0,+ preFFNWeight: MTLBuffer,+ preFFNWeightOffset: Int = 0,+ preFFN2Weight: MTLBuffer,+ preFFN2WeightOffset: Int = 0,+ d: UInt32,+ eps: Float) {+ precondition(d <= 4096,+ "D > 4096 exceeds the fused post-attention setup scratch")+ guard let enc = cb.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState((d == 2816 ? specializedPSO : nil) ?? pso)+ enc.setBuffer(hidden, offset: 0, index: 0)+ enc.setBuffer(attn, offset: 0, index: 1)+ enc.setBuffer(denseX, offset: 0, index: 2)+ enc.setBuffer(routedX, offset: 0, index: 3)+ enc.setBuffer(routerX, offset: 0, index: 4)+ enc.setBuffer(postAttentionWeight, offset: postAttentionWeightOffset, index: 5)+ enc.setBuffer(preFFNWeight, offset: preFFNWeightOffset, index: 6)+ enc.setBuffer(preFFN2Weight, offset: preFFN2WeightOffset, index: 7)+ var dVar = d+ var epsVar = eps+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 8)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 9)++ let threads = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ enc.dispatchThreads(MTLSize(width: threads, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Fusions/FusedQKVEpilogue.swift b/Sources/TurboFieldfare/Kernels/Fusions/FusedQKVEpilogue.swiftnew file mode 100644index 00000000..af6207e7--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Fusions/FusedQKVEpilogue.swift@@ -0,0 +1,96 @@+import Foundation+import Metal++/// Single-kernel Gemma 4 Q/K/V epilogue.+///+/// Equivalent to:+/// Q = rmsnorm_bf16w_perhead(Q, q_norm); rope_neox(Q)+/// K = rmsnorm_bf16w_perhead(K, k_norm); rope_neox(K)+/// V = rmsnorm_no_scale_perhead(V)+final class FusedQKVEpilogue {+ private struct Shape: Hashable {+ var headDim: UInt32+ var numQHeads: UInt32+ var numKVHeads: UInt32+ var rotatedPairs: UInt32+ }++ private let pso: MTLComputePipelineState+ private let specializedPSOs: [Shape: MTLComputePipelineState]+ private static let realDecodeShapes: [Shape] = [+ Shape(headDim: 256, numQHeads: 16, numKVHeads: 8, rotatedPairs: 128),+ Shape(headDim: 512, numQHeads: 16, numKVHeads: 2, rotatedPairs: 64),+ ]++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("fused_qkv_epilogue")+ var variants: [Shape: MTLComputePipelineState] = [:]+ for shape in Self.realDecodeShapes {+ variants[shape] = try context.pipeline(+ "fused_qkv_epilogue",+ constants: [+ MetalFunctionConstant(index: 82, value: .uint32(shape.headDim)),+ MetalFunctionConstant(index: 83, value: .uint32(shape.numQHeads)),+ MetalFunctionConstant(index: 84, value: .uint32(shape.numKVHeads)),+ MetalFunctionConstant(index: 85, value: .uint32(shape.rotatedPairs)),+ MetalFunctionConstant(index: 86, value: .bool(true)),+ ])+ }+ self.specializedPSOs = variants+ }++ func encode(commandBuffer cb: MTLCommandBuffer,+ q: MTLBuffer,+ qOffset: Int = 0,+ k: MTLBuffer,+ kOffset: Int = 0,+ v: MTLBuffer,+ vOffset: Int = 0,+ qWeight: MTLBuffer,+ qWeightOffset: Int = 0,+ kWeight: MTLBuffer,+ kWeightOffset: Int = 0,+ headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ position: UInt32,+ theta: Float,+ rotatedPairs: UInt32,+ eps: Float) {+ precondition(headDim <= 512,+ "headDim > 512 exceeds the fused QKV epilogue scratch")+ precondition(rotatedPairs * 2 <= headDim,+ "rotatedPairs must fit inside one NeoX head")+ guard let enc = cb.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(+ specializedPSOs[Shape(headDim: headDim,+ numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ rotatedPairs: rotatedPairs)] ?? pso)+ enc.setBuffer(q, offset: qOffset, index: 0)+ enc.setBuffer(k, offset: kOffset, index: 1)+ enc.setBuffer(v, offset: vOffset, index: 2)+ enc.setBuffer(qWeight, offset: qWeightOffset, index: 3)+ enc.setBuffer(kWeight, offset: kWeightOffset, index: 4)+ var headDimVar = headDim+ var numQVar = numQHeads+ var numKVVar = numKVHeads+ var posVar = position+ var thetaVar = theta+ var rotatedVar = rotatedPairs+ var epsVar = eps+ enc.setBytes(&headDimVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&numQVar, length: MemoryLayout<UInt32>.size, index: 6)+ enc.setBytes(&numKVVar, length: MemoryLayout<UInt32>.size, index: 7)+ enc.setBytes(&posVar, length: MemoryLayout<UInt32>.size, index: 8)+ enc.setBytes(&thetaVar, length: MemoryLayout<Float>.size, index: 9)+ enc.setBytes(&rotatedVar, length: MemoryLayout<UInt32>.size, index: 10)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 11)++ let threads = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ let groups = Int(numQHeads + 2 * numKVHeads)+ enc.dispatchThreadgroups(MTLSize(width: groups, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Fusions/FusedQKVGEMV.swift b/Sources/TurboFieldfare/Kernels/Fusions/FusedQKVGEMV.swiftnew file mode 100644index 00000000..8cd6ad0d--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Fusions/FusedQKVGEMV.swift@@ -0,0 +1,92 @@+import Foundation+import Metal++final class FusedQKVGEMV {+ private struct Shape: Hashable {+ var qRows: UInt32+ var kvRows: UInt32+ var n: UInt32+ }++ private let pso: MTLComputePipelineState+ private let specializedPSOs: [Shape: MTLComputePipelineState]++ private static let realDecodeShapes: [Shape] = [+ Shape(qRows: 4096, kvRows: 2048, n: 2816),+ Shape(qRows: 8192, kvRows: 1024, n: 2816),+ ]++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("dequant_int4_qkv_gemv_simd",+ constants: [],+ maxTotalThreadsPerThreadgroup: 512)+ var variants: [Shape: MTLComputePipelineState] = [:]+ for shape in Self.realDecodeShapes {+ variants[shape] = try context.pipeline(+ "dequant_int4_qkv_gemv_simd",+ constants: [+ MetalFunctionConstant(index: 23, value: .uint32(shape.qRows)),+ MetalFunctionConstant(index: 24, value: .uint32(shape.kvRows)),+ MetalFunctionConstant(index: 25, value: .uint32(shape.n)),+ MetalFunctionConstant(index: 26, value: .bool(true)),+ ],+ maxTotalThreadsPerThreadgroup: 512)+ }+ self.specializedPSOs = variants+ }++ func encode(commandBuffer: MTLCommandBuffer,+ qWeights: MTLBuffer, qWeightsOffset: Int = 0,+ qScales: MTLBuffer, qScalesOffset: Int = 0,+ qBiases: MTLBuffer, qBiasesOffset: Int = 0,+ kWeights: MTLBuffer, kWeightsOffset: Int = 0,+ kScales: MTLBuffer, kScalesOffset: Int = 0,+ kBiases: MTLBuffer, kBiasesOffset: Int = 0,+ vWeights: MTLBuffer, vWeightsOffset: Int = 0,+ vScales: MTLBuffer, vScalesOffset: Int = 0,+ vBiases: MTLBuffer, vBiasesOffset: Int = 0,+ x: MTLBuffer,+ qOut: MTLBuffer, qOutOffset: Int = 0,+ kOut: MTLBuffer, kOutOffset: Int = 0,+ vOut: MTLBuffer, vOutOffset: Int = 0,+ qRows: UInt32,+ kvRows: UInt32,+ n: UInt32) {+ precondition(n % UInt32(Quantization.groupSize) == 0,+ "N must be a multiple of \(Quantization.groupSize)")+ precondition(qWeightsOffset % 2 == 0 &&+ kWeightsOffset % 2 == 0 &&+ vWeightsOffset % 2 == 0,+ "FusedQKVGEMV needs 2-aligned weights offsets")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ let shape = Shape(qRows: qRows, kvRows: kvRows, n: n)+ enc.setComputePipelineState(specializedPSOs[shape] ?? pso)+ enc.setBuffer(qWeights, offset: qWeightsOffset, index: 0)+ enc.setBuffer(qScales, offset: qScalesOffset, index: 1)+ enc.setBuffer(qBiases, offset: qBiasesOffset, index: 2)+ enc.setBuffer(kWeights, offset: kWeightsOffset, index: 3)+ enc.setBuffer(kScales, offset: kScalesOffset, index: 4)+ enc.setBuffer(kBiases, offset: kBiasesOffset, index: 5)+ enc.setBuffer(vWeights, offset: vWeightsOffset, index: 6)+ enc.setBuffer(vScales, offset: vScalesOffset, index: 7)+ enc.setBuffer(vBiases, offset: vBiasesOffset, index: 8)+ enc.setBuffer(x, offset: 0, index: 9)+ enc.setBuffer(qOut, offset: qOutOffset, index: 10)+ enc.setBuffer(kOut, offset: kOutOffset, index: 11)+ enc.setBuffer(vOut, offset: vOutOffset, index: 12)+ var qVar = qRows+ var kvVar = kvRows+ var nVar = n+ enc.setBytes(&qVar, length: MemoryLayout<UInt32>.size, index: 13)+ enc.setBytes(&kvVar, length: MemoryLayout<UInt32>.size, index: 14)+ enc.setBytes(&nVar, length: MemoryLayout<UInt32>.size, index: 15)+ let totalRows = Int(qRows + 2 * kvRows)+ enc.dispatchThreadgroups(MTLSize(width: (totalRows + 7) / 8,+ height: 1,+ depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256,+ height: 1,+ depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Fusions/LMHeadChainInt4.swift b/Sources/TurboFieldfare/Kernels/Fusions/LMHeadChainInt4.swiftnew file mode 100644index 00000000..c91ab4c1--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Fusions/LMHeadChainInt4.swift@@ -0,0 +1,123 @@+import Metal++/// Final BF16 RMSNorm, INT4 affine lm-head projection, and greedy argmax.+/// The hot path writes one token ID without materializing vocab-sized logits.+final class LMHeadChainInt4 {+ static let rowsPerThreadgroup = 8++ private static let rowSummaryStride = 2+ private static let realDecodeD: UInt32 = 2816+ private static let realDecodeVocab: UInt32 = 262144+ private static let realDecodeHeadConstants: [MetalFunctionConstant] = [+ MetalFunctionConstant(index: 10, value: .uint32(realDecodeD)),+ MetalFunctionConstant(index: 11, value: .uint32(realDecodeVocab)),+ MetalFunctionConstant(index: 13, value: .bool(true)),+ ]++ private let rms: RMSNorm+ private let rowGreedy: MTLComputePipelineState+ private let rowGreedySpecialized: MTLComputePipelineState+ private let rowReducer: MTLComputePipelineState+ private let xNormedBuffer: MTLBuffer+ private let rowSummariesBuffer: MTLBuffer+ private let maxD: Int+ private let maxVocab: Int++ init(context: MetalContext,+ maxD: Int = 2816,+ maxVocab: Int = 262144) throws {+ self.rms = try RMSNorm(context: context)+ self.rowGreedy = try context.pipeline("lm_head_greedy_int4_rows_chunk_raw")+ self.rowGreedySpecialized = try context.pipeline(+ "lm_head_greedy_int4_rows_chunk_raw",+ constants: Self.realDecodeHeadConstants)+ self.rowReducer = try context.pipeline("lm_head_greedy_int4_rows_reduce")+ self.maxD = maxD+ self.maxVocab = maxVocab++ let rowGroups = (maxVocab + Self.rowsPerThreadgroup - 1) / Self.rowsPerThreadgroup+ let xLength = max(maxD, 1) * MemoryLayout<Float16>.size+ let summaryLength = rowGroups * Self.rowSummaryStride * MemoryLayout<Float>.size+ guard let xNormedBuffer = context.device.makeBuffer(+ length: xLength,+ options: .storageModePrivate),+ let rowSummariesBuffer = context.device.makeBuffer(+ length: summaryLength,+ options: .storageModePrivate) else {+ throw MetalError.noDevice+ }+ self.xNormedBuffer = xNormedBuffer+ self.rowSummariesBuffer = rowSummariesBuffer+ }++ func encodeGreedyDecode(commandBuffer: MTLCommandBuffer,+ hidden: MTLBuffer,+ hiddenOffset: Int = 0,+ normWeight: MTLBuffer,+ normOffset: Int = 0,+ weights: MTLBuffer,+ weightsOffset: Int = 0,+ scales: MTLBuffer,+ scalesOffset: Int = 0,+ biases: MTLBuffer,+ biasesOffset: Int = 0,+ outToken: MTLBuffer,+ d: UInt32,+ vocab: UInt32,+ rmsEps: Float = 1e-6) {+ precondition(Int(d) <= maxD, "d=\(d) exceeds wrapper maxD=\(maxD)")+ precondition(Int(vocab) <= maxVocab,+ "vocab=\(vocab) exceeds wrapper maxVocab=\(maxVocab)")+ precondition(Int(d) % Quantization.groupSize == 0,+ "d must be a multiple of \(Quantization.groupSize)")+ precondition(hiddenOffset >= 0, "hiddenOffset must be non-negative")+ precondition(weightsOffset % 2 == 0,+ "lm_head_greedy_int4_rows_chunk_raw needs a 2-aligned weightsOffset")++ let rowGroups = (Int(vocab) + Self.rowsPerThreadgroup - 1)+ / Self.rowsPerThreadgroup+ rms.encodeBF16W(commandBuffer: commandBuffer,+ x: hidden,+ xOffset: hiddenOffset,+ weight: normWeight,+ weightOffset: normOffset,+ out: xNormedBuffer,+ d: d,+ eps: rmsEps)++ if let encoder = commandBuffer.makeComputeCommandEncoder() {+ let specialized = d == Self.realDecodeD && vocab == Self.realDecodeVocab+ encoder.setComputePipelineState(specialized ? rowGreedySpecialized : rowGreedy)+ encoder.setBuffer(xNormedBuffer, offset: 0, index: 0)+ encoder.setBuffer(weights, offset: weightsOffset, index: 1)+ encoder.setBuffer(scales, offset: scalesOffset, index: 2)+ encoder.setBuffer(biases, offset: biasesOffset, index: 3)+ encoder.setBuffer(rowSummariesBuffer, offset: 0, index: 4)+ var dValue = d+ var vocabValue = vocab+ encoder.setBytes(&dValue, length: MemoryLayout<UInt32>.size, index: 5)+ encoder.setBytes(&vocabValue, length: MemoryLayout<UInt32>.size, index: 6)++ let threadgroupSize = MTLSize(+ width: 32 * Self.rowsPerThreadgroup,+ height: 1,+ depth: 1)+ encoder.dispatchThreadgroups(+ MTLSize(width: rowGroups, height: 1, depth: 1),+ threadsPerThreadgroup: threadgroupSize)+ encoder.endEncoding()+ }++ if let encoder = commandBuffer.makeComputeCommandEncoder() {+ encoder.setComputePipelineState(rowReducer)+ encoder.setBuffer(rowSummariesBuffer, offset: 0, index: 0)+ encoder.setBuffer(outToken, offset: 0, index: 1)+ var rowGroupCount = UInt32(rowGroups)+ encoder.setBytes(&rowGroupCount, length: MemoryLayout<UInt32>.size, index: 2)++ let threadgroupSize = MTLSize(width: 256, height: 1, depth: 1)+ encoder.dispatchThreads(threadgroupSize, threadsPerThreadgroup: threadgroupSize)+ encoder.endEncoding()+ }+ }+}diff --git a/Sources/TurboFieldfare/Kernels/KVCache/TurboQuant.swift b/Sources/TurboFieldfare/Kernels/KVCache/TurboQuant.swiftnew file mode 100644index 00000000..71c67966--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/KVCache/TurboQuant.swift@@ -0,0 +1,196 @@+import Foundation+import Metal++struct TurboQuantKVWriteParams {+ var d: UInt32+ var numHeads: UInt32+ var bytesPerHead: UInt32+ var packedOffset: UInt32+ var scaleOffset: UInt32+ var tokenBase: UInt32+ var bytesPerToken: UInt32++ init(d: UInt32,+ numHeads: UInt32,+ roleLayout: TurboQuantKVRoleLayout,+ tokenBase: UInt32 = 0) {+ self.d = d+ self.numHeads = numHeads+ self.bytesPerHead = UInt32(roleLayout.bytesPerHead)+ self.packedOffset = UInt32(roleLayout.packedOffsetPerHead)+ self.scaleOffset = UInt32(roleLayout.scaleOffsetPerHead)+ self.tokenBase = tokenBase+ self.bytesPerToken = UInt32(roleLayout.bytesPerToken)+ }+}++enum TurboQuantKVBulkWriteError: Error, Equatable, CustomStringConvertible {+ case invalidTokenCount(Int)+ case invalidDestinationTokenBase(Int)+ case invalidCacheCapacity(Int)+ case rangeExceedsCache(start: Int, count: Int, capacity: Int)+ case unsupportedSourceTokenStride(actual: Int, expected: Int)++ public var description: String {+ switch self {+ case .invalidTokenCount(let count):+ return "invalid TurboQuant bulk token count \(count)"+ case .invalidDestinationTokenBase(let base):+ return "invalid TurboQuant bulk destination token base \(base)"+ case .invalidCacheCapacity(let capacity):+ return "invalid TurboQuant bulk cache capacity \(capacity)"+ case let .rangeExceedsCache(start, count, capacity):+ return "TurboQuant bulk write range start=\(start) count=\(count) exceeds capacity=\(capacity)"+ case let .unsupportedSourceTokenStride(actual, expected):+ return "TurboQuant bulk source token stride \(actual) does not match contiguous stride \(expected)"+ }+ }+}++struct TurboQuantKVBulkWriteParams {+ var kv: TurboQuantKVWriteParams+ var tokenCount: Int+ var dstTokenBase: Int+ var cacheTokenCapacity: Int+ var sourceTokenStrideElements: Int++ init(kv: TurboQuantKVWriteParams,+ tokenCount: Int,+ dstTokenBase: Int,+ cacheTokenCapacity: Int,+ sourceTokenStrideElements: Int) {+ self.kv = kv+ self.tokenCount = tokenCount+ self.dstTokenBase = dstTokenBase+ self.cacheTokenCapacity = cacheTokenCapacity+ self.sourceTokenStrideElements = sourceTokenStrideElements+ }+}++struct TurboQuantWHTParams {+ var numHeads: UInt32+ var layer: UInt32+ var rotationSeed: UInt32+ var applyRotation: UInt32++ init(numHeads: UInt32 = 1,+ layer: UInt32 = 0,+ rotationSeed: UInt32 = 0,+ applyRotation: Bool = false) {+ self.numHeads = numHeads+ self.layer = layer+ self.rotationSeed = rotationSeed+ self.applyRotation = applyRotation ? 1 : 0+ }+}++/// Packs pre-WHT FP16 K/V rows directly into the production TurboQuant cache+/// layout. One threadgroup handles each flattened `(token, head)` pair.+final class TurboQuantQuant {+ private struct Shape: Hashable {+ var d: UInt32+ var numHeads: UInt32+ }++ private let kvWriteWHTPSO: MTLComputePipelineState+ private let kvWriteWHTSpecializedPSOs: [Shape: MTLComputePipelineState]+ private static let realDecodeShapes: [Shape] = [+ Shape(d: 256, numHeads: 8),+ Shape(d: 512, numHeads: 2),+ ]++ init(context: MetalContext) throws {+ self.kvWriteWHTPSO = try context.pipeline("turboquant_quant_kv_write_wht")+ var variants: [Shape: MTLComputePipelineState] = [:]+ for shape in Self.realDecodeShapes {+ variants[shape] = try context.pipeline(+ "turboquant_quant_kv_write_wht",+ constants: [+ MetalFunctionConstant(index: 100, value: .uint32(shape.d)),+ MetalFunctionConstant(index: 101, value: .uint32(shape.numHeads)),+ MetalFunctionConstant(index: 103, value: .bool(true)),+ ])+ }+ self.kvWriteWHTSpecializedPSOs = variants+ }++ func encodeKVWriteWHT(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer,+ xOffset: Int = 0,+ cache: MTLBuffer,+ cacheOffset: Int = 0,+ params: TurboQuantKVWriteParams,+ whtParams: TurboQuantWHTParams,+ pairs: Int) {+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }+ encoder.setComputePipelineState(+ kvWriteWHTSpecializedPSOs[Shape(d: params.d,+ numHeads: params.numHeads)] ?? kvWriteWHTPSO)+ encoder.setBuffer(x, offset: xOffset, index: 0)+ encoder.setBuffer(cache, offset: cacheOffset, index: 1)+ var writeParams = params+ var transformParams = whtParams+ encoder.setBytes(&writeParams,+ length: MemoryLayout<TurboQuantKVWriteParams>.size,+ index: 2)+ encoder.setBytes(&transformParams,+ length: MemoryLayout<TurboQuantWHTParams>.size,+ index: 3)+ let threads = Int(params.d)+ encoder.dispatchThreadgroups(+ MTLSize(width: pairs, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ encoder.endEncoding()+ }++ func encodeKVWriteWHTBulk(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer,+ xOffset: Int = 0,+ cache: MTLBuffer,+ cacheOffset: Int = 0,+ params: TurboQuantKVBulkWriteParams,+ whtParams: TurboQuantWHTParams) throws {+ let writeParams = try validateBulkWriteParams(params)+ let destinationOffset = cacheOffset+ + params.dstTokenBase * Int(writeParams.bytesPerToken)+ encodeKVWriteWHT(commandBuffer: commandBuffer,+ x: x,+ xOffset: xOffset,+ cache: cache,+ cacheOffset: destinationOffset,+ params: writeParams,+ whtParams: whtParams,+ pairs: params.tokenCount * Int(writeParams.numHeads))+ }++ private func validateBulkWriteParams(+ _ params: TurboQuantKVBulkWriteParams+ ) throws -> TurboQuantKVWriteParams {+ guard params.tokenCount > 0 else {+ throw TurboQuantKVBulkWriteError.invalidTokenCount(params.tokenCount)+ }+ guard params.dstTokenBase >= 0 else {+ throw TurboQuantKVBulkWriteError.invalidDestinationTokenBase(params.dstTokenBase)+ }+ guard params.cacheTokenCapacity >= 0 else {+ throw TurboQuantKVBulkWriteError.invalidCacheCapacity(params.cacheTokenCapacity)+ }+ guard params.dstTokenBase + params.tokenCount <= params.cacheTokenCapacity else {+ throw TurboQuantKVBulkWriteError.rangeExceedsCache(+ start: params.dstTokenBase,+ count: params.tokenCount,+ capacity: params.cacheTokenCapacity)+ }++ let expectedStride = Int(params.kv.numHeads) * Int(params.kv.d)+ guard params.sourceTokenStrideElements == expectedStride else {+ throw TurboQuantKVBulkWriteError.unsupportedSourceTokenStride(+ actual: params.sourceTokenStrideElements,+ expected: expectedStride)+ }++ var writeParams = params.kv+ writeParams.tokenBase = UInt32(params.dstTokenBase)+ return writeParams+ }+}diff --git a/Sources/TurboFieldfare/Kernels/MoE/MoE.swift b/Sources/TurboFieldfare/Kernels/MoE/MoE.swiftnew file mode 100644index 00000000..b1cd4787--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/MoE/MoE.swift@@ -0,0 +1,313 @@+import Foundation+import Metal++@frozen+public struct MoEExpertOffsets {+ public var gateWOff: UInt32+ public var gateSOff: UInt32+ public var gateBOff: UInt32+ public var upWOff: UInt32+ public var upSOff: UInt32+ public var upBOff: UInt32+ public var downWOff: UInt32+ public var downSOff: UInt32+ public var downBOff: UInt32++ public init(gateWOff: UInt32, gateSOff: UInt32, gateBOff: UInt32,+ upWOff: UInt32, upSOff: UInt32, upBOff: UInt32,+ downWOff: UInt32, downSOff: UInt32, downBOff: UInt32) {+ self.gateWOff = gateWOff+ self.gateSOff = gateSOff+ self.gateBOff = gateBOff+ self.upWOff = upWOff+ self.upSOff = upSOff+ self.upBOff = upBOff+ self.downWOff = downWOff+ self.downSOff = downSOff+ self.downBOff = downBOff+ }+}++final class MoE {+ static let maxStreamedExperts = 8++ private static let realDecodeD: UInt32 = 2816+ private static let realDecodeF: UInt32 = 704+ private static let realDecodeTopK: UInt32 = 8+ private static let realDecodeNumExperts: UInt32 = 128+ private static let realDecodeMoEConstants: [MetalFunctionConstant] = [+ MetalFunctionConstant(index: 0, value: .uint32(realDecodeD)),+ MetalFunctionConstant(index: 1, value: .uint32(realDecodeF)),+ MetalFunctionConstant(index: 2, value: .uint32(realDecodeTopK)),+ MetalFunctionConstant(index: 3, value: .bool(true)),+ ]+ private static let realDecodeRouterConstants: [MetalFunctionConstant] = [+ MetalFunctionConstant(index: 40, value: .uint32(realDecodeNumExperts)),+ MetalFunctionConstant(index: 41, value: .uint32(realDecodeD)),+ MetalFunctionConstant(index: 42, value: .uint32(realDecodeTopK)),+ MetalFunctionConstant(index: 43, value: .bool(true)),+ ]++ private let routerGemvPSO: MTLComputePipelineState+ private let routerGemvSpecializedPSO: MTLComputePipelineState+ private let routerSelectK8PSO: MTLComputePipelineState+ private let routerSelectK8SpecializedPSO: MTLComputePipelineState+ private let routerLogits: MTLBuffer+ private let phase1U16PSO: MTLComputePipelineState+ private let phase1U16SpecializedPSO: MTLComputePipelineState+ private let phase1SubsetU16PSO: MTLComputePipelineState+ private let phase1SubsetU16SpecializedPSO: MTLComputePipelineState+ private let phase2ReduceK8PSO: MTLComputePipelineState+ private let phase2ReduceK8SpecializedPSO: MTLComputePipelineState+ private let routedArgEncoder: MTLArgumentEncoder+ private let reusableRoutedArgBuffer: MTLBuffer++ init(context: MetalContext) throws {+ let routerName = "router_gemv_gemma4_r4"+ self.routerGemvPSO = try context.pipeline(+ routerName,+ constants: [],+ maxTotalThreadsPerThreadgroup: 512)+ self.routerGemvSpecializedPSO = try context.pipeline(+ routerName,+ constants: Self.realDecodeRouterConstants,+ maxTotalThreadsPerThreadgroup: 512)+ self.routerSelectK8PSO = try context.pipeline("router_topk_select_k8")+ self.routerSelectK8SpecializedPSO = try context.pipeline(+ "router_topk_select_k8",+ constants: Self.realDecodeRouterConstants)+ self.phase1U16PSO = try context.pipeline("moe_phase1_gate_up_act_u16load")+ self.phase1U16SpecializedPSO = try context.pipeline(+ "moe_phase1_gate_up_act_u16load",+ constants: Self.realDecodeMoEConstants)+ self.phase1SubsetU16PSO = try context.pipeline("moe_phase1_gate_up_act_subset_u16load")+ self.phase1SubsetU16SpecializedPSO = try context.pipeline(+ "moe_phase1_gate_up_act_subset_u16load",+ constants: Self.realDecodeMoEConstants)+ self.phase2ReduceK8PSO = try context.pipeline("moe_phase2_down_reduce_k8")+ self.phase2ReduceK8SpecializedPSO = try context.pipeline(+ "moe_phase2_down_reduce_k8",+ constants: Self.realDecodeMoEConstants)++ guard let logits = context.device.makeBuffer(+ length: 256 * MemoryLayout<Float>.stride,+ options: .storageModeShared),+ let phase1Function = context.library.makeFunction(+ name: "moe_phase1_gate_up_act_u16load") else {+ throw MetalError.noDevice+ }+ self.routerLogits = logits+ self.routedArgEncoder = phase1Function.makeArgumentEncoder(bufferIndex: 0)+ guard let reusable = context.device.makeBuffer(+ length: routedArgEncoder.encodedLength,+ options: .storageModeShared) else {+ throw MetalError.noDevice+ }+ self.reusableRoutedArgBuffer = reusable+ }++ func encodeRouterGemma4(commandBuffer: MTLCommandBuffer,+ weights: MTLBuffer, weightsOffset: Int = 0,+ scales: MTLBuffer, scalesOffset: Int = 0,+ biases: MTLBuffer, biasesOffset: Int = 0,+ hidden: MTLBuffer,+ effectiveScale: MTLBuffer, effectiveScaleOffset: Int = 0,+ perExpertScale: MTLBuffer, perExpertScaleOffset: Int = 0,+ outIndices: MTLBuffer,+ outWeights: MTLBuffer,+ numExperts: UInt32,+ d: UInt32,+ topK: UInt32) {+ precondition(d.isMultiple(of: UInt32(Quantization.groupSize)))+ precondition(numExperts <= 256)+ precondition(topK == UInt32(Self.maxStreamedExperts))++ var expertCount = numExperts+ var dimension = d+ let useSpecialized = numExperts == Self.realDecodeNumExperts+ && d == Self.realDecodeD+ if let encoder = commandBuffer.makeComputeCommandEncoder() {+ encoder.setComputePipelineState(+ useSpecialized ? routerGemvSpecializedPSO : routerGemvPSO)+ encoder.setBuffer(weights, offset: weightsOffset, index: 0)+ encoder.setBuffer(scales, offset: scalesOffset, index: 1)+ encoder.setBuffer(biases, offset: biasesOffset, index: 2)+ encoder.setBuffer(hidden, offset: 0, index: 3)+ encoder.setBuffer(effectiveScale, offset: effectiveScaleOffset, index: 4)+ encoder.setBuffer(routerLogits, offset: 0, index: 5)+ encoder.setBytes(&expertCount, length: MemoryLayout<UInt32>.stride, index: 6)+ encoder.setBytes(&dimension, length: MemoryLayout<UInt32>.stride, index: 7)+ encoder.dispatchThreadgroups(+ MTLSize(width: (Int(numExperts) + 3) / 4, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 128, height: 1, depth: 1))+ encoder.endEncoding()+ }++ if let encoder = commandBuffer.makeComputeCommandEncoder() {+ encoder.setComputePipelineState(+ useSpecialized ? routerSelectK8SpecializedPSO : routerSelectK8PSO)+ encoder.setBuffer(routerLogits, offset: 0, index: 0)+ encoder.setBuffer(perExpertScale, offset: perExpertScaleOffset, index: 1)+ encoder.setBuffer(outIndices, offset: 0, index: 2)+ encoder.setBuffer(outWeights, offset: 0, index: 3)+ encoder.setBytes(&expertCount, length: MemoryLayout<UInt32>.stride, index: 4)+ encoder.dispatchThreadgroups(+ MTLSize(width: 1, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 32, height: 1, depth: 1))+ encoder.endEncoding()+ }+ }++ func makeRoutedArgumentBuffer(routedBlobs: [MTLBuffer],+ topK: UInt32) -> MTLBuffer? {+ validate(routedBlobs: routedBlobs, topK: topK)+ guard let buffer = routedBlobs.first?.device.makeBuffer(+ length: routedArgEncoder.encodedLength,+ options: .storageModeShared) else {+ return nil+ }+ encodeRoutedArgumentBuffer(buffer, routedBlobs: routedBlobs)+ return buffer+ }++ func makeReusedRoutedArgumentBuffer(routedBlobs: [MTLBuffer],+ topK: UInt32) -> MTLBuffer {+ validate(routedBlobs: routedBlobs, topK: topK)+ encodeRoutedArgumentBuffer(reusableRoutedArgBuffer, routedBlobs: routedBlobs)+ return reusableRoutedArgBuffer+ }++ func encodeRoutedPersistentPhase1U16Load(+ commandBuffer: MTLCommandBuffer,+ routedArgBuffer: MTLBuffer,+ routedBlobs: [MTLBuffer],+ routedOffsets: MoEExpertOffsets,+ x: MTLBuffer,+ acts: MTLBuffer,+ d: UInt32,+ f: UInt32,+ topK: UInt32+ ) {+ validate(routedBlobs: routedBlobs, topK: topK)+ var dimension = d+ var intermediate = f+ var expertCount = topK+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }+ encoder.setComputePipelineState(+ useRealDecodeConstants(d: d, f: f)+ ? phase1U16SpecializedPSO+ : phase1U16PSO)+ encoder.setBuffer(routedArgBuffer, offset: 0, index: 0)+ for buffer in routedBlobs { encoder.useResource(buffer, usage: .read) }+ var offsets = routedOffsets+ encoder.setBytes(&offsets, length: MemoryLayout<MoEExpertOffsets>.stride, index: 1)+ encoder.setBuffer(x, offset: 0, index: 2)+ encoder.setBuffer(acts, offset: 0, index: 3)+ encoder.setBytes(&dimension, length: MemoryLayout<UInt32>.stride, index: 4)+ encoder.setBytes(&intermediate, length: MemoryLayout<UInt32>.stride, index: 5)+ encoder.setBytes(&expertCount, length: MemoryLayout<UInt32>.stride, index: 6)+ encoder.dispatchThreadgroups(+ MTLSize(width: (Int(topK * f) + 7) / 8, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ encoder.endEncoding()+ }++ func encodeRoutedPersistentPhase1SubsetU16Load(+ commandBuffer: MTLCommandBuffer,+ routedArgBuffer: MTLBuffer,+ routedBlobs: [MTLBuffer],+ routedOffsets: MoEExpertOffsets,+ x: MTLBuffer,+ acts: MTLBuffer,+ activeSlots: MTLBuffer,+ activeSlotIndices: [UInt32],+ activeCount: UInt32,+ d: UInt32,+ f: UInt32,+ topK: UInt32+ ) {+ guard activeCount > 0 else { return }+ validate(routedBlobs: routedBlobs, topK: topK)+ precondition(activeSlotIndices.count == Int(activeCount))+ var dimension = d+ var intermediate = f+ var expertCount = topK+ var active = activeCount+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }+ encoder.setComputePipelineState(+ useRealDecodeConstants(d: d, f: f)+ ? phase1SubsetU16SpecializedPSO+ : phase1SubsetU16PSO)+ encoder.setBuffer(routedArgBuffer, offset: 0, index: 0)+ for slot in activeSlotIndices {+ encoder.useResource(routedBlobs[Int(slot)], usage: .read)+ }+ var offsets = routedOffsets+ encoder.setBytes(&offsets, length: MemoryLayout<MoEExpertOffsets>.stride, index: 1)+ encoder.setBuffer(x, offset: 0, index: 2)+ encoder.setBuffer(acts, offset: 0, index: 3)+ encoder.setBytes(&dimension, length: MemoryLayout<UInt32>.stride, index: 4)+ encoder.setBytes(&intermediate, length: MemoryLayout<UInt32>.stride, index: 5)+ encoder.setBytes(&expertCount, length: MemoryLayout<UInt32>.stride, index: 6)+ encoder.setBuffer(activeSlots, offset: 0, index: 7)+ encoder.setBytes(&active, length: MemoryLayout<UInt32>.stride, index: 8)+ encoder.dispatchThreadgroups(+ MTLSize(width: (Int(activeCount * f) + 7) / 8, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ encoder.endEncoding()+ }++ func encodeRoutedPersistentPhase2Reduce(+ commandBuffer: MTLCommandBuffer,+ routedArgBuffer: MTLBuffer,+ routedBlobs: [MTLBuffer],+ routedOffsets: MoEExpertOffsets,+ acts: MTLBuffer,+ routingWeights: MTLBuffer,+ residual: MTLBuffer,+ y: MTLBuffer,+ d: UInt32,+ f: UInt32,+ topK: UInt32+ ) {+ validate(routedBlobs: routedBlobs, topK: topK)+ var dimension = d+ var intermediate = f+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }+ encoder.setComputePipelineState(+ useRealDecodeConstants(d: d, f: f)+ ? phase2ReduceK8SpecializedPSO+ : phase2ReduceK8PSO)+ encoder.setBuffer(routedArgBuffer, offset: 0, index: 0)+ for buffer in routedBlobs { encoder.useResource(buffer, usage: .read) }+ var offsets = routedOffsets+ encoder.setBytes(&offsets, length: MemoryLayout<MoEExpertOffsets>.stride, index: 1)+ encoder.setBuffer(acts, offset: 0, index: 2)+ encoder.setBuffer(routingWeights, offset: 0, index: 3)+ encoder.setBuffer(residual, offset: 0, index: 4)+ encoder.setBuffer(y, offset: 0, index: 5)+ encoder.setBytes(&dimension, length: MemoryLayout<UInt32>.stride, index: 6)+ encoder.setBytes(&intermediate, length: MemoryLayout<UInt32>.stride, index: 7)+ encoder.dispatchThreadgroups(+ MTLSize(width: Int(d), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ encoder.endEncoding()+ }++ private func validate(routedBlobs: [MTLBuffer], topK: UInt32) {+ precondition(topK == UInt32(Self.maxStreamedExperts))+ precondition(routedBlobs.count == Int(topK))+ }++ private func encodeRoutedArgumentBuffer(_ buffer: MTLBuffer,+ routedBlobs: [MTLBuffer]) {+ routedArgEncoder.setArgumentBuffer(buffer, offset: 0)+ for (index, blob) in routedBlobs.enumerated() {+ routedArgEncoder.setBuffer(blob, offset: 0, index: index)+ }+ }++ private func useRealDecodeConstants(d: UInt32, f: UInt32) -> Bool {+ d == Self.realDecodeD && f == Self.realDecodeF+ }+}diff --git a/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt8.swift b/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt8.swiftnew file mode 100644index 00000000..11fdf6c0--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt8.swift@@ -0,0 +1,208 @@+import Foundation+import Metal++/// Per-projection 8-bit affine weights for the Gemma 4 shared (dense) MLP.+///+/// The Gemma 4 26B-A4B manifest stores `mlp.gate/up/down_proj.weight` at 8-bit+/// MLX affine (group=64, BF16 scale + BF16 bias). Shapes:+/// gate: [F=2112, D=2816] up: [F=2112, D=2816] down: [D=2816, F=2112]+struct SharedExpertInt8Proj {+ let weights: MTLBuffer+ let scales: MTLBuffer+ let biases: MTLBuffer+ let weightsOffset: Int+ let scalesOffset: Int+ let biasesOffset: Int+ let rows: UInt32+ let cols: UInt32++ init(weights: MTLBuffer, scales: MTLBuffer, biases: MTLBuffer,+ weightsOffset: Int = 0, scalesOffset: Int = 0, biasesOffset: Int = 0,+ rows: UInt32, cols: UInt32) {+ self.weights = weights+ self.scales = scales+ self.biases = biases+ self.weightsOffset = weightsOffset+ self.scalesOffset = scalesOffset+ self.biasesOffset = biasesOffset+ self.rows = rows+ self.cols = cols+ }+}++enum SharedExpertInt8Error: Error, CustomStringConvertible {+ case dimensionMismatch(String)+ case scratchTooSmall(String)++ public var description: String {+ switch self {+ case .dimensionMismatch(let s): return "SharedExpertInt8 dimension mismatch: \(s)"+ case .scratchTooSmall(let s): return "SharedExpertInt8 scratch too small: \(s)"+ }+ }+}++/// Standalone 8-bit dense MLP — the "shared expert" branch of Gemma 4's+/// parallel MoE. Runs on the same hidden as the routed+/// branch, in parallel; their outputs are summed downstream.+///+/// y = down(gelu_pytorch_tanh(gate(x)) * up(x))+///+/// The gate, up, and activation work is fused. The caller provides one FP16+/// activation buffer of length F, which can be reused across layers.+final class SharedExpertInt8 {+ private let int8: DequantInt8GEMV+ private let fusedGateUpActPSO: MTLComputePipelineState+ private let specializedFusedGateUpActPSO: MTLComputePipelineState?++ init(context: MetalContext) throws {+ self.int8 = try DequantInt8GEMV(context: context)+ self.fusedGateUpActPSO = try context.pipeline("shared_int8_gate_up_act_simd")+ self.specializedFusedGateUpActPSO = try? context.pipeline(+ "shared_int8_gate_up_act_simd",+ constants: [+ MetalFunctionConstant(index: 70, value: .uint32(2112)),+ MetalFunctionConstant(index: 71, value: .uint32(2816)),+ MetalFunctionConstant(index: 72, value: .bool(true)),+ MetalFunctionConstant(index: 73, value: .uint32(8)),+ ])+ }++ func encode(commandBuffer cb: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ gate: SharedExpertInt8Proj,+ up: SharedExpertInt8Proj,+ down: SharedExpertInt8Proj,+ y: MTLBuffer, yOffset: Int = 0,+ scratchAct: MTLBuffer, scratchActOffset: Int = 0) throws {+ guard gate.rows == up.rows, gate.cols == up.cols else {+ throw SharedExpertInt8Error.dimensionMismatch(+ "gate/up shapes differ: gate=(\(gate.rows),\(gate.cols)) up=(\(up.rows),\(up.cols))")+ }+ guard down.rows == gate.cols, down.cols == gate.rows else {+ throw SharedExpertInt8Error.dimensionMismatch(+ "down expected (\(gate.cols),\(gate.rows)), got (\(down.rows),\(down.cols))")+ }+ let needBytes = Int(gate.rows) * MemoryLayout<Float16>.size+ guard scratchActOffset >= 0, scratchActOffset + needBytes <= scratchAct.length else {+ throw SharedExpertInt8Error.scratchTooSmall(+ "scratchAct offset \(scratchActOffset) + needed \(needBytes) exceeds length \(scratchAct.length)")+ }+ let inputBytes = Int(gate.cols) * MemoryLayout<Float16>.size+ let outputBytes = Int(down.rows) * MemoryLayout<Float16>.size+ guard xOffset >= 0, xOffset + inputBytes <= x.length else {+ throw SharedExpertInt8Error.scratchTooSmall(+ "x offset \(xOffset) + needed \(inputBytes) exceeds length \(x.length)")+ }+ guard yOffset >= 0, yOffset + outputBytes <= y.length else {+ throw SharedExpertInt8Error.scratchTooSmall(+ "y offset \(yOffset) + needed \(outputBytes) exceeds length \(y.length)")+ }++ try encodePhase1(commandBuffer: cb,+ x: x,+ xOffset: xOffset,+ gate: gate,+ up: up,+ scratchAct: scratchAct,+ scratchActOffset: scratchActOffset)++ try encodeDown(commandBuffer: cb,+ down: down,+ y: y,+ yOffset: yOffset,+ scratchAct: scratchAct,+ scratchActOffset: scratchActOffset)+ }++ func encodePhase1(commandBuffer cb: MTLCommandBuffer,+ x: MTLBuffer,+ xOffset: Int = 0,+ gate: SharedExpertInt8Proj,+ up: SharedExpertInt8Proj,+ scratchAct: MTLBuffer,+ scratchActOffset: Int = 0) throws {+ guard gate.rows == up.rows, gate.cols == up.cols else {+ throw SharedExpertInt8Error.dimensionMismatch(+ "gate/up shapes differ: gate=(\(gate.rows),\(gate.cols)) up=(\(up.rows),\(up.cols))")+ }+ let needBytes = Int(gate.rows) * MemoryLayout<Float16>.size+ guard scratchActOffset >= 0, scratchActOffset + needBytes <= scratchAct.length else {+ throw SharedExpertInt8Error.scratchTooSmall(+ "scratchAct offset \(scratchActOffset) + needed \(needBytes) exceeds length \(scratchAct.length)")+ }+ let inputBytes = Int(gate.cols) * MemoryLayout<Float16>.size+ guard xOffset >= 0, xOffset + inputBytes <= x.length else {+ throw SharedExpertInt8Error.scratchTooSmall(+ "x offset \(xOffset) + needed \(inputBytes) exceeds length \(x.length)")+ }++ try encodeFusedGateUpAct(commandBuffer: cb,+ x: x,+ xOffset: xOffset,+ gate: gate,+ up: up,+ scratchAct: scratchAct,+ scratchActOffset: scratchActOffset)+ }++ func encodeDown(commandBuffer cb: MTLCommandBuffer,+ down: SharedExpertInt8Proj,+ y: MTLBuffer,+ yOffset: Int = 0,+ scratchAct: MTLBuffer,+ scratchActOffset: Int = 0) throws {+ let inputBytes = Int(down.cols) * MemoryLayout<Float16>.size+ let outputBytes = Int(down.rows) * MemoryLayout<Float16>.size+ guard scratchActOffset >= 0, scratchActOffset + inputBytes <= scratchAct.length else {+ throw SharedExpertInt8Error.scratchTooSmall(+ "scratchAct offset \(scratchActOffset) + needed \(inputBytes) exceeds length \(scratchAct.length)")+ }+ guard yOffset >= 0, yOffset + outputBytes <= y.length else {+ throw SharedExpertInt8Error.scratchTooSmall(+ "y offset \(yOffset) + needed \(outputBytes) exceeds length \(y.length)")+ }+ int8.encode(commandBuffer: cb,+ weights: down.weights, weightsOffset: down.weightsOffset,+ scales: down.scales, scalesOffset: down.scalesOffset,+ biases: down.biases, biasesOffset: down.biasesOffset,+ x: scratchAct, xOffset: scratchActOffset,+ y: y, yOffset: yOffset,+ m: down.rows, n: down.cols)+ }++ private func encodeFusedGateUpAct(commandBuffer cb: MTLCommandBuffer,+ x: MTLBuffer,+ xOffset: Int,+ gate: SharedExpertInt8Proj,+ up: SharedExpertInt8Proj,+ scratchAct: MTLBuffer,+ scratchActOffset: Int) throws {+ guard let enc = cb.makeComputeCommandEncoder() else {+ throw SharedExpertInt8Error.dimensionMismatch("encoder alloc failed")+ }+ enc.setComputePipelineState(+ (gate.rows == 2112 && gate.cols == 2816 ? specializedFusedGateUpActPSO : nil)+ ?? fusedGateUpActPSO)+ enc.setBuffer(gate.weights, offset: gate.weightsOffset, index: 0)+ enc.setBuffer(gate.scales, offset: gate.scalesOffset, index: 1)+ enc.setBuffer(gate.biases, offset: gate.biasesOffset, index: 2)+ enc.setBuffer(up.weights, offset: up.weightsOffset, index: 3)+ enc.setBuffer(up.scales, offset: up.scalesOffset, index: 4)+ enc.setBuffer(up.biases, offset: up.biasesOffset, index: 5)+ enc.setBuffer(x, offset: xOffset, index: 6)+ enc.setBuffer(scratchAct, offset: scratchActOffset, index: 7)+ var rows = gate.rows+ var cols = gate.cols+ enc.setBytes(&rows, length: MemoryLayout<UInt32>.size, index: 8)+ enc.setBytes(&cols, length: MemoryLayout<UInt32>.size, index: 9)++ let rowsPerTG = 8+ let groups = (Int(gate.rows) + rowsPerTG - 1) / rowsPerTG+ enc.dispatchThreadgroups(MTLSize(width: groups, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 32 * rowsPerTG,+ height: 1,+ depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillFinalRowHead.swift b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillFinalRowHead.swiftnew file mode 100644index 00000000..406e8953--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillFinalRowHead.swift@@ -0,0 +1,66 @@+import Foundation+import Metal++final class PrefillFinalRowHeadInt4 {+ private let rms: RMSNorm+ private let int4: DequantInt4GEMV+ private let normed: MTLBuffer+ private let maxD: Int++ init(context: MetalContext, maxD: Int = 2816) throws {+ precondition(maxD > 0, "maxD must be positive")+ self.rms = try RMSNorm(context: context)+ self.int4 = try DequantInt4GEMV(context: context)+ self.maxD = maxD+ guard let normed = context.device.makeBuffer(length: maxD * MemoryLayout<Float16>.size,+ options: .storageModePrivate) else {+ throw MetalError.noDevice+ }+ self.normed = normed+ }++ func encodeLogits(commandBuffer: MTLCommandBuffer,+ hiddenBlock: MTLBuffer,+ row: Int,+ rowStrideElements: Int,+ normWeight: MTLBuffer,+ normWeightOffset: Int = 0,+ weights: MTLBuffer,+ weightsOffset: Int = 0,+ scales: MTLBuffer,+ scalesOffset: Int = 0,+ biases: MTLBuffer,+ biasesOffset: Int = 0,+ logits: MTLBuffer,+ logitsOffset: Int = 0,+ d: UInt32,+ vocab: UInt32,+ rmsEps: Float) {+ precondition(row >= 0, "row must be non-negative")+ precondition(rowStrideElements >= Int(d), "row stride must cover d")+ precondition(Int(d) <= maxD, "d=\(d) exceeds maxD=\(maxD)")+ precondition(d % UInt32(Quantization.groupSize) == 0,+ "d must be a multiple of \(Quantization.groupSize)")+ let hiddenOffset = (row * rowStrideElements) * MemoryLayout<Float16>.size+ rms.encodeBF16W(commandBuffer: commandBuffer,+ x: hiddenBlock,+ xOffset: hiddenOffset,+ weight: normWeight,+ weightOffset: normWeightOffset,+ out: normed,+ d: d,+ eps: rmsEps)+ int4.encode(commandBuffer: commandBuffer,+ weights: weights,+ weightsOffset: weightsOffset,+ scales: scales,+ scalesOffset: scalesOffset,+ biases: biases,+ biasesOffset: biasesOffset,+ x: normed,+ y: logits,+ yOffset: logitsOffset,+ m: vocab,+ n: d)+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillLayerTail.swift b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillLayerTail.swiftnew file mode 100644index 00000000..37eea538--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillLayerTail.swift@@ -0,0 +1,61 @@+import Foundation+import Metal++final class PrefillLayerTail {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("prefill_layer_tail_block")+ }++ func encode(commandBuffer: MTLCommandBuffer,+ h2: MTLBuffer,+ h2Offset: Int = 0,+ h1: MTLBuffer,+ h1Offset: Int = 0,+ hidden: MTLBuffer,+ hiddenOffset: Int = 0,+ postFFN2Weight: MTLBuffer,+ postFFN2WeightOffset: Int = 0,+ postFFNWeight: MTLBuffer,+ postFFNWeightOffset: Int = 0,+ queryCount: UInt32,+ d: UInt32,+ h2StrideElements: UInt32,+ h1StrideElements: UInt32,+ hiddenStrideElements: UInt32,+ eps: Float,+ layerScalar: Float) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(d > 0 && d <= 4096, "D must be in 1...4096")+ precondition(h2StrideElements >= d, "h2 stride is too small")+ precondition(h1StrideElements >= d, "h1 stride is too small")+ precondition(hiddenStrideElements >= d, "hidden stride is too small")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(h2, offset: h2Offset, index: 0)+ enc.setBuffer(h1, offset: h1Offset, index: 1)+ enc.setBuffer(hidden, offset: hiddenOffset, index: 2)+ enc.setBuffer(postFFN2Weight, offset: postFFN2WeightOffset, index: 3)+ enc.setBuffer(postFFNWeight, offset: postFFNWeightOffset, index: 4)+ var tVar = queryCount+ var dVar = d+ var h2Stride = h2StrideElements+ var h1Stride = h1StrideElements+ var hiddenStride = hiddenStrideElements+ var epsVar = eps+ var scaleVar = layerScalar+ enc.setBytes(&tVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 6)+ enc.setBytes(&h2Stride, length: MemoryLayout<UInt32>.size, index: 7)+ enc.setBytes(&h1Stride, length: MemoryLayout<UInt32>.size, index: 8)+ enc.setBytes(&hiddenStride, length: MemoryLayout<UInt32>.size, index: 9)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 10)+ enc.setBytes(&scaleVar, length: MemoryLayout<Float>.size, index: 11)++ let threads = min(pso.maxTotalThreadsPerThreadgroup, 256)+ enc.dispatchThreadgroups(MTLSize(width: Int(queryCount), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillPostAttentionSetup.swift b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillPostAttentionSetup.swiftnew file mode 100644index 00000000..bbf5b2fa--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillPostAttentionSetup.swift@@ -0,0 +1,75 @@+import Foundation+import Metal++final class PrefillPostAttentionSetup {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("prefill_post_attn_setup_block")+ }++ func encode(commandBuffer: MTLCommandBuffer,+ hidden: MTLBuffer,+ hiddenOffset: Int = 0,+ attn: MTLBuffer,+ attnOffset: Int = 0,+ denseX: MTLBuffer,+ denseXOffset: Int = 0,+ routedX: MTLBuffer,+ routedXOffset: Int = 0,+ routerX: MTLBuffer,+ routerXOffset: Int = 0,+ postAttentionWeight: MTLBuffer,+ postAttentionWeightOffset: Int = 0,+ preFFNWeight: MTLBuffer,+ preFFNWeightOffset: Int = 0,+ preFFN2Weight: MTLBuffer,+ preFFN2WeightOffset: Int = 0,+ queryCount: UInt32,+ d: UInt32,+ hiddenStrideElements: UInt32,+ attnStrideElements: UInt32,+ denseStrideElements: UInt32,+ routedStrideElements: UInt32,+ routerStrideElements: UInt32,+ eps: Float) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(d > 0 && d <= 4096, "D must be in 1...4096")+ precondition(hiddenStrideElements >= d, "hidden stride is too small")+ precondition(attnStrideElements >= d, "attention stride is too small")+ precondition(denseStrideElements >= d, "dense stride is too small")+ precondition(routedStrideElements >= d, "routed stride is too small")+ precondition(routerStrideElements >= d, "router stride is too small")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(hidden, offset: hiddenOffset, index: 0)+ enc.setBuffer(attn, offset: attnOffset, index: 1)+ enc.setBuffer(denseX, offset: denseXOffset, index: 2)+ enc.setBuffer(routedX, offset: routedXOffset, index: 3)+ enc.setBuffer(routerX, offset: routerXOffset, index: 4)+ enc.setBuffer(postAttentionWeight, offset: postAttentionWeightOffset, index: 5)+ enc.setBuffer(preFFNWeight, offset: preFFNWeightOffset, index: 6)+ enc.setBuffer(preFFN2Weight, offset: preFFN2WeightOffset, index: 7)+ var tVar = queryCount+ var dVar = d+ var hiddenStride = hiddenStrideElements+ var attnStride = attnStrideElements+ var denseStride = denseStrideElements+ var routedStride = routedStrideElements+ var routerStride = routerStrideElements+ var epsVar = eps+ enc.setBytes(&tVar, length: MemoryLayout<UInt32>.size, index: 8)+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 9)+ enc.setBytes(&hiddenStride, length: MemoryLayout<UInt32>.size, index: 10)+ enc.setBytes(&attnStride, length: MemoryLayout<UInt32>.size, index: 11)+ enc.setBytes(&denseStride, length: MemoryLayout<UInt32>.size, index: 12)+ enc.setBytes(&routedStride, length: MemoryLayout<UInt32>.size, index: 13)+ enc.setBytes(&routerStride, length: MemoryLayout<UInt32>.size, index: 14)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 15)++ let threads = min(pso.maxTotalThreadsPerThreadgroup, 256)+ enc.dispatchThreadgroups(MTLSize(width: Int(queryCount), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillQKVEpilogue.swift b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillQKVEpilogue.swiftnew file mode 100644index 00000000..c616b1d6--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/Epilogues/PrefillQKVEpilogue.swift@@ -0,0 +1,122 @@+import Foundation+import Metal++final class PrefillQKVEpilogue {+ private let perHeadNorm: PrefillPerHeadNorm+ private let rope: PrefillRoPE++ init(context: MetalContext) throws {+ self.perHeadNorm = try PrefillPerHeadNorm(context: context)+ self.rope = try PrefillRoPE(context: context)+ }++ func encode(commandBuffer: MTLCommandBuffer,+ q: MTLBuffer,+ qOffset: Int = 0,+ k: MTLBuffer,+ kOffset: Int = 0,+ v: MTLBuffer,+ vOffset: Int = 0,+ qWeight: MTLBuffer,+ qWeightOffset: Int = 0,+ kWeight: MTLBuffer,+ kWeightOffset: Int = 0,+ startPosition: UInt32,+ queryCount: UInt32,+ headDim: UInt32,+ numQHeads: UInt32,+ numKVHeads: UInt32,+ qTokenStrideElements: UInt32,+ kvTokenStrideElements: UInt32,+ theta: Float,+ rotatedPairs: UInt32,+ eps: Float) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(headDim > 0 && headDim % 2 == 0, "headDim must be positive and even")+ precondition(numQHeads > 0, "numQHeads must be positive")+ precondition(numKVHeads > 0, "numKVHeads must be positive")+ precondition(rotatedPairs > 0, "rotatedPairs must be positive")+ precondition(rotatedPairs * 2 <= headDim, "rotatedPairs must fit inside one head")+ precondition(qTokenStrideElements >= numQHeads * headDim,+ "Q token stride is too small")+ precondition(kvTokenStrideElements >= numKVHeads * headDim,+ "KV token stride is too small")++ perHeadNorm.encodeBF16W(commandBuffer: commandBuffer,+ x: q,+ xOffset: qOffset,+ weight: qWeight,+ weightOffset: qWeightOffset,+ out: q,+ outOffset: qOffset,+ queryCount: queryCount,+ headDim: headDim,+ numHeads: numQHeads,+ tokenStrideElements: qTokenStrideElements,+ eps: eps)+ perHeadNorm.encodeBF16W(commandBuffer: commandBuffer,+ x: k,+ xOffset: kOffset,+ weight: kWeight,+ weightOffset: kWeightOffset,+ out: k,+ outOffset: kOffset,+ queryCount: queryCount,+ headDim: headDim,+ numHeads: numKVHeads,+ tokenStrideElements: kvTokenStrideElements,+ eps: eps)+ perHeadNorm.encodeNoScale(commandBuffer: commandBuffer,+ x: v,+ xOffset: vOffset,+ out: v,+ outOffset: vOffset,+ queryCount: queryCount,+ headDim: headDim,+ numHeads: numKVHeads,+ tokenStrideElements: kvTokenStrideElements,+ eps: eps)++ if rotatedPairs * 2 == headDim {+ rope.encodeDefaultNeox(commandBuffer: commandBuffer,+ data: q,+ dataOffset: qOffset,+ startPosition: startPosition,+ queryCount: queryCount,+ headDim: headDim,+ numHeads: numQHeads,+ tokenStrideElements: qTokenStrideElements,+ theta: theta)+ rope.encodeDefaultNeox(commandBuffer: commandBuffer,+ data: k,+ dataOffset: kOffset,+ startPosition: startPosition,+ queryCount: queryCount,+ headDim: headDim,+ numHeads: numKVHeads,+ tokenStrideElements: kvTokenStrideElements,+ theta: theta)+ } else {+ rope.encodeProportionalNeox(commandBuffer: commandBuffer,+ data: q,+ dataOffset: qOffset,+ startPosition: startPosition,+ queryCount: queryCount,+ headDim: headDim,+ numHeads: numQHeads,+ rotatedPairs: rotatedPairs,+ tokenStrideElements: qTokenStrideElements,+ theta: theta)+ rope.encodeProportionalNeox(commandBuffer: commandBuffer,+ data: k,+ dataOffset: kOffset,+ startPosition: startPosition,+ queryCount: queryCount,+ headDim: headDim,+ numHeads: numKVHeads,+ rotatedPairs: rotatedPairs,+ tokenStrideElements: kvTokenStrideElements,+ theta: theta)+ }+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillGroupedRoutedMoE.swift b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillGroupedRoutedMoE.swiftnew file mode 100644index 00000000..9f94b30a--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillGroupedRoutedMoE.swift@@ -0,0 +1,463 @@+import Foundation+import Metal+import Darwin++enum PrefillGroupedRoutedMoEBufferIndex {+ static let hidden = 0+ static let sortedPairs = 1+ static let routePartials = 5+ static let gateUpActScratch = 7+ static let downScratch = 8+ static let expertArgumentState = 9+ static let params = 10+}++struct PrefillGroupedRoutedMoEStreamedMetadataBuffers {+ let sortedPairs: MTLBuffer+}++struct PrefillStreamedTileArgumentBuffer {+ let buffer: MTLBuffer+}++public struct PrefillStreamedTileFetchResult {+ public let expertIDs: [Int]+ public let binding: PrefillStreamedTileBinding+ public let usedPlannedFetch: Bool+ public let plannedHits: Int+ public let plannedMissIndices: [Int]+ public let plannedAssignedSlots: [Int]+ public let plannedMissSlots: [Int]++ public init(expertIDs: [Int],+ binding: PrefillStreamedTileBinding,+ usedPlannedFetch: Bool,+ plannedHits: Int,+ plannedMissIndices: [Int],+ plannedAssignedSlots: [Int],+ plannedMissSlots: [Int]) {+ self.expertIDs = expertIDs+ self.binding = binding+ self.usedPlannedFetch = usedPlannedFetch+ self.plannedHits = plannedHits+ self.plannedMissIndices = plannedMissIndices+ self.plannedAssignedSlots = plannedAssignedSlots+ self.plannedMissSlots = plannedMissSlots+ }+}++enum PrefillStreamedTileLifetimeError: Error, Equatable, CustomStringConvertible {+ case duplicateSlots(tileIndex: Int, slots: [Int])+ case slotReuseBeforeCompletion(tileIndex: Int, conflictingTileIndex: Int, slots: [Int])+ case completeWithoutInFlightTile(tileIndex: Int)++ public var description: String {+ switch self {+ case .duplicateSlots(let tileIndex, let slots):+ return "prefill streamed tile \(tileIndex) has duplicate planned slots \(slots)"+ case .slotReuseBeforeCompletion(let tileIndex, let conflictingTileIndex, let slots):+ return "prefill streamed tile \(tileIndex) would reuse planned slots \(slots) while tile \(conflictingTileIndex) is in flight"+ case .completeWithoutInFlightTile(let tileIndex):+ return "prefill streamed tile \(tileIndex) completed without a matching in-flight tile"+ }+ }+}++struct PrefillStreamedTileSlotLifetime: Sendable, Equatable {+ private var inFlightSlotsByTile: [Int: Set<Int>] = [:]++ init() {}++ mutating func begin(tileIndex: Int, plannedSlots: [Int]) throws {+ let slots = try normalizedSlots(tileIndex: tileIndex, plannedSlots: plannedSlots)+ for (otherTile, otherSlots) in inFlightSlotsByTile {+ let overlap = slots.intersection(otherSlots)+ if !overlap.isEmpty {+ throw PrefillStreamedTileLifetimeError.slotReuseBeforeCompletion(+ tileIndex: tileIndex,+ conflictingTileIndex: otherTile,+ slots: overlap.sorted())+ }+ }+ inFlightSlotsByTile[tileIndex] = slots+ }++ mutating func complete(tileIndex: Int) throws {+ guard inFlightSlotsByTile.removeValue(forKey: tileIndex) != nil else {+ throw PrefillStreamedTileLifetimeError.completeWithoutInFlightTile(tileIndex: tileIndex)+ }+ }++ private func normalizedSlots(tileIndex: Int, plannedSlots: [Int]) throws -> Set<Int> {+ var slots = Set<Int>()+ for slot in plannedSlots {+ guard slots.insert(slot).inserted else {+ throw PrefillStreamedTileLifetimeError.duplicateSlots(+ tileIndex: tileIndex,+ slots: plannedSlots.sorted())+ }+ }+ return slots+ }+}++struct PrefillGroupedRoutedMoEStreamedParams: Equatable, Sendable {+ var pairStart: UInt32+ var pairCount: UInt32+ var d: UInt32+ var routedIntermediate: UInt32+ var topK: UInt32+ var hiddenStrideElements: UInt32+ var liveExpertCount: UInt32+ var localExpert0: UInt32+ var localExpert1: UInt32+ var localExpert2: UInt32+ var localExpert3: UInt32+ var localExpert4: UInt32+ var localExpert5: UInt32+ var localExpert6: UInt32+ var localExpert7: UInt32+ var localExpert8: UInt32+ var localExpert9: UInt32+ var localExpert10: UInt32+ var localExpert11: UInt32+ var localExpert12: UInt32+ var localExpert13: UInt32+ var localExpert14: UInt32+ var localExpert15: UInt32+ var gateWOff: UInt32+ var gateSOff: UInt32+ var gateBOff: UInt32+ var upWOff: UInt32+ var upSOff: UInt32+ var upBOff: UInt32+ var downWOff: UInt32+ var downSOff: UInt32+ var downBOff: UInt32++ init(pairStart: UInt32,+ pairCount: UInt32,+ d: UInt32,+ routedIntermediate: UInt32,+ topK: UInt32,+ hiddenStrideElements: UInt32,+ binding: PrefillStreamedTileBinding,+ offsets: MoEExpertOffsets) {+ var ids = Array(repeating: UInt32.max, count: 16)+ for (index, expert) in binding.expertIDs.enumerated() {+ ids[index] = UInt32(expert)+ }+ self.pairStart = pairStart+ self.pairCount = pairCount+ self.d = d+ self.routedIntermediate = routedIntermediate+ self.topK = topK+ self.hiddenStrideElements = hiddenStrideElements+ self.liveExpertCount = UInt32(binding.expertIDs.count)+ self.localExpert0 = ids[0]+ self.localExpert1 = ids[1]+ self.localExpert2 = ids[2]+ self.localExpert3 = ids[3]+ self.localExpert4 = ids[4]+ self.localExpert5 = ids[5]+ self.localExpert6 = ids[6]+ self.localExpert7 = ids[7]+ self.localExpert8 = ids[8]+ self.localExpert9 = ids[9]+ self.localExpert10 = ids[10]+ self.localExpert11 = ids[11]+ self.localExpert12 = ids[12]+ self.localExpert13 = ids[13]+ self.localExpert14 = ids[14]+ self.localExpert15 = ids[15]+ self.gateWOff = offsets.gateWOff+ self.gateSOff = offsets.gateSOff+ self.gateBOff = offsets.gateBOff+ self.upWOff = offsets.upWOff+ self.upSOff = offsets.upSOff+ self.upBOff = offsets.upBOff+ self.downWOff = offsets.downWOff+ self.downSOff = offsets.downSOff+ self.downBOff = offsets.downBOff+ }+}++public struct PrefillStreamedTileBinding: Sendable, Equatable {+ public let expertIDs: [Int]+ public let views: [TensorView]++ public init(expertIDs: [Int], views: [TensorView]) throws {+ guard !expertIDs.isEmpty else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding("tile binding must include at least one expert")+ }+ guard expertIDs.count <= 16 else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "tile binding has \(expertIDs.count) experts; maximum is 16")+ }+ guard expertIDs.count == views.count else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "expertIDs.count \(expertIDs.count) != views.count \(views.count)")+ }+ var seen = Set<Int>()+ for expert in expertIDs {+ guard expert >= 0 else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "expert id \(expert) must be non-negative")+ }+ guard seen.insert(expert).inserted else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "duplicate expert id \(expert) in tile binding")+ }+ }+ self.expertIDs = expertIDs+ self.views = views+ }++ public func localSlot(for expert: UInt32) -> Int? {+ expertIDs.firstIndex(of: Int(expert))+ }++ public static func expertIDs(forTile tileIndex: Int,+ routes: PrefillMoEGroupedRoutes) throws -> [Int] {+ guard routes.tiles.indices.contains(tileIndex) else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "tile index \(tileIndex) is out of range")+ }+ let tile = routes.tiles[tileIndex]+ let groupStart = Int(tile.groupStart)+ let groupCount = Int(tile.groupCount)+ guard groupCount > 0, groupCount <= 16 else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "tile has \(groupCount) live experts; expected 1...16")+ }+ guard groupStart >= 0, groupStart + groupCount <= routes.groups.count else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "tile group range \(groupStart)..<\(groupStart + groupCount) exceeds \(routes.groups.count)")+ }+ return routes.groups[groupStart..<(groupStart + groupCount)].map { Int($0.expert) }+ }++ public static func fetchBindingForTile(model: Model,+ layer: Int,+ tileIndex: Int,+ routes: PrefillMoEGroupedRoutes,+ plannedFetch: RoutedExpertFetchPlan? = nil,+ avoidingSlots: Set<Int> = []) async throws+ -> PrefillStreamedTileFetchResult {+ let expertIDs = try expertIDs(forTile: tileIndex, routes: routes)+ let plan = try plannedFetch ?? model.planRoutedExperts(layer: layer,+ experts: expertIDs,+ avoidingSlots: avoidingSlots)+ let views: [TensorView]+ let usedPlannedFetch: Bool+ let plannedHits: Int+ let plannedMissIndices: [Int]+ let plannedAssignedSlots: [Int]+ let plannedMissSlots: [Int]+ if let plan {+ guard plan.layer == layer, plan.experts == expertIDs else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "preplanned fetch does not match tile \(tileIndex)")+ }+ views = try await model.fetchRoutedExperts(plan: plan)+ usedPlannedFetch = true+ plannedHits = plan.hits+ plannedMissIndices = plan.misses+ plannedAssignedSlots = plan.assignedSlots+ plannedMissSlots = plan.misses.map { plan.assignedSlots[$0] }+ } else {+ views = try await model.fetchRoutedExperts(layer: layer, experts: expertIDs)+ usedPlannedFetch = false+ plannedHits = 0+ plannedMissIndices = []+ plannedAssignedSlots = []+ plannedMissSlots = []+ }+ let binding = try PrefillStreamedTileBinding(expertIDs: expertIDs, views: views)+ return PrefillStreamedTileFetchResult(expertIDs: expertIDs,+ binding: binding,+ usedPlannedFetch: usedPlannedFetch,+ plannedHits: plannedHits,+ plannedMissIndices: plannedMissIndices,+ plannedAssignedSlots: plannedAssignedSlots,+ plannedMissSlots: plannedMissSlots)+ }++ public func validateCoversPairs(_ pairs: [PrefillTokenExpertPair],+ pairStart: Int,+ pairCount: Int) throws {+ guard pairStart >= 0, pairCount >= 0, pairStart + pairCount <= pairs.count else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "pair range \(pairStart)..<\(pairStart + pairCount) exceeds \(pairs.count)")+ }+ for pair in pairs[pairStart..<(pairStart + pairCount)] {+ guard localSlot(for: pair.expert) != nil else {+ throw PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(+ "route expert \(pair.expert) is not bound in tile")+ }+ }+ }++ public static func == (lhs: PrefillStreamedTileBinding,+ rhs: PrefillStreamedTileBinding) -> Bool {+ guard lhs.expertIDs == rhs.expertIDs, lhs.views.count == rhs.views.count else {+ return false+ }+ for index in lhs.views.indices {+ let l = lhs.views[index]+ let r = rhs.views[index]+ guard l.buffer === r.buffer,+ l.offset == r.offset,+ l.length == r.length,+ l.scaleOffset == r.scaleOffset,+ l.scaleLength == r.scaleLength,+ l.biasOffset == r.biasOffset,+ l.biasLength == r.biasLength,+ l.shape == r.shape,+ l.dtype == r.dtype else {+ return false+ }+ }+ return true+ }+}++enum PrefillGroupedRoutedMoEError: Error, Equatable, CustomStringConvertible {+ case invalidStreamedTileBinding(String)+ case allocationFailed(String)++ public var description: String {+ switch self {+ case .invalidStreamedTileBinding(let reason):+ return "invalid streamed tile binding: \(reason)"+ case .allocationFailed(let label):+ return "failed to allocate \(label)"+ }+ }+}++final class PrefillGroupedRoutedMoE {+ private let batchedPhase1PSO: MTLComputePipelineState+ private let batchedDownPSO: MTLComputePipelineState+ private let streamedArgEncoder: MTLArgumentEncoder++ func makeStreamedArgumentBuffer(device: MTLDevice,+ binding: PrefillStreamedTileBinding) throws -> PrefillStreamedTileArgumentBuffer {+ guard let buffer = device.makeBuffer(length: streamedArgEncoder.encodedLength,+ options: .storageModeShared) else {+ throw PrefillGroupedRoutedMoEError.allocationFailed("prefill streamed expert argument buffer")+ }+ buffer.label = "prefill.groupedMoe.streamedArgumentBuffer"++ streamedArgEncoder.setArgumentBuffer(buffer, offset: 0)+ for index in binding.views.indices {+ let view = binding.views[index]+ streamedArgEncoder.setBuffer(view.buffer, offset: Int(view.offset), index: index)+ }++ return PrefillStreamedTileArgumentBuffer(buffer: buffer)+ }++ init(context: MetalContext) throws {+ self.batchedPhase1PSO = try context.pipeline("prefill_grouped_routed_moe_batched_phase1")+ self.batchedDownPSO = try context.pipeline("prefill_grouped_routed_moe_batched_down")+ guard let streamedFn = context.library.makeFunction(name: "prefill_grouped_routed_moe_batched_phase1") else {+ throw MetalError.missingFunction("prefill_grouped_routed_moe_batched_phase1")+ }+ self.streamedArgEncoder = streamedFn.makeArgumentEncoder(+ bufferIndex: PrefillGroupedRoutedMoEBufferIndex.expertArgumentState)+ }++ func makeStreamedMetadataBuffers(+ device: MTLDevice,+ routes: PrefillMoEGroupedRoutes+ ) throws -> PrefillGroupedRoutedMoEStreamedMetadataBuffers {+ let bytes = routes.sortedPairs.count * MemoryLayout<PrefillTokenExpertPair>.stride+ guard let sortedPairs = routes.sortedPairs.withUnsafeBufferPointer({ ptr in+ device.makeBuffer(bytes: ptr.baseAddress!,+ length: bytes,+ options: .storageModeShared)+ }) else {+ throw PrefillGroupedRoutedMoEError.allocationFailed("prefill sorted route pairs")+ }+ return PrefillGroupedRoutedMoEStreamedMetadataBuffers(sortedPairs: sortedPairs)+ }++ @discardableResult+ func encodeStreamedBatched(commandBuffer: MTLCommandBuffer,+ hidden: MTLBuffer,+ hiddenOffset: Int = 0,+ sortedPairs: MTLBuffer,+ sortedPairsOffset: Int = 0,+ routePartials: MTLBuffer,+ routePartialsOffset: Int = 0,+ gateUpActScratch: MTLBuffer,+ gateUpActScratchOffset: Int = 0,+ downScratch: MTLBuffer,+ downScratchOffset: Int = 0,+ argumentBuffer: PrefillStreamedTileArgumentBuffer,+ binding: PrefillStreamedTileBinding,+ params: PrefillGroupedRoutedMoEStreamedParams,+ pairMicrobatchRows: Int = 32) -> Int {+ guard params.pairCount > 0,+ params.liveExpertCount == UInt32(binding.views.count),+ pairMicrobatchRows > 0 else { return 0 }+ var consumed: UInt32 = 0+ var microbatchCount = 0+ while consumed < params.pairCount {+ var p = params+ p.pairStart = params.pairStart + consumed+ p.pairCount = min(UInt32(pairMicrobatchRows), params.pairCount - consumed)++ if let enc = commandBuffer.makeComputeCommandEncoder() {+ enc.setComputePipelineState(batchedPhase1PSO)+ enc.setBuffer(hidden, offset: hiddenOffset, index: PrefillGroupedRoutedMoEBufferIndex.hidden)+ enc.setBuffer(sortedPairs, offset: sortedPairsOffset, index: PrefillGroupedRoutedMoEBufferIndex.sortedPairs)+ enc.setBuffer(gateUpActScratch, offset: gateUpActScratchOffset,+ index: PrefillGroupedRoutedMoEBufferIndex.gateUpActScratch)+ enc.setBuffer(argumentBuffer.buffer, offset: 0,+ index: PrefillGroupedRoutedMoEBufferIndex.expertArgumentState)+ enc.setBytes(&p,+ length: MemoryLayout<PrefillGroupedRoutedMoEStreamedParams>.stride,+ index: PrefillGroupedRoutedMoEBufferIndex.params)+ for view in binding.views {+ enc.useResource(view.buffer, usage: .read)+ }+ enc.dispatchThreads(MTLSize(width: Int(p.routedIntermediate),+ height: Int(p.pairCount),+ depth: 1),+ threadsPerThreadgroup: MTLSize(width: 8, height: 8, depth: 1))+ enc.endEncoding()+ }++ if let enc = commandBuffer.makeComputeCommandEncoder() {+ enc.setComputePipelineState(batchedDownPSO)+ enc.setBuffer(sortedPairs, offset: sortedPairsOffset, index: PrefillGroupedRoutedMoEBufferIndex.sortedPairs)+ enc.setBuffer(routePartials, offset: routePartialsOffset,+ index: PrefillGroupedRoutedMoEBufferIndex.routePartials)+ enc.setBuffer(gateUpActScratch, offset: gateUpActScratchOffset,+ index: PrefillGroupedRoutedMoEBufferIndex.gateUpActScratch)+ enc.setBuffer(downScratch, offset: downScratchOffset,+ index: PrefillGroupedRoutedMoEBufferIndex.downScratch)+ enc.setBuffer(argumentBuffer.buffer, offset: 0,+ index: PrefillGroupedRoutedMoEBufferIndex.expertArgumentState)+ enc.setBytes(&p,+ length: MemoryLayout<PrefillGroupedRoutedMoEStreamedParams>.stride,+ index: PrefillGroupedRoutedMoEBufferIndex.params)+ for view in binding.views {+ enc.useResource(view.buffer, usage: .read)+ }+ enc.dispatchThreads(MTLSize(width: Int(p.d),+ height: Int(p.pairCount),+ depth: 1),+ threadsPerThreadgroup: MTLSize(width: 8, height: 8, depth: 1))+ enc.endEncoding()+ }++ consumed += p.pairCount+ microbatchCount += 1+ }+ return microbatchCount+ }++}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillMoE.swift b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillMoE.swiftnew file mode 100644index 00000000..0077292a--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillMoE.swift@@ -0,0 +1,40 @@+import Foundation+import Metal++final class PrefillMoE {+ private let reducePSO: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.reducePSO = try context.pipeline("prefill_moe_reduce_token_major")+ }++ func encodeReduceTokenMajor(commandBuffer: MTLCommandBuffer,+ routePartials: MTLBuffer,+ routePartialsOffset: Int = 0,+ routeWeights: MTLBuffer,+ routeWeightsOffset: Int = 0,+ h2: MTLBuffer,+ h2Offset: Int = 0,+ queryCount: UInt32,+ topK: UInt32,+ d: UInt32) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(topK > 0, "topK must be positive")+ precondition(d > 0, "D must be positive")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(reducePSO)+ enc.setBuffer(routePartials, offset: routePartialsOffset, index: 0)+ enc.setBuffer(routeWeights, offset: routeWeightsOffset, index: 1)+ enc.setBuffer(h2, offset: h2Offset, index: 2)+ var tVar = queryCount+ var topKVar = topK+ var dVar = d+ enc.setBytes(&tVar, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&topKVar, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.dispatchThreads(MTLSize(width: Int(d), height: Int(queryCount), depth: 1),+ threadsPerThreadgroup: MTLSize(width: 16, height: 16, depth: 1))+ enc.endEncoding()+ }++}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillMoEGrouping.swift b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillMoEGrouping.swiftnew file mode 100644index 00000000..12d6c044--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillMoEGrouping.swift@@ -0,0 +1,193 @@+import Foundation++@frozen+public struct PrefillMoEGroup: Equatable, Sendable {+ public var expert: UInt32+ public var pairStart: UInt32+ public var pairCount: UInt32++ public init(expert: UInt32, pairStart: UInt32, pairCount: UInt32) {+ self.expert = expert+ self.pairStart = pairStart+ self.pairCount = pairCount+ }+}++@frozen+public struct PrefillMoETile: Equatable, Sendable {+ public var groupStart: UInt32+ public var groupCount: UInt32+ public var pairStart: UInt32+ public var pairCount: UInt32++ public init(groupStart: UInt32, groupCount: UInt32, pairStart: UInt32, pairCount: UInt32) {+ self.groupStart = groupStart+ self.groupCount = groupCount+ self.pairStart = pairStart+ self.pairCount = pairCount+ }+}++public struct PrefillMoEGroupedRoutes: Equatable, Sendable {+ public let sortedPairs: [PrefillTokenExpertPair]+ public let perExpertOffsets: [UInt32]+ public let perExpertCounts: [UInt32]+ public let groups: [PrefillMoEGroup]+ public let tiles: [PrefillMoETile]+ public let queryCount: Int++ public var maxPairsPerExpert: Int {+ groups.map { Int($0.pairCount) }.max() ?? 0+ }++ public var maxPairsPerTile: Int {+ tiles.map { Int($0.pairCount) }.max() ?? 0+ }++ public var maxLiveExpertsPerTile: Int {+ tiles.map { Int($0.groupCount) }.max() ?? 0+ }+}++enum PrefillMoEGroupingError: Error, Equatable, CustomStringConvertible {+ case invalidQueryCount(Int)+ case invalidTopK(Int)+ case invalidNumExperts(Int)+ case invalidTileExpertCount(Int)+ case pairCountMismatch(expected: Int, actual: Int)+ case tokenOutOfRange(UInt32)+ case rankOutOfRange(UInt32)+ case expertOutOfRange(UInt32)+ case duplicateTokenRank(token: UInt32, rank: UInt32)+ case expertSortKeyCountMismatch(expected: Int, actual: Int)++ public var description: String {+ switch self {+ case .invalidQueryCount(let value):+ return "queryCount must be non-negative, got \(value)"+ case .invalidTopK(let value):+ return "topK must be positive, got \(value)"+ case .invalidNumExperts(let value):+ return "numExperts must be positive, got \(value)"+ case .invalidTileExpertCount(let value):+ return "tileExpertCount must be in 1...16, got \(value)"+ case .pairCountMismatch(let expected, let actual):+ return "expected \(expected) route pairs, got \(actual)"+ case .tokenOutOfRange(let value):+ return "route token \(value) is out of range"+ case .rankOutOfRange(let value):+ return "route rank \(value) is out of range"+ case .expertOutOfRange(let value):+ return "route expert \(value) is out of range"+ case .duplicateTokenRank(let token, let rank):+ return "duplicate route pair for token \(token), rank \(rank)"+ case .expertSortKeyCountMismatch(let expected, let actual):+ return "expected \(expected) expert sort keys, got \(actual)"+ }+ }+}++enum PrefillMoEGrouping {+ static func groupTokenExpertPairs(+ _ pairs: [PrefillTokenExpertPair],+ queryCount: Int,+ topK: Int,+ numExperts: Int,+ tileExpertCount: Int = 16,+ expertSortKeys: [UInt64]? = nil+ ) throws -> PrefillMoEGroupedRoutes {+ guard queryCount >= 0 else {+ throw PrefillMoEGroupingError.invalidQueryCount(queryCount)+ }+ guard topK > 0 else {+ throw PrefillMoEGroupingError.invalidTopK(topK)+ }+ guard numExperts > 0 else {+ throw PrefillMoEGroupingError.invalidNumExperts(numExperts)+ }+ guard (1...16).contains(tileExpertCount) else {+ throw PrefillMoEGroupingError.invalidTileExpertCount(tileExpertCount)+ }+ if let expertSortKeys, expertSortKeys.count != numExperts {+ throw PrefillMoEGroupingError.expertSortKeyCountMismatch(expected: numExperts,+ actual: expertSortKeys.count)+ }+ let expectedPairs = queryCount * topK+ guard pairs.count == expectedPairs else {+ throw PrefillMoEGroupingError.pairCountMismatch(expected: expectedPairs,+ actual: pairs.count)+ }++ var seenTokenRanks: Set<UInt64> = []+ seenTokenRanks.reserveCapacity(pairs.count)+ for pair in pairs {+ guard pair.token < UInt32(queryCount) else {+ throw PrefillMoEGroupingError.tokenOutOfRange(pair.token)+ }+ guard pair.rank < UInt32(topK) else {+ throw PrefillMoEGroupingError.rankOutOfRange(pair.rank)+ }+ guard pair.expert < UInt32(numExperts) else {+ throw PrefillMoEGroupingError.expertOutOfRange(pair.expert)+ }+ let key = UInt64(pair.token) << 32 | UInt64(pair.rank)+ guard seenTokenRanks.insert(key).inserted else {+ throw PrefillMoEGroupingError.duplicateTokenRank(token: pair.token,+ rank: pair.rank)+ }+ }++ let sortedPairs = pairs.sorted {+ if let expertSortKeys {+ let lhsKey = expertSortKeys[Int($0.expert)]+ let rhsKey = expertSortKeys[Int($1.expert)]+ if lhsKey != rhsKey { return lhsKey < rhsKey }+ }+ if $0.expert != $1.expert { return $0.expert < $1.expert }+ if $0.token != $1.token { return $0.token < $1.token }+ return $0.rank < $1.rank+ }++ var offsets = Array(repeating: UInt32.max, count: numExperts)+ var counts = Array(repeating: UInt32(0), count: numExperts)+ var groups: [PrefillMoEGroup] = []+ groups.reserveCapacity(min(numExperts, sortedPairs.count))++ var i = 0+ while i < sortedPairs.count {+ let expert = sortedPairs[i].expert+ let start = i+ while i < sortedPairs.count, sortedPairs[i].expert == expert {+ i += 1+ }+ let count = i - start+ offsets[Int(expert)] = UInt32(start)+ counts[Int(expert)] = UInt32(count)+ groups.append(PrefillMoEGroup(expert: expert,+ pairStart: UInt32(start),+ pairCount: UInt32(count)))+ }++ var tiles: [PrefillMoETile] = []+ var groupStart = 0+ while groupStart < groups.count {+ let groupEnd = min(groups.count, groupStart + tileExpertCount)+ let first = groups[groupStart]+ let last = groups[groupEnd - 1]+ let pairStart = first.pairStart+ let pairEnd = last.pairStart + last.pairCount+ tiles.append(PrefillMoETile(groupStart: UInt32(groupStart),+ groupCount: UInt32(groupEnd - groupStart),+ pairStart: pairStart,+ pairCount: pairEnd - pairStart))+ groupStart = groupEnd+ }++ return PrefillMoEGroupedRoutes(sortedPairs: sortedPairs,+ perExpertOffsets: offsets,+ perExpertCounts: counts,+ groups: groups,+ tiles: tiles,+ queryCount: queryCount)+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillRoutedTileScheduler.swift b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillRoutedTileScheduler.swiftnew file mode 100644index 00000000..38c5d753--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillRoutedTileScheduler.swift@@ -0,0 +1,67 @@+enum PrefillRoutedTileSchedulerDrainReason: Sendable, Equatable {+ case pendingTileHasNoAssignedSlots+ case avoidingSlotPlanUnavailable+ case maxPendingDepthReached+}++enum PrefillRoutedTileSchedulerDecision: Sendable, Equatable {+ case issueWithoutPending+ case prefetchNext(avoidingSlots: [Int])+ case drainBeforeIssue(reason: PrefillRoutedTileSchedulerDrainReason)+}++struct PrefillRoutedTileSchedulerInput: Sendable, Equatable {+ let hasPendingTile: Bool+ let pendingDepth: Int+ let pendingAssignedSlots: [Int]+ let avoidingSlotPlanAvailable: Bool++ init(hasPendingTile: Bool,+ pendingDepth: Int? = nil,+ pendingAssignedSlots: [Int],+ avoidingSlotPlanAvailable: Bool) {+ self.hasPendingTile = hasPendingTile+ self.pendingDepth = max(0, pendingDepth ?? (hasPendingTile ? 1 : 0))+ self.pendingAssignedSlots = pendingAssignedSlots+ self.avoidingSlotPlanAvailable = avoidingSlotPlanAvailable+ }+}++struct PrefillRoutedTileSchedulerConfig: Sendable, Equatable {+ let maxPendingDepth: Int+ let tileExperts: Int++ init(maxPendingDepth: Int = 1, tileExperts: Int = 8) {+ self.maxPendingDepth = max(1, maxPendingDepth)+ self.tileExperts = max(1, min(16, tileExperts))+ }++ func fitsSlotBudget(slotCount: Int, reservedHits: Int = 0) -> Bool {+ guard slotCount > 0, reservedHits >= 0 else { return false }+ return (maxPendingDepth + 1) * tileExperts + reservedHits <= slotCount+ }+}++struct PrefillRoutedTileScheduler: Sendable, Equatable {+ let config: PrefillRoutedTileSchedulerConfig++ init(config: PrefillRoutedTileSchedulerConfig = PrefillRoutedTileSchedulerConfig()) {+ self.config = config+ }++ func decide(_ input: PrefillRoutedTileSchedulerInput) -> PrefillRoutedTileSchedulerDecision {+ guard input.hasPendingTile else {+ return .issueWithoutPending+ }+ guard input.pendingDepth <= config.maxPendingDepth else {+ return .drainBeforeIssue(reason: .maxPendingDepthReached)+ }+ guard !input.pendingAssignedSlots.isEmpty else {+ return .drainBeforeIssue(reason: .pendingTileHasNoAssignedSlots)+ }+ guard input.avoidingSlotPlanAvailable else {+ return .drainBeforeIssue(reason: .avoidingSlotPlanUnavailable)+ }+ return .prefetchNext(avoidingSlots: input.pendingAssignedSlots)+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillRouter.swift b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillRouter.swiftnew file mode 100644index 00000000..da817df8--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillRouter.swift@@ -0,0 +1,112 @@+import Foundation+import Metal++@frozen+public struct PrefillTokenExpertPair: Equatable, Sendable {+ public var token: UInt32+ public var expert: UInt32+ public var rank: UInt32+ public var weightBitsAndReserved: UInt32++ public init(token: UInt32, expert: UInt32, rank: UInt32, weight: Float16) {+ self.token = token+ self.expert = expert+ self.rank = rank+ self.weightBitsAndReserved = UInt32(weight.bitPattern)+ }++ public init(token: UInt32, expert: UInt32, rank: UInt32, weightBitsAndReserved: UInt32) {+ self.token = token+ self.expert = expert+ self.rank = rank+ self.weightBitsAndReserved = weightBitsAndReserved+ }++ public var weight: Float16 {+ Float16(bitPattern: UInt16(truncatingIfNeeded: weightBitsAndReserved))+ }+}++final class PrefillRouter {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("prefill_router_gemma4_block")+ }++ func encodeGemma4Block(commandBuffer: MTLCommandBuffer,+ weights: MTLBuffer,+ weightsOffset: Int = 0,+ scales: MTLBuffer,+ scalesOffset: Int = 0,+ biases: MTLBuffer,+ biasesOffset: Int = 0,+ hidden: MTLBuffer,+ hiddenOffset: Int = 0,+ effectiveScale: MTLBuffer,+ effectiveScaleOffset: Int = 0,+ perExpertScale: MTLBuffer,+ perExpertScaleOffset: Int = 0,+ outIndices: MTLBuffer,+ outIndicesOffset: Int = 0,+ outWeights: MTLBuffer,+ outWeightsOffset: Int = 0,+ queryCount: UInt32,+ numExperts: UInt32,+ d: UInt32,+ topK: UInt32,+ hiddenStrideElements: UInt32) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(numExperts <= 256, "numExperts > 256 is not supported")+ precondition(topK > 0 && topK <= 64, "topK must be in 1...64")+ precondition(d % UInt32(Quantization.groupSize) == 0,+ "D must be a multiple of \(Quantization.groupSize)")+ precondition(hiddenStrideElements >= d, "hidden stride is too small")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(weights, offset: weightsOffset, index: 0)+ enc.setBuffer(scales, offset: scalesOffset, index: 1)+ enc.setBuffer(biases, offset: biasesOffset, index: 2)+ enc.setBuffer(hidden, offset: hiddenOffset, index: 3)+ enc.setBuffer(effectiveScale, offset: effectiveScaleOffset, index: 4)+ enc.setBuffer(perExpertScale, offset: perExpertScaleOffset, index: 5)+ enc.setBuffer(outIndices, offset: outIndicesOffset, index: 6)+ enc.setBuffer(outWeights, offset: outWeightsOffset, index: 7)+ var tVar = queryCount+ var neVar = numExperts+ var dVar = d+ var topKVar = topK+ var strideVar = hiddenStrideElements+ enc.setBytes(&tVar, length: MemoryLayout<UInt32>.size, index: 8)+ enc.setBytes(&neVar, length: MemoryLayout<UInt32>.size, index: 9)+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 10)+ enc.setBytes(&topKVar, length: MemoryLayout<UInt32>.size, index: 11)+ enc.setBytes(&strideVar, length: MemoryLayout<UInt32>.size, index: 12)+ let tgWidth = min(max(Int(numExperts), 32), pso.maxTotalThreadsPerThreadgroup)+ enc.dispatchThreadgroups(MTLSize(width: Int(queryCount), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: tgWidth, height: 1, depth: 1))+ enc.endEncoding()+ }++ static func makeTokenExpertPairs(indices: [UInt32],+ weights: [Float16],+ queryCount: Int,+ topK: Int) -> [PrefillTokenExpertPair] {+ precondition(queryCount >= 0, "queryCount must be non-negative")+ precondition(topK >= 0, "topK must be non-negative")+ precondition(indices.count == queryCount * topK, "indices count mismatch")+ precondition(weights.count == queryCount * topK, "weights count mismatch")+ var pairs: [PrefillTokenExpertPair] = []+ pairs.reserveCapacity(indices.count)+ for token in 0..<queryCount {+ for rank in 0..<topK {+ let i = token * topK + rank+ pairs.append(PrefillTokenExpertPair(token: UInt32(token),+ expert: indices[i],+ rank: UInt32(rank),+ weight: weights[i]))+ }+ }+ return pairs+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillSharedExpert.swift b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillSharedExpert.swiftnew file mode 100644index 00000000..45762965--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillSharedExpert.swift@@ -0,0 +1,52 @@+import Foundation+import Metal++final class PrefillSharedExpert {+ private let shared: SharedExpertInt8++ init(context: MetalContext) throws {+ self.shared = try SharedExpertInt8(context: context)+ }++ func encodeBlock(commandBuffer cb: MTLCommandBuffer,+ x: MTLBuffer,+ xOffset: Int = 0,+ y: MTLBuffer,+ yOffset: Int = 0,+ gate: SharedExpertInt8Proj,+ up: SharedExpertInt8Proj,+ down: SharedExpertInt8Proj,+ scratchAct: MTLBuffer,+ scratchActOffset: Int = 0,+ queryCount: Int,+ d: Int,+ intermediate: Int,+ xStrideElements: Int,+ yStrideElements: Int) throws {+ precondition(queryCount >= 0, "queryCount must be non-negative")+ precondition(d > 0, "d must be positive")+ precondition(intermediate > 0, "intermediate must be positive")+ precondition(xStrideElements >= d, "x stride is too small")+ precondition(yStrideElements >= d, "y stride is too small")+ guard gate.rows == UInt32(intermediate), gate.cols == UInt32(d),+ up.rows == UInt32(intermediate), up.cols == UInt32(d),+ down.rows == UInt32(d), down.cols == UInt32(intermediate) else {+ throw SharedExpertInt8Error.dimensionMismatch(+ "expected gate/up=(\(intermediate),\(d)) down=(\(d),\(intermediate))")+ }++ let halfBytes = MemoryLayout<Float16>.stride+ for row in 0..<queryCount {+ try shared.encode(commandBuffer: cb,+ x: x,+ xOffset: xOffset + row * xStrideElements * halfBytes,+ gate: gate,+ up: up,+ down: down,+ y: y,+ yOffset: yOffset + row * yStrideElements * halfBytes,+ scratchAct: scratchAct,+ scratchActOffset: scratchActOffset)+ }+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillPerHeadNorm.swift b/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillPerHeadNorm.swiftnew file mode 100644index 00000000..3887d35e--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillPerHeadNorm.swift@@ -0,0 +1,85 @@+import Foundation+import Metal++final class PrefillPerHeadNorm {+ private let psoBF16W: MTLComputePipelineState+ private let psoNoScale: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.psoBF16W = try context.pipeline("prefill_rmsnorm_bf16w_perhead_block")+ self.psoNoScale = try context.pipeline("prefill_rmsnorm_no_scale_perhead_block")+ }++ func encodeBF16W(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer,+ xOffset: Int = 0,+ weight: MTLBuffer,+ weightOffset: Int = 0,+ out: MTLBuffer,+ outOffset: Int = 0,+ queryCount: UInt32,+ headDim: UInt32,+ numHeads: UInt32,+ tokenStrideElements: UInt32,+ eps: Float) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(headDim > 0, "headDim must be positive")+ precondition(numHeads > 0, "numHeads must be positive")+ precondition(tokenStrideElements >= headDim * numHeads,+ "token stride is too small")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(psoBF16W)+ enc.setBuffer(x, offset: xOffset, index: 0)+ enc.setBuffer(weight, offset: weightOffset, index: 1)+ enc.setBuffer(out, offset: outOffset, index: 2)+ var t = queryCount+ var hd = headDim+ var heads = numHeads+ var stride = tokenStrideElements+ var epsVar = eps+ enc.setBytes(&t, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&hd, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&heads, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&stride, length: MemoryLayout<UInt32>.size, index: 6)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 7)+ let threads = min(psoBF16W.maxTotalThreadsPerThreadgroup, 256)+ enc.dispatchThreadgroups(MTLSize(width: Int(numHeads), height: Int(queryCount), depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }++ func encodeNoScale(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer,+ xOffset: Int = 0,+ out: MTLBuffer,+ outOffset: Int = 0,+ queryCount: UInt32,+ headDim: UInt32,+ numHeads: UInt32,+ tokenStrideElements: UInt32,+ eps: Float) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(headDim > 0, "headDim must be positive")+ precondition(numHeads > 0, "numHeads must be positive")+ precondition(tokenStrideElements >= headDim * numHeads,+ "token stride is too small")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(psoNoScale)+ enc.setBuffer(x, offset: xOffset, index: 0)+ enc.setBuffer(out, offset: outOffset, index: 1)+ var t = queryCount+ var hd = headDim+ var heads = numHeads+ var stride = tokenStrideElements+ var epsVar = eps+ enc.setBytes(&t, length: MemoryLayout<UInt32>.size, index: 2)+ enc.setBytes(&hd, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&heads, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&stride, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 6)+ let threads = min(psoNoScale.maxTotalThreadsPerThreadgroup, 256)+ enc.dispatchThreadgroups(MTLSize(width: Int(numHeads), height: Int(queryCount), depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillPrimitives.swift b/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillPrimitives.swiftnew file mode 100644index 00000000..f1ff1476--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillPrimitives.swift@@ -0,0 +1,109 @@+import Foundation+import Metal++final class PrefillEmbedLookupInt4 {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("prefill_embed_lookup_int4_block")+ }++ func encode(commandBuffer: MTLCommandBuffer,+ table: MTLBuffer, tableOffset: Int = 0,+ scales: MTLBuffer, scalesOffset: Int = 0,+ biases: MTLBuffer, biasesOffset: Int = 0,+ tokens: MTLBuffer, tokensOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ t: UInt32,+ d: UInt32,+ outScale: Float) {+ precondition(d % UInt32(Quantization.groupSize) == 0,+ "D must be a multiple of \(Quantization.groupSize)")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(table, offset: tableOffset, index: 0)+ enc.setBuffer(scales, offset: scalesOffset, index: 1)+ enc.setBuffer(biases, offset: biasesOffset, index: 2)+ enc.setBuffer(tokens, offset: tokensOffset, index: 3)+ enc.setBuffer(out, offset: outOffset, index: 4)+ var tVar = t+ var dVar = d+ var scaleVar = outScale+ enc.setBytes(&tVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 6)+ enc.setBytes(&scaleVar, length: MemoryLayout<Float>.size, index: 7)+ enc.dispatchThreads(MTLSize(width: Int(d), height: Int(t), depth: 1),+ threadsPerThreadgroup: MTLSize(width: 16, height: 16, depth: 1))+ enc.endEncoding()+ }+}++final class PrefillRMSNorm {+ private let psoBF16W: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.psoBF16W = try context.pipeline("prefill_rmsnorm_bf16w_block")+ }++ func encodeBF16W(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ weight: MTLBuffer, weightOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ t: UInt32,+ d: UInt32,+ eps: Float) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(psoBF16W)+ enc.setBuffer(x, offset: xOffset, index: 0)+ enc.setBuffer(weight, offset: weightOffset, index: 1)+ enc.setBuffer(out, offset: outOffset, index: 2)+ var tVar = t+ var dVar = d+ var epsVar = eps+ enc.setBytes(&tVar, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 5)+ let threads = min(Int(psoBF16W.maxTotalThreadsPerThreadgroup), 256)+ enc.dispatchThreadgroups(MTLSize(width: Int(t), height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))+ enc.endEncoding()+ }+}++final class PrefillInt4QMM {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("prefill_dequant_int4_qmm_f16_block")+ }++ func encode(commandBuffer: MTLCommandBuffer,+ weights: MTLBuffer, weightsOffset: Int = 0,+ scales: MTLBuffer, scalesOffset: Int = 0,+ biases: MTLBuffer, biasesOffset: Int = 0,+ x: MTLBuffer, xOffset: Int = 0,+ y: MTLBuffer, yOffset: Int = 0,+ t: Int,+ n: Int,+ k: Int) {+ precondition(k % Quantization.groupSize == 0,+ "K must be a multiple of \(Quantization.groupSize)")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(weights, offset: weightsOffset, index: 0)+ enc.setBuffer(scales, offset: scalesOffset, index: 1)+ enc.setBuffer(biases, offset: biasesOffset, index: 2)+ enc.setBuffer(x, offset: xOffset, index: 3)+ enc.setBuffer(y, offset: yOffset, index: 4)+ var tVar = UInt32(t)+ var nVar = UInt32(n)+ var kVar = UInt32(k)+ enc.setBytes(&tVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&nVar, length: MemoryLayout<UInt32>.size, index: 6)+ enc.setBytes(&kVar, length: MemoryLayout<UInt32>.size, index: 7)+ enc.dispatchThreadgroups(+ MTLSize(width: (n + 7) / 8, height: (t + 7) / 8, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 8, height: 8, depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillRoPE.swift b/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillRoPE.swiftnew file mode 100644index 00000000..1b14afd8--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Prefill/Primitives/PrefillRoPE.swift@@ -0,0 +1,89 @@+import Foundation+import Metal++final class PrefillRoPE {+ private let psoDefaultNeox: MTLComputePipelineState+ private let psoProportionalNeox: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.psoDefaultNeox = try context.pipeline("prefill_rope_default_neox_block")+ self.psoProportionalNeox = try context.pipeline("prefill_rope_proportional_neox_block")+ }++ func encodeDefaultNeox(commandBuffer: MTLCommandBuffer,+ data: MTLBuffer,+ dataOffset: Int = 0,+ startPosition: UInt32,+ queryCount: UInt32,+ headDim: UInt32,+ numHeads: UInt32,+ tokenStrideElements: UInt32,+ theta: Float = 10_000.0) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(headDim % 2 == 0, "headDim must be even")+ precondition(tokenStrideElements >= numHeads * headDim,+ "token stride is too small")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(psoDefaultNeox)+ enc.setBuffer(data, offset: dataOffset, index: 0)+ var start = startPosition+ var hd = headDim+ var heads = numHeads+ var stride = tokenStrideElements+ var thetaVar = theta+ enc.setBytes(&start, length: MemoryLayout<UInt32>.size, index: 1)+ enc.setBytes(&hd, length: MemoryLayout<UInt32>.size, index: 2)+ enc.setBytes(&heads, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&stride, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&thetaVar, length: MemoryLayout<Float>.size, index: 5)++ let pairs = Int(headDim) / 2+ enc.dispatchThreads(+ MTLSize(width: pairs, height: Int(numHeads), depth: Int(queryCount)),+ threadsPerThreadgroup: MTLSize(width: min(pairs, psoDefaultNeox.maxTotalThreadsPerThreadgroup),+ height: 1,+ depth: 1))+ enc.endEncoding()+ }++ func encodeProportionalNeox(commandBuffer: MTLCommandBuffer,+ data: MTLBuffer,+ dataOffset: Int = 0,+ startPosition: UInt32,+ queryCount: UInt32,+ headDim: UInt32,+ numHeads: UInt32,+ rotatedPairs: UInt32,+ tokenStrideElements: UInt32,+ theta: Float = 1_000_000.0) {+ precondition(queryCount > 0, "queryCount must be positive")+ precondition(headDim % 2 == 0, "headDim must be even")+ precondition(rotatedPairs * 2 <= headDim,+ "rotatedPairs * 2 must not exceed headDim")+ precondition(tokenStrideElements >= numHeads * headDim,+ "token stride is too small")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(psoProportionalNeox)+ enc.setBuffer(data, offset: dataOffset, index: 0)+ var start = startPosition+ var hd = headDim+ var heads = numHeads+ var stride = tokenStrideElements+ var thetaVar = theta+ var rp = rotatedPairs+ enc.setBytes(&start, length: MemoryLayout<UInt32>.size, index: 1)+ enc.setBytes(&hd, length: MemoryLayout<UInt32>.size, index: 2)+ enc.setBytes(&heads, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&stride, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&thetaVar, length: MemoryLayout<Float>.size, index: 5)+ enc.setBytes(&rp, length: MemoryLayout<UInt32>.size, index: 6)++ enc.dispatchThreads(+ MTLSize(width: Int(rotatedPairs), height: Int(numHeads), depth: Int(queryCount)),+ threadsPerThreadgroup: MTLSize(width: min(Int(rotatedPairs),+ psoProportionalNeox.maxTotalThreadsPerThreadgroup),+ height: 1,+ depth: 1))+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Primitives/RMSNorm.swift b/Sources/TurboFieldfare/Kernels/Primitives/RMSNorm.swiftnew file mode 100644index 00000000..59a0d795--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Primitives/RMSNorm.swift@@ -0,0 +1,189 @@+import Foundation+import Metal++/// Swift wrapper for the RMSNorm kernel family.+///+/// inv = 1 / sqrt(mean(x[i]^2) + eps)+/// y[i] = x[i] * inv * weight[i] // BF16 weight+/// y[i] = x[i] * inv // .noScale+///+/// One row per dispatch — callers needing per-head dispatch (q/k_norm) loop+/// across heads and offset both `x` and `out`. Single-row is the shape we hit+/// at decode: a token at a time, 61 norm dispatches per token before fusion.+final class RMSNorm {++ private let psoBF16: MTLComputePipelineState+ private let psoNoScale: MTLComputePipelineState+ private let psoBF16PerHead: MTLComputePipelineState+ private let psoNoScalePerHead: MTLComputePipelineState+ private let psoBF16D2816: MTLComputePipelineState+ private let psoNoScaleD2816: MTLComputePipelineState+ private let psoBF16PerHead256: MTLComputePipelineState+ private let psoBF16PerHead512: MTLComputePipelineState+ private let psoNoScalePerHead256: MTLComputePipelineState+ private let psoNoScalePerHead512: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.psoBF16 = try context.pipeline("rmsnorm_bf16w")+ self.psoNoScale = try context.pipeline("rmsnorm_no_scale")+ self.psoBF16PerHead = try context.pipeline("rmsnorm_bf16w_perhead")+ self.psoNoScalePerHead = try context.pipeline("rmsnorm_no_scale_perhead")+ self.psoBF16D2816 = try Self.specializedPipeline(context,+ "rmsnorm_bf16w",+ d: 2816)+ self.psoNoScaleD2816 = try Self.specializedPipeline(context,+ "rmsnorm_no_scale",+ d: 2816)+ self.psoBF16PerHead256 = try Self.specializedPipeline(context,+ "rmsnorm_bf16w_perhead",+ d: 256)+ self.psoBF16PerHead512 = try Self.specializedPipeline(context,+ "rmsnorm_bf16w_perhead",+ d: 512)+ self.psoNoScalePerHead256 = try Self.specializedPipeline(context,+ "rmsnorm_no_scale_perhead",+ d: 256)+ self.psoNoScalePerHead512 = try Self.specializedPipeline(context,+ "rmsnorm_no_scale_perhead",+ d: 512)+ }++ /// Encode the BF16-weight variant (Gemma 4 norms).+ func encodeBF16W(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ weight: MTLBuffer, weightOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ d: UInt32,+ eps: Float) {+ encodeWeighted(commandBuffer: commandBuffer,+ pso: d == 2816 ? psoBF16D2816 : psoBF16,+ x: x, xOffset: xOffset,+ weight: weight, weightOffset: weightOffset,+ out: out, outOffset: outOffset,+ d: d, eps: eps)+ }++ /// Encode the no-scale variant (v_norm, router internal norm).+ func encodeNoScale(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ d: UInt32,+ eps: Float) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ let pso = d == 2816 ? psoNoScaleD2816 : psoNoScale+ enc.setComputePipelineState(pso)+ enc.setBuffer(x, offset: xOffset, index: 0)+ enc.setBuffer(out, offset: outOffset, index: 1)+ var dVar = d+ var epsVar = eps+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 2)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 3)+ dispatchOneRow(enc: enc, pso: pso)+ enc.endEncoding()+ }++ /// BF16-weight RMSNorm applied to `numHeads` contiguous heads of width+ /// `headDim` in one dispatch. `weight` is the shared+ /// [headDim] per-head gain. In-place safe (each head's threadgroup touches+ /// only its own region).+ func encodeBF16WPerHead(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ weight: MTLBuffer, weightOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ headDim: UInt32, numHeads: Int,+ eps: Float) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ let pso = perHeadPipeline(headDim: headDim,+ base: psoBF16PerHead,+ p256: psoBF16PerHead256,+ p512: psoBF16PerHead512)+ enc.setComputePipelineState(pso)+ enc.setBuffer(x, offset: xOffset, index: 0)+ enc.setBuffer(weight, offset: weightOffset, index: 1)+ enc.setBuffer(out, offset: outOffset, index: 2)+ var hd = headDim+ var epsVar = eps+ enc.setBytes(&hd, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 4)+ let w = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ enc.dispatchThreadgroups(MTLSize(width: numHeads, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: w, height: 1, depth: 1))+ enc.endEncoding()+ }++ /// No-scale RMSNorm over `numHeads` contiguous heads (v_norm), one dispatch.+ func encodeNoScalePerHead(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ headDim: UInt32, numHeads: Int,+ eps: Float) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ let pso = perHeadPipeline(headDim: headDim,+ base: psoNoScalePerHead,+ p256: psoNoScalePerHead256,+ p512: psoNoScalePerHead512)+ enc.setComputePipelineState(pso)+ enc.setBuffer(x, offset: xOffset, index: 0)+ enc.setBuffer(out, offset: outOffset, index: 1)+ var hd = headDim+ var epsVar = eps+ enc.setBytes(&hd, length: MemoryLayout<UInt32>.size, index: 2)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 3)+ let w = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ enc.dispatchThreadgroups(MTLSize(width: numHeads, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: w, height: 1, depth: 1))+ enc.endEncoding()+ }++ private func encodeWeighted(commandBuffer: MTLCommandBuffer,+ pso: MTLComputePipelineState,+ x: MTLBuffer, xOffset: Int,+ weight: MTLBuffer, weightOffset: Int,+ out: MTLBuffer, outOffset: Int,+ d: UInt32,+ eps: Float) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(x, offset: xOffset, index: 0)+ enc.setBuffer(weight, offset: weightOffset, index: 1)+ enc.setBuffer(out, offset: outOffset, index: 2)+ var dVar = d+ var epsVar = eps+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&epsVar, length: MemoryLayout<Float>.size, index: 4)+ dispatchOneRow(enc: enc, pso: pso)+ enc.endEncoding()+ }++ private func dispatchOneRow(enc: MTLComputeCommandEncoder,+ pso: MTLComputePipelineState) {+ // One threadgroup, 256 threads. 256 is a multiple of the 32-lane SIMD+ // width on Apple silicon — no trailing partial SIMD-group to special-case.+ let threadsPerGroup = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ let gridSize = MTLSize(width: threadsPerGroup, height: 1, depth: 1)+ let tgSize = MTLSize(width: threadsPerGroup, height: 1, depth: 1)+ enc.dispatchThreads(gridSize, threadsPerThreadgroup: tgSize)+ }++ private static func specializedPipeline(_ context: MetalContext,+ _ name: String,+ d: UInt32) throws -> MTLComputePipelineState {+ try context.pipeline(+ name,+ constants: [+ MetalFunctionConstant(index: 30, value: .uint32(d)),+ MetalFunctionConstant(index: 31, value: .bool(true)),+ ])+ }++ private func perHeadPipeline(headDim: UInt32,+ base: MTLComputePipelineState,+ p256: MTLComputePipelineState,+ p512: MTLComputePipelineState) -> MTLComputePipelineState {+ switch headDim {+ case 256: return p256+ case 512: return p512+ default: return base+ }+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Primitives/RoPE.swift b/Sources/TurboFieldfare/Kernels/Primitives/RoPE.swiftnew file mode 100644index 00000000..d615f1ae--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Primitives/RoPE.swift@@ -0,0 +1,138 @@+import Metal++/// NeoX RoPE variants used by Gemma 4 attention.+final class RoPE {+ private let defaultNeox: MTLComputePipelineState+ private let proportionalNeox: MTLComputePipelineState+ private let defaultNeoxSWAQ: MTLComputePipelineState+ private let defaultNeoxSWAK: MTLComputePipelineState+ private let proportionalNeoxFullQ: MTLComputePipelineState+ private let proportionalNeoxFullK: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.defaultNeox = try context.pipeline("rope_default_neox")+ self.proportionalNeox = try context.pipeline("rope_proportional_neox")+ self.defaultNeoxSWAQ = try Self.specializedPipeline(+ context, "rope_default_neox", headDim: 256, numHeads: 16)+ self.defaultNeoxSWAK = try Self.specializedPipeline(+ context, "rope_default_neox", headDim: 256, numHeads: 8)+ self.proportionalNeoxFullQ = try Self.specializedPipeline(+ context, "rope_proportional_neox",+ headDim: 512, numHeads: 16, rotatedPairs: 64)+ self.proportionalNeoxFullK = try Self.specializedPipeline(+ context, "rope_proportional_neox",+ headDim: 512, numHeads: 2, rotatedPairs: 64)+ }++ func encodeDefaultNeox(commandBuffer: MTLCommandBuffer,+ data: MTLBuffer,+ dataOffset: Int = 0,+ position: UInt32,+ headDim: UInt32,+ numHeads: UInt32,+ numTokens: UInt32 = 1,+ theta: Float = 10_000.0) {+ precondition(headDim.isMultiple(of: 2), "head_dim must be even")+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }+ let pipeline = defaultPipeline(headDim: headDim, numHeads: numHeads)+ encoder.setComputePipelineState(pipeline)+ encoder.setBuffer(data, offset: dataOffset, index: 0)+ var positionValue = position+ var headDimValue = headDim+ var numHeadsValue = numHeads+ var thetaValue = theta+ encoder.setBytes(&positionValue, length: MemoryLayout<UInt32>.size, index: 1)+ encoder.setBytes(&headDimValue, length: MemoryLayout<UInt32>.size, index: 2)+ encoder.setBytes(&numHeadsValue, length: MemoryLayout<UInt32>.size, index: 3)+ encoder.setBytes(&thetaValue, length: MemoryLayout<Float>.size, index: 4)+ dispatch(encoder: encoder,+ pipeline: pipeline,+ pairs: Int(headDim) / 2,+ heads: Int(numHeads),+ tokens: Int(numTokens))+ encoder.endEncoding()+ }++ func encodeProportionalNeox(commandBuffer: MTLCommandBuffer,+ data: MTLBuffer,+ dataOffset: Int = 0,+ position: UInt32,+ headDim: UInt32,+ numHeads: UInt32,+ rotatedPairs: UInt32,+ numTokens: UInt32 = 1,+ theta: Float = 1_000_000.0) {+ precondition(headDim.isMultiple(of: 2), "head_dim must be even")+ precondition(rotatedPairs * 2 <= headDim,+ "rotatedPairs * 2 must not exceed head_dim")+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }+ let pipeline = proportionalPipeline(+ headDim: headDim,+ numHeads: numHeads,+ rotatedPairs: rotatedPairs)+ encoder.setComputePipelineState(pipeline)+ encoder.setBuffer(data, offset: dataOffset, index: 0)+ var positionValue = position+ var headDimValue = headDim+ var numHeadsValue = numHeads+ var thetaValue = theta+ var rotatedPairsValue = rotatedPairs+ encoder.setBytes(&positionValue, length: MemoryLayout<UInt32>.size, index: 1)+ encoder.setBytes(&headDimValue, length: MemoryLayout<UInt32>.size, index: 2)+ encoder.setBytes(&numHeadsValue, length: MemoryLayout<UInt32>.size, index: 3)+ encoder.setBytes(&thetaValue, length: MemoryLayout<Float>.size, index: 4)+ encoder.setBytes(&rotatedPairsValue, length: MemoryLayout<UInt32>.size, index: 5)+ dispatch(encoder: encoder,+ pipeline: pipeline,+ pairs: Int(headDim) / 2,+ heads: Int(numHeads),+ tokens: Int(numTokens))+ encoder.endEncoding()+ }++ private static func specializedPipeline(_ context: MetalContext,+ _ name: String,+ headDim: UInt32,+ numHeads: UInt32,+ rotatedPairs: UInt32 = 0) throws+ -> MTLComputePipelineState {+ try context.pipeline(+ name,+ constants: [+ MetalFunctionConstant(index: 50, value: .uint32(headDim)),+ MetalFunctionConstant(index: 51, value: .uint32(numHeads)),+ MetalFunctionConstant(index: 52, value: .uint32(rotatedPairs)),+ MetalFunctionConstant(index: 53, value: .bool(true)),+ ])+ }++ private func defaultPipeline(headDim: UInt32,+ numHeads: UInt32) -> MTLComputePipelineState {+ if headDim == 256 && numHeads == 16 { return defaultNeoxSWAQ }+ if headDim == 256 && numHeads == 8 { return defaultNeoxSWAK }+ return defaultNeox+ }++ private func proportionalPipeline(headDim: UInt32,+ numHeads: UInt32,+ rotatedPairs: UInt32) -> MTLComputePipelineState {+ if headDim == 512 && rotatedPairs == 64 && numHeads == 16 {+ return proportionalNeoxFullQ+ }+ if headDim == 512 && rotatedPairs == 64 && numHeads == 2 {+ return proportionalNeoxFullK+ }+ return proportionalNeox+ }++ private func dispatch(encoder: MTLComputeCommandEncoder,+ pipeline: MTLComputePipelineState,+ pairs: Int,+ heads: Int,+ tokens: Int) {+ let width = min(pairs, Int(pipeline.maxTotalThreadsPerThreadgroup))+ encoder.dispatchThreads(+ MTLSize(width: pairs, height: heads, depth: tokens),+ threadsPerThreadgroup: MTLSize(width: width, height: 1, depth: 1))+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Quant/DequantInt4GEMV.swift b/Sources/TurboFieldfare/Kernels/Quant/DequantInt4GEMV.swiftnew file mode 100644index 00000000..42de5e48--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Quant/DequantInt4GEMV.swift@@ -0,0 +1,88 @@+import Metal++/// MLX-affine INT4 matrix-vector multiplication.+/// Eight SIMD groups process eight output rows per threadgroup.+final class DequantInt4GEMV {+ private struct Shape: Hashable {+ var m: UInt32+ var n: UInt32+ }++ private static let rowsPerThreadgroup = 8+ private static let realDecodeShapes: [Shape] = [+ Shape(m: 4096, n: 2816),+ Shape(m: 2048, n: 2816),+ Shape(m: 2816, n: 4096),+ Shape(m: 8192, n: 2816),+ Shape(m: 1024, n: 2816),+ Shape(m: 2816, n: 8192),+ ]++ private let pipeline: MTLComputePipelineState+ private let specializedPipelines: [Shape: MTLComputePipelineState]++ init(context: MetalContext) throws {+ self.pipeline = try context.pipeline(+ "dequant_int4_gemv_simd",+ constants: [],+ maxTotalThreadsPerThreadgroup: 512)++ var specializedPipelines: [Shape: MTLComputePipelineState] = [:]+ for shape in Self.realDecodeShapes {+ specializedPipelines[shape] = try context.pipeline(+ "dequant_int4_gemv_simd",+ constants: [+ MetalFunctionConstant(index: 20, value: .uint32(shape.m)),+ MetalFunctionConstant(index: 21, value: .uint32(shape.n)),+ MetalFunctionConstant(index: 22, value: .bool(true)),+ ],+ maxTotalThreadsPerThreadgroup: 512)+ }+ self.specializedPipelines = specializedPipelines+ }++ func encode(commandBuffer: MTLCommandBuffer,+ weights: MTLBuffer,+ weightsOffset: Int = 0,+ scales: MTLBuffer,+ scalesOffset: Int = 0,+ biases: MTLBuffer,+ biasesOffset: Int = 0,+ x: MTLBuffer,+ xOffset: Int = 0,+ y: MTLBuffer,+ yOffset: Int = 0,+ m: UInt32,+ n: UInt32) {+ precondition(n % UInt32(Quantization.groupSize) == 0,+ "N must be a multiple of \(Quantization.groupSize)")+ // The kernel reads packed weights through a `ushort*`; the repacker+ // guarantees two-byte sub-tensor alignment but not four-byte alignment.+ precondition(weightsOffset % 2 == 0,+ "dequant_int4_gemv_simd needs a 2-aligned weightsOffset, got \(weightsOffset)")+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }+ encoder.setComputePipelineState(+ specializedPipelines[Shape(m: m, n: n)] ?? pipeline)+ encoder.setBuffer(weights, offset: weightsOffset, index: 0)+ encoder.setBuffer(scales, offset: scalesOffset, index: 1)+ encoder.setBuffer(biases, offset: biasesOffset, index: 2)+ encoder.setBuffer(x, offset: xOffset, index: 3)+ encoder.setBuffer(y, offset: yOffset, index: 4)+ var mValue = m+ var nValue = n+ encoder.setBytes(&mValue, length: MemoryLayout<UInt32>.size, index: 5)+ encoder.setBytes(&nValue, length: MemoryLayout<UInt32>.size, index: 6)++ let threadgroupSize = MTLSize(+ width: 32 * Self.rowsPerThreadgroup,+ height: 1,+ depth: 1)+ let threadgroupCount = MTLSize(+ width: (Int(m) + Self.rowsPerThreadgroup - 1) / Self.rowsPerThreadgroup,+ height: 1,+ depth: 1)+ encoder.dispatchThreadgroups(threadgroupCount,+ threadsPerThreadgroup: threadgroupSize)+ encoder.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Quant/DequantInt8GEMV.swift b/Sources/TurboFieldfare/Kernels/Quant/DequantInt8GEMV.swiftnew file mode 100644index 00000000..b118b06e--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Quant/DequantInt8GEMV.swift@@ -0,0 +1,82 @@+import Foundation+import Metal++/// Swift wrapper for `dequant_int8_gemv_simd`.+///+/// y = W * x+///+/// where W (M rows, N cols) is MLX-affine 8-bit (group=64) with BF16 scale ++/// BF16 bias per group, x is FP16 [N], y is FP16 [M].+///+/// Same kernel, two call sites:+/// * router — M=128, N=2816 (one per layer)+/// * lm_head — M=262144, N=2816 (final classifier, tied with embed table)+///+/// One SIMD group (32 threads) runs per output row.+final class DequantInt8GEMV {+ private struct Shape: Hashable {+ var m: UInt32+ var n: UInt32+ }++ private let pso: MTLComputePipelineState+ private let specializedPSOs: [Shape: MTLComputePipelineState]+ private static let realDecodeShapes: [Shape] = [+ Shape(m: 128, n: 2816), // router.proj+ Shape(m: 2112, n: 2816), // shared expert gate/up+ Shape(m: 2816, n: 2112), // shared expert down+ ]++ init(context: MetalContext) throws {+ let kernelName = "dequant_int8_gemv_simd"+ self.pso = try context.pipeline(kernelName)++ var variants: [Shape: MTLComputePipelineState] = [:]+ for shape in Self.realDecodeShapes {+ variants[shape] = try context.pipeline(+ kernelName,+ constants: [+ MetalFunctionConstant(index: 70, value: .uint32(shape.m)),+ MetalFunctionConstant(index: 71, value: .uint32(shape.n)),+ MetalFunctionConstant(index: 72, value: .bool(true)),+ ])+ }+ self.specializedPSOs = variants+ }++ /// Encodes the GEMV onto `commandBuffer`. Offsets allow passing the same+ /// mmap'd `MTLBuffer` for weights / scales / biases when they share a+ /// page-aligned blob.+ func encode(commandBuffer: MTLCommandBuffer,+ weights: MTLBuffer, weightsOffset: Int = 0,+ scales: MTLBuffer, scalesOffset: Int = 0,+ biases: MTLBuffer, biasesOffset: Int = 0,+ x: MTLBuffer,+ xOffset: Int = 0,+ y: MTLBuffer,+ yOffset: Int = 0,+ m: UInt32,+ n: UInt32) {+ precondition(n % UInt32(Quantization.groupSize) == 0,+ "N must be a multiple of \(Quantization.groupSize)")+ precondition(xOffset >= 0 && yOffset >= 0, "buffer offsets must be non-negative")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(specializedPSOs[Shape(m: m, n: n)] ?? pso)+ enc.setBuffer(weights, offset: weightsOffset, index: 0)+ enc.setBuffer(scales, offset: scalesOffset, index: 1)+ enc.setBuffer(biases, offset: biasesOffset, index: 2)+ enc.setBuffer(x, offset: xOffset, index: 3)+ enc.setBuffer(y, offset: yOffset, index: 4)+ var mVar = m+ var nVar = n+ enc.setBytes(&mVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&nVar, length: MemoryLayout<UInt32>.size, index: 6)++ let rowsPerTG = 8+ let tgSize = MTLSize(width: 32 * rowsPerTG, height: 1, depth: 1)+ let tgCount = MTLSize(width: (Int(m) + rowsPerTG - 1) / rowsPerTG,+ height: 1, depth: 1)+ enc.dispatchThreadgroups(tgCount, threadsPerThreadgroup: tgSize)+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Quant/EmbedLookupInt4.swift b/Sources/TurboFieldfare/Kernels/Quant/EmbedLookupInt4.swiftnew file mode 100644index 00000000..1b30b7de--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Quant/EmbedLookupInt4.swift@@ -0,0 +1,51 @@+import Foundation+import Metal++/// 4-bit affine embedding lookup with fused output scale.+///+/// Gemma 4 ships a tied 4-bit MLX-affine embedding table (`embed_tokens.weight`+/// is `U32`/packed 4-bit with `weightBits=4` in the manifest). The same table+/// also drives the lm_head GEMV via `DequantInt4GEMV` over the transposed+/// access pattern. The `outScale` parameter fuses the `sqrt(hidden_size)`+/// post-embedding scale so the per-token dequant + scale+/// is one pass.+final class EmbedLookupInt4 {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("embed_lookup_int4")+ }++ /// Encodes the lookup. `table`, `scales`, `biases` typically live inside+ /// one resident blob — pass that buffer with the per-region offsets.+ /// Pass `outScale = 1.0` to write the raw dequantized row.+ func encode(commandBuffer: MTLCommandBuffer,+ table: MTLBuffer, tableOffset: Int = 0,+ scales: MTLBuffer, scalesOffset: Int = 0,+ biases: MTLBuffer, biasesOffset: Int = 0,+ out: MTLBuffer, outOffset: Int = 0,+ tokenId: UInt32,+ d: UInt32,+ outScale: Float) {+ precondition(d % UInt32(Quantization.groupSize) == 0,+ "D must be a multiple of \(Quantization.groupSize)")+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(table, offset: tableOffset, index: 0)+ enc.setBuffer(scales, offset: scalesOffset, index: 1)+ enc.setBuffer(biases, offset: biasesOffset, index: 2)+ enc.setBuffer(out, offset: outOffset, index: 3)+ var tokenVar = tokenId+ var dVar = d+ var sVar = outScale+ enc.setBytes(&tokenVar, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&dVar, length: MemoryLayout<UInt32>.size, index: 5)+ enc.setBytes(&sVar, length: MemoryLayout<Float>.size, index: 6)++ let threadsPerGroup = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ let gridSize = MTLSize(width: Int(d), height: 1, depth: 1)+ let tgSize = MTLSize(width: threadsPerGroup, height: 1, depth: 1)+ enc.dispatchThreads(gridSize, threadsPerThreadgroup: tgSize)+ enc.endEncoding()+ }+}diff --git a/Sources/TurboFieldfare/Kernels/Sampling/LogitOutput.swift b/Sources/TurboFieldfare/Kernels/Sampling/LogitOutput.swiftnew file mode 100644index 00000000..1242d66f--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/Sampling/LogitOutput.swift@@ -0,0 +1,213 @@+import Foundation+import Metal++/// Swift wrapper for `logit_softcap_softmax`.+///+/// z'[i] = softcap * tanh(z[i] / softcap)+/// p[i] = exp(z'[i] - max_j z'[j]) / sum_j exp(z'[j] - max_j z'[j])+///+/// One threadgroup, single online-softmax pass (Milakov & Gimelshein). FP16+/// storage in and out, FP32 accumulation. The softcap value lives in the+/// kernel signature instead of being hardcoded so that downstream callers+/// (and tests) can disable it by passing a very large number.+final class LogitSoftcapSoftmax {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("logit_softcap_softmax")+ }++ /// Encodes the kernel onto `commandBuffer`. `logits` and `probs` are FP16+ /// buffers of length `v`. Gemma 4 uses `softcap=30.0`.+ func encode(commandBuffer: MTLCommandBuffer,+ logits: MTLBuffer,+ probs: MTLBuffer,+ v: UInt32,+ softcap: Float = 30.0) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(logits, offset: 0, index: 0)+ enc.setBuffer(probs, offset: 0, index: 1)+ var vVar = v+ var softcapVar = softcap+ enc.setBytes(&vVar, length: MemoryLayout<UInt32>.size, index: 2)+ enc.setBytes(&softcapVar, length: MemoryLayout<Float>.size, index: 3)++ let threadsPerGroup = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ let gridSize = MTLSize(width: threadsPerGroup, height: 1, depth: 1)+ let tgSize = MTLSize(width: threadsPerGroup, height: 1, depth: 1)+ enc.dispatchThreads(gridSize, threadsPerThreadgroup: tgSize)+ enc.endEncoding()+ }+}++/// Swift wrapper for `sample`.+///+/// Reads softmaxed probabilities (output of `LogitSoftcapSoftmax`) and writes+/// one UInt32 token id. With `temperature == 0` performs greedy argmax and+/// ignores top-k / top-p / seed. With `temperature > 0` applies top-p against+/// the full distribution, caps the surviving set with top-k, then applies+/// temperature sharpening (`p^(1/T)`) and samples via a seeded PRNG. The+/// plain-temperature fast path uses the same+/// `(seed, position, row)` Gumbel stream as the fused lm_head sampler.+final class Sample {+ private let pso: MTLComputePipelineState++ init(context: MetalContext) throws {+ self.pso = try context.pipeline("sample")+ }++ /// Encodes the sampler. `probs` is an FP16 buffer of length `v`. `outToken`+ /// must point at storage for one UInt32. The seed is the full 64-bit PRNG+ /// state — tests pass identical seeds to assert determinism.+ func encode(commandBuffer: MTLCommandBuffer,+ probs: MTLBuffer,+ outToken: MTLBuffer,+ v: UInt32,+ temperature: Float = 1.0,+ topK: UInt32 = 0,+ topP: Float = 1.0,+ seed: UInt64,+ position: UInt32 = 0) {+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }+ enc.setComputePipelineState(pso)+ enc.setBuffer(probs, offset: 0, index: 0)+ enc.setBuffer(outToken, offset: 0, index: 1)+ var vVar = v+ var tVar = temperature+ var kVar = topK+ var pVar = topP+ var sVar = seed+ var posVar = position+ enc.setBytes(&vVar, length: MemoryLayout<UInt32>.size, index: 2)+ enc.setBytes(&tVar, length: MemoryLayout<Float>.size, index: 3)+ enc.setBytes(&kVar, length: MemoryLayout<UInt32>.size, index: 4)+ enc.setBytes(&pVar, length: MemoryLayout<Float>.size, index: 5)+ enc.setBytes(&sVar, length: MemoryLayout<UInt64>.size, index: 6)+ enc.setBytes(&posVar, length: MemoryLayout<UInt32>.size, index: 7)++ let threadsPerGroup = min(Int(pso.maxTotalThreadsPerThreadgroup), 256)+ let gridSize = MTLSize(width: threadsPerGroup, height: 1, depth: 1)+ let tgSize = MTLSize(width: threadsPerGroup, height: 1, depth: 1)+ enc.dispatchThreads(gridSize, threadsPerThreadgroup: tgSize)+ enc.endEncoding()+ }+}+enum SampleTopK64Error: Error {+ case unsupportedVocabulary(Int)+ case scratchAllocationFailed+}++/// Three-stage Top-64 sampler for the documented Gemma 4 policy and measured+/// temperature variants. Intermediate pairs remain in private GPU memory.+final class SampleTopK64 {+ private static let tileSize = 1024+ private static let keptPerTile = 64++ private let ctx: MetalContext+ private let stage1PSO: MTLComputePipelineState+ private let reducePSO: MTLComputePipelineState+ private let finalPSO: MTLComputePipelineState+ private let stage1Values: MTLBuffer+ private let stage1Indices: MTLBuffer+ private let stage2Values: MTLBuffer+ private let stage2Indices: MTLBuffer+ private let stage1Groups: Int+ private let stage2Groups: Int+ private let stage1Count: Int+ private let stage2Count: Int++ public let vocab: Int+ public let scratchBytes: Int++ public init(context: MetalContext, vocab: Int) throws {+ guard vocab > 0, vocab <= 262_144 else {+ throw SampleTopK64Error.unsupportedVocabulary(vocab)+ }+ self.ctx = context+ self.vocab = vocab+ self.stage1PSO = try context.pipeline("sample_topk64_stage1")+ self.reducePSO = try context.pipeline("sample_topk64_reduce")+ self.finalPSO = try context.pipeline("sample_topk64_final")++ self.stage1Groups = (vocab + Self.tileSize - 1) / Self.tileSize+ self.stage1Count = stage1Groups * Self.keptPerTile+ self.stage2Groups = (stage1Count + Self.tileSize - 1) / Self.tileSize+ self.stage2Count = stage2Groups * Self.keptPerTile++ let stage1ValueBytes = stage1Count * MemoryLayout<Float>.stride+ let stage1IndexBytes = stage1Count * MemoryLayout<UInt32>.stride+ let stage2ValueBytes = stage2Count * MemoryLayout<Float>.stride+ let stage2IndexBytes = stage2Count * MemoryLayout<UInt32>.stride+ self.scratchBytes = stage1ValueBytes + stage1IndexBytes+ + stage2ValueBytes + stage2IndexBytes++ guard let stage1Values = context.device.makeBuffer(+ length: stage1ValueBytes, options: .storageModePrivate),+ let stage1Indices = context.device.makeBuffer(+ length: stage1IndexBytes, options: .storageModePrivate),+ let stage2Values = context.device.makeBuffer(+ length: stage2ValueBytes, options: .storageModePrivate),+ let stage2Indices = context.device.makeBuffer(+ length: stage2IndexBytes, options: .storageModePrivate)+ else {+ throw SampleTopK64Error.scratchAllocationFailed+ }+ self.stage1Values = stage1Values+ self.stage1Indices = stage1Indices+ self.stage2Values = stage2Values+ self.stage2Indices = stage2Indices+ }++ public func encode(commandBuffer: MTLCommandBuffer,+ probs: MTLBuffer,+ outToken: MTLBuffer,+ temperature: Float,+ topP: Float,+ seed: UInt64) {+ let threads = MTLSize(width: 256, height: 1, depth: 1)++ if let enc = commandBuffer.makeComputeCommandEncoder() {+ enc.setComputePipelineState(stage1PSO)+ enc.setBuffer(probs, offset: 0, index: 0)+ enc.setBuffer(stage1Values, offset: 0, index: 1)+ enc.setBuffer(stage1Indices, offset: 0, index: 2)+ var v = UInt32(vocab)+ enc.setBytes(&v, length: MemoryLayout<UInt32>.size, index: 3)+ enc.dispatchThreadgroups(MTLSize(width: stage1Groups, height: 1, depth: 1),+ threadsPerThreadgroup: threads)+ enc.endEncoding()+ }++ if let enc = commandBuffer.makeComputeCommandEncoder() {+ enc.setComputePipelineState(reducePSO)+ enc.setBuffer(stage1Values, offset: 0, index: 0)+ enc.setBuffer(stage1Indices, offset: 0, index: 1)+ enc.setBuffer(stage2Values, offset: 0, index: 2)+ enc.setBuffer(stage2Indices, offset: 0, index: 3)+ var count = UInt32(stage1Count)+ enc.setBytes(&count, length: MemoryLayout<UInt32>.size, index: 4)+ enc.dispatchThreadgroups(MTLSize(width: stage2Groups, height: 1, depth: 1),+ threadsPerThreadgroup: threads)+ enc.endEncoding()+ }++ if let enc = commandBuffer.makeComputeCommandEncoder() {+ enc.setComputePipelineState(finalPSO)+ enc.setBuffer(stage2Values, offset: 0, index: 0)+ enc.setBuffer(stage2Indices, offset: 0, index: 1)+ enc.setBuffer(outToken, offset: 0, index: 2)+ var count = UInt32(stage2Count)+ var temp = temperature+ var p = topP+ var rngSeed = seed+ enc.setBytes(&count, length: MemoryLayout<UInt32>.size, index: 3)+ enc.setBytes(&temp, length: MemoryLayout<Float>.size, index: 4)+ enc.setBytes(&p, length: MemoryLayout<Float>.size, index: 5)+ enc.setBytes(&rngSeed, length: MemoryLayout<UInt64>.size, index: 6)+ enc.dispatchThreadgroups(MTLSize(width: 1, height: 1, depth: 1),+ threadsPerThreadgroup: threads)+ enc.endEncoding()+ }+ }+}diff --git a/Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swift b/Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swiftnew file mode 100644index 00000000..aa3fc9c5--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swift@@ -0,0 +1,79 @@+import Foundation+import Metal++final class MPPPrefillInt4QMM {+ enum Path: String, Sendable {+ case affineThreadgroupF16 = "affine-threadgroup-f16"+ case unavailable+ }++ static let tileM = 64+ static let tileN = 32+ static let tileK = Quantization.groupSize++ private var pipeline: MTLComputePipelineState?++ init(context: MetalContext) {+ do {+ let library = try Self.compileTensorOpsLibrary(device: context.device)+ guard let function = library.makeFunction(+ name: "mpp_prefill_affine_threadgroup_f16") else {+ throw MetalError.missingFunction("mpp_prefill_affine_threadgroup_f16")+ }+ self.pipeline = try context.device.makeComputePipelineState(function: function)+ } catch {+ self.pipeline = nil+ }+ }++ @discardableResult+ func encode(commandBuffer: MTLCommandBuffer,+ weights: MTLBuffer, weightsOffset: Int = 0,+ scales: MTLBuffer, scalesOffset: Int = 0,+ biases: MTLBuffer, biasesOffset: Int = 0,+ x: MTLBuffer, xOffset: Int = 0,+ y: MTLBuffer, yOffset: Int = 0,+ m: Int,+ n: Int,+ k: Int) -> Path {+ guard m > 0,+ n > 0,+ k > 0,+ k.isMultiple(of: Self.tileK),+ weightsOffset >= 0,+ scalesOffset.isMultiple(of: MemoryLayout<UInt16>.stride),+ biasesOffset.isMultiple(of: MemoryLayout<UInt16>.stride),+ xOffset.isMultiple(of: MemoryLayout<Float16>.stride),+ yOffset.isMultiple(of: MemoryLayout<Float16>.stride),+ let pipeline,+ let encoder = commandBuffer.makeComputeCommandEncoder() else {+ return .unavailable+ }++ encoder.setComputePipelineState(pipeline)+ encoder.setBuffer(weights, offset: weightsOffset, index: 0)+ encoder.setBuffer(scales, offset: scalesOffset, index: 1)+ encoder.setBuffer(biases, offset: biasesOffset, index: 2)+ encoder.setBuffer(x, offset: xOffset, index: 3)+ encoder.setBuffer(y, offset: yOffset, index: 4)+ var mValue = UInt32(m)+ var nValue = UInt32(n)+ var kValue = UInt32(k)+ encoder.setBytes(&mValue, length: MemoryLayout<UInt32>.size, index: 5)+ encoder.setBytes(&nValue, length: MemoryLayout<UInt32>.size, index: 6)+ encoder.setBytes(&kValue, length: MemoryLayout<UInt32>.size, index: 7)+ encoder.dispatchThreadgroups(+ MTLSize(width: (n + Self.tileN - 1) / Self.tileN,+ height: (m + Self.tileM - 1) / Self.tileM,+ depth: 1),+ threadsPerThreadgroup: MTLSize(width: pipeline.threadExecutionWidth * 4,+ height: 1,+ depth: 1))+ encoder.endEncoding()+ return .affineThreadgroupF16+ }++ private static func compileTensorOpsLibrary(device: MTLDevice) throws -> MTLLibrary {+ try MetalContext.moduleLibrary(device: device, module: "tensorops")+ }+}diff --git a/Sources/TurboFieldfare/Metal/Attention/attention.metal b/Sources/TurboFieldfare/Metal/Attention/attention.metalnew file mode 100644index 00000000..7222c3c0--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Attention/attention.metal@@ -0,0 +1,1013 @@+#include <metal_stdlib>+using namespace metal;++// ============================================================================+// attention — split-KV tiled softmax attention for single-token decode.+//+// Decode path only: M_q = 1 (one query token), arbitrary seq_len history.+// The MPP prefill path handles M_q > 1 separately.+//+// Layout (caller-side contract):+// Q : [num_q_heads, head_dim] FP16, contiguous.+// K : [seq_len, num_kv_heads, head_dim] FP16, contiguous.+// V : [seq_len, num_kv_heads, head_dim] FP16, same shape as K.+// Full attention reuses the raw K projection for V, but its separate+// normalization and RoPE paths make these buffers distinct here.+// out : [num_q_heads, head_dim] FP16.+//+// GQA: q_head -> kv_head = q_head / (num_q_heads / num_kv_heads).+// Multiple Q heads share one KV head; the dispatch indexes Q heads.+//+// Online softmax recurrence (FP32 accumulators) — Milakov & Gimelshein 2018,+// also FlashAttention:+// m_new = max(m, s)+// alpha = exp(m - m_new) // rescale factor for past state+// d = d * alpha + exp(s - m_new)+// o[i] = o[i] * alpha + exp(s - m_new) * V[p, i]+// m = m_new+// Final normalization: out[i] = o[i] / d.+//+// ============================================================================++constant constexpr uint kAttnThreads = 256;+// kAttnMaxSimdGroups must cover kAttnThreads / 32 = 8.+constant constexpr uint kAttnMaxSimdGroups = 8;+constant constexpr uint kAttnMaxQPerKV = 2;+constant constexpr uint kAttnMaxFullQPerKV = 8;+constant constexpr uint kAttnFullQPerThreadgroup = 2;+// Largest head_dim we run with (full-attention layers). SWA uses 256 — the+// kernel still allocates the 512-slot scratch but only touches the live half.+constant constexpr uint kAttnMaxHeadDim = 512;+constant uint FC_ATTN_HEAD_DIM [[function_constant(60)]];+constant uint FC_ATTN_NUM_Q_HEADS [[function_constant(61)]];+constant uint FC_ATTN_NUM_KV_HEADS [[function_constant(62)]];+constant bool FC_ATTN_USE_FC [[function_constant(63)]];+constant float FC_ATTN_SCALE [[function_constant(64)]];+constant uint FC_ATTN_NUM_CHUNKS [[function_constant(65)]];+constant uint FC_ATTN_RING_CAP [[function_constant(69)]];++static inline uint attn_fc_head_dim(constant uint& head_dim) {+ return (is_function_constant_defined(FC_ATTN_USE_FC) &&+ FC_ATTN_USE_FC &&+ is_function_constant_defined(FC_ATTN_HEAD_DIM))+ ? FC_ATTN_HEAD_DIM+ : head_dim;+}+static inline uint attn_fc_num_q_heads(constant uint& num_q_heads) {+ return (is_function_constant_defined(FC_ATTN_USE_FC) &&+ FC_ATTN_USE_FC &&+ is_function_constant_defined(FC_ATTN_NUM_Q_HEADS))+ ? FC_ATTN_NUM_Q_HEADS+ : num_q_heads;+}++static inline uint attn_fc_num_kv_heads(constant uint& num_kv_heads) {+ return (is_function_constant_defined(FC_ATTN_USE_FC) &&+ FC_ATTN_USE_FC &&+ is_function_constant_defined(FC_ATTN_NUM_KV_HEADS))+ ? FC_ATTN_NUM_KV_HEADS+ : num_kv_heads;+}++static inline float attn_fc_scale(float scale) {+ return is_function_constant_defined(FC_ATTN_SCALE) ? FC_ATTN_SCALE : scale;+}++static inline uint attn_fc_num_chunks(constant uint& num_chunks) {+ return is_function_constant_defined(FC_ATTN_NUM_CHUNKS) ? FC_ATTN_NUM_CHUNKS : num_chunks;+}++static inline uint attn_ring_slot(uint p) {+ return (is_function_constant_defined(FC_ATTN_RING_CAP) &&+ FC_ATTN_RING_CAP != 0u)+ ? (p % FC_ATTN_RING_CAP)+ : p;+}++static inline float attn_softmax_exp(float x) {+ return fast::exp(x);+}++// Block reduce: per-SIMD-group simd_sum, write partial to scratch, lane 0 of+// SIMD-group 0 finishes the merge with a second simd_sum and broadcasts.+// `scratch` must hold at least `simdgroups` floats; `bcast` is one float used+// to publish the final reduced value to all threads.+inline float block_reduce_sum(float v,+ uint simd_lane_id,+ uint simd_group_id,+ uint simdgroups,+ threadgroup float* scratch,+ threadgroup float* bcast) {+ float s = simd_sum(v);+ if (simd_lane_id == 0) { scratch[simd_group_id] = s; }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (simd_group_id == 0) {+ float t = (simd_lane_id < simdgroups) ? scratch[simd_lane_id] : 0.0f;+ t = simd_sum(t);+ if (simd_lane_id == 0) { *bcast = t; }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ return *bcast;+}++// ============================================================================+// TurboQuant packed-KV attention.+// ============================================================================++struct AttentionTurboQuantKVParams {+ uint head_dim;+ uint num_q_heads;+ uint num_kv_heads;+ uint seq_len;+ uint kv_start;+ float scale;+ uint layer;+ uint rotation_seed;+ uint key_bytes_per_head;+ uint key_packed_offset;+ uint key_scale_offset;+ uint value_bytes_per_head;+ uint value_packed_offset;+ uint value_scale_offset;+ uint q_pretransformed;+};++static inline uint attn_tq_key_bit_width(constant AttentionTurboQuantKVParams&) {+ return 4u;+}++static inline uint attn_tq_value_bit_width(constant AttentionTurboQuantKVParams&) {+ return 4u;+}++constant constexpr float kAttnTQCodebook4[16] = {+ -2.7326f, -2.0690f, -1.6181f, -1.2562f,+ -0.9424f, -0.6568f, -0.3881f, -0.1284f,+ 0.1284f, 0.3881f, 0.6568f, 0.9424f,+ 1.2562f, 1.6181f, 2.0690f, 2.7326f+};++static inline float attn_tq_centroid(uint idx) {+ return kAttnTQCodebook4[idx];+}++static inline ulong attn_tq_mix64(ulong z) {+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;+ return z ^ (z >> 31);+}++static inline bool attn_tq_rotation_is_negative(uint layer, uint head, uint dim, uint seed) {+ ulong z = ulong(seed);+ z ^= ulong(layer) * 0x9E3779B97F4A7C15ul;+ z ^= ulong(head) * 0xBF58476D1CE4E5B9ul;+ z ^= ulong(dim) * 0x94D049BB133111EBul;+ return (attn_tq_mix64(z) >> 63) != 0ul;+}++static inline float attn_tq_apply_rotation(float v,+ uint layer,+ uint head,+ uint dim,+ uint seed) {+ return attn_tq_rotation_is_negative(layer, head, dim, seed) ? -v : v;+}++static inline void attn_tq_wht_inplace(threadgroup float* data,+ uint D,+ uint lid,+ uint lsize) {+ for (uint stride = 1u; stride < D; stride <<= 1u) {+ for (uint j = lid; j < D / 2u; j += lsize) {+ const uint block = j / stride;+ const uint lane = j - block * stride;+ const uint a_idx = block * stride * 2u + lane;+ const uint b_idx = a_idx + stride;+ const float a = data[a_idx];+ const float b = data[b_idx];+ data[a_idx] = (a + b) * 0.7071067811865475f;+ data[b_idx] = (a - b) * 0.7071067811865475f;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }+}++static inline void attn_tq_wht_inplace_d256(threadgroup float* data,+ uint lid,+ uint simd_lane) {+ float v = data[lid];+ for (uint stride = 1u; stride < 32u; stride <<= 1u) {+ float other = simd_shuffle_xor(v, stride);+ v = ((simd_lane & stride) == 0u)+ ? (v + other) * 0.7071067811865475f+ : (other - v) * 0.7071067811865475f;+ }++ data[lid] = v;+ for (uint stride = 32u; stride < 256u; stride <<= 1u) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if ((lid & stride) == 0u) {+ uint j = lid | stride;+ float a = data[lid];+ float b = data[j];+ data[lid] = (a + b) * 0.7071067811865475f;+ data[j] = (a - b) * 0.7071067811865475f;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+}++static inline void attn_tq_wht_inplace_d512(threadgroup float* data,+ uint lid,+ uint simd_lane) {+ float v0 = data[lid];+ float v1 = data[lid + 256u];+ for (uint stride = 1u; stride < 32u; stride <<= 1u) {+ float other0 = simd_shuffle_xor(v0, stride);+ float other1 = simd_shuffle_xor(v1, stride);+ const bool lo = (simd_lane & stride) == 0u;+ v0 = lo+ ? (v0 + other0) * 0.7071067811865475f+ : (other0 - v0) * 0.7071067811865475f;+ v1 = lo+ ? (v1 + other1) * 0.7071067811865475f+ : (other1 - v1) * 0.7071067811865475f;+ }++ data[lid] = v0;+ data[lid + 256u] = v1;+ for (uint stride = 32u; stride < 256u; stride <<= 1u) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if ((lid & stride) == 0u) {+ uint j = lid | stride;+ float a0 = data[lid];+ float b0 = data[j];+ data[lid] = (a0 + b0) * 0.7071067811865475f;+ data[j] = (a0 - b0) * 0.7071067811865475f;++ float a1 = data[lid + 256u];+ float b1 = data[j + 256u];+ data[lid + 256u] = (a1 + b1) * 0.7071067811865475f;+ data[j + 256u] = (a1 - b1) * 0.7071067811865475f;+ }+ }++ threadgroup_barrier(mem_flags::mem_threadgroup);+ float a = data[lid];+ float b = data[lid + 256u];+ data[lid] = (a + b) * 0.7071067811865475f;+ data[lid + 256u] = (a - b) * 0.7071067811865475f;+ threadgroup_barrier(mem_flags::mem_threadgroup);+}++static inline void attn_tq_wht_inplace_fast(threadgroup float* data,+ uint D,+ uint lid,+ uint lsize,+ uint simd_lane) {+ if (D == 256u && lsize >= 256u) {+ attn_tq_wht_inplace_d256(data, lid, simd_lane);+ } else if (D == 512u && lsize >= 256u) {+ attn_tq_wht_inplace_d512(data, lid, simd_lane);+ } else {+ attn_tq_wht_inplace(data, D, lid, lsize);+ }+}++static inline float attn_tq_read_packed(device const uint8_t* cache,+ uint head_base,+ uint packed_bits,+ uint packed_offset,+ uint D,+ uint dim,+ float scale) {+ const uint packed_base = head_base + packed_offset;+ const uint byte = dim >> 1u;+ const uint shift = (dim & 1u) << 2u;+ const uint idx = (uint(cache[packed_base + byte]) >> shift) & 0xFu;+ return attn_tq_centroid(idx) * scale;+}++static inline uint attn_tq_read_index(device const uint8_t* cache,+ uint head_base,+ uint packed_bits,+ uint packed_offset,+ uint D,+ uint dim) {+ const uint packed_base = head_base + packed_offset;+ const uint byte = dim >> 1u;+ const uint shift = (dim & 1u) << 2u;+ return (uint(cache[packed_base + byte]) >> shift) & 0xFu;+}++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_turboquant_q_rht(+ device const half* Q [[buffer(0)]],+ device half* out [[buffer(1)]],+ constant AttentionTurboQuantKVParams& params [[buffer(2)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]]+) {+ threadgroup float q_smem[kAttnMaxHeadDim];+ const uint HD = params.head_dim;+ const uint q_head = tg_id;+ const uint kv_head = q_head / (params.num_q_heads / params.num_kv_heads);+ device const half* Q_row = Q + q_head * HD;+ for (uint i = lid; i < HD; i += lsize) {+ const float q = float(Q_row[i]);+ q_smem[i] = attn_tq_apply_rotation(q,+ params.layer,+ kv_head,+ i,+ params.rotation_seed);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ attn_tq_wht_inplace_fast(q_smem, HD, lid, lsize, simd_lane_id);++ device half* out_row = out + q_head * HD;+ for (uint i = lid; i < HD; i += lsize) {+ out_row[i] = half(q_smem[i]);+ }+}++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_turboquant_decode_partial(+ device const half* Q [[buffer(0)]],+ device const uint8_t* K_cache [[buffer(1)]],+ device const uint8_t* V_cache [[buffer(2)]],+ device float* m_out [[buffer(3)]],+ device float* d_out [[buffer(4)]],+ device float* o_out [[buffer(5)]],+ constant AttentionTurboQuantKVParams& params [[buffer(6)]],+ constant uint& chunk_len [[buffer(7)]],+ constant uint& num_chunks [[buffer(8)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float q_smem[kAttnMaxHeadDim];+ threadgroup float reduce_scratch[kAttnMaxSimdGroups];+ threadgroup float bcast;++ const uint HD = attn_fc_head_dim(params.head_dim);+ const uint NQ = attn_fc_num_q_heads(params.num_q_heads);+ const uint NKV = attn_fc_num_kv_heads(params.num_kv_heads);+ const uint NC = attn_fc_num_chunks(num_chunks);+ const uint q_head = tg_id / NC;+ const uint chunk = tg_id % NC;+ const uint kv_head = q_head / (NQ / NKV);+ const uint key_bytes_per_token = params.key_bytes_per_head * NKV;+ const uint value_bytes_per_token = params.value_bytes_per_head * NKV;+ const uint p_start = params.kv_start + chunk * chunk_len;+ uint p_end = p_start + chunk_len;+ if (p_end > params.seq_len) { p_end = params.seq_len; }++ device const half* Q_row = Q + q_head * HD;+ for (uint i = lid; i < HD; i += lsize) {+ if (params.q_pretransformed != 0u) {+ q_smem[i] = float(Q_row[i]);+ } else {+ const float q = float(Q_row[i]);+ q_smem[i] = attn_tq_apply_rotation(q,+ params.layer,+ kv_head,+ i,+ params.rotation_seed);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (params.q_pretransformed == 0u) {+ attn_tq_wht_inplace_fast(q_smem, HD, lid, lsize, simd_lane_id);+ }++ constexpr uint kPerThread = (kAttnMaxHeadDim + kAttnThreads - 1) / kAttnThreads;+ float o_local[kPerThread];+ for (uint k = 0; k < kPerThread; ++k) { o_local[k] = 0.0f; }++ float m_run = -INFINITY;+ float d_run = 0.0f;++ for (uint p = p_start; p < p_end; ++p) {+ const uint key_head_base = p * key_bytes_per_token+ + kv_head * params.key_bytes_per_head;+ const uint value_head_base = p * value_bytes_per_token+ + kv_head * params.value_bytes_per_head;+ const device half* key_scale_ptr = reinterpret_cast<const device half*>(+ K_cache + key_head_base + params.key_scale_offset);+ const device half* value_scale_ptr = reinterpret_cast<const device half*>(+ V_cache + value_head_base + params.value_scale_offset);+ const float key_scale = float(*key_scale_ptr);+ const float value_scale = float(*value_scale_ptr);++ float partial = 0.0f;+ for (uint i = lid; i < HD; i += lsize) {+ const float k_val = attn_tq_read_packed(K_cache,+ key_head_base,+ 4u,+ params.key_packed_offset,+ HD,+ i,+ key_scale);+ partial = fma(q_smem[i], k_val, partial);+ }+ float s = block_reduce_sum(partial,+ simd_lane_id, simd_group_id, simdgroups,+ reduce_scratch, &bcast);+ s *= params.scale;++ const float m_new = max(m_run, s);+ const float alpha = attn_softmax_exp(m_run - m_new);+ const float p_exp = attn_softmax_exp(s - m_new);+ d_run = d_run * alpha + p_exp;++ uint slot = 0;+ for (uint i = lid; i < HD; i += lsize) {+ float v_val = attn_tq_read_packed(V_cache,+ value_head_base,+ 4u,+ params.value_packed_offset,+ HD,+ i,+ value_scale);+ o_local[slot] = o_local[slot] * alpha + p_exp * v_val;+ slot += 1;+ }+ m_run = m_new;+ }++ const uint base = q_head * NC + chunk;+ if (lid == 0) {+ m_out[base] = m_run;+ d_out[base] = d_run;+ }+ device float* o_row = o_out + base * HD;+ uint slot = 0;+ for (uint i = lid; i < HD; i += lsize) {+ o_row[i] = o_local[slot];+ slot += 1;+ }+}++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_turboquant_decode_gqa_swa_partial(+ device const half* Q [[buffer(0)]],+ device const uint8_t* K_cache [[buffer(1)]],+ device const uint8_t* V_cache [[buffer(2)]],+ device float* m_out [[buffer(3)]],+ device float* d_out [[buffer(4)]],+ device float* o_out [[buffer(5)]],+ constant AttentionTurboQuantKVParams& params [[buffer(6)]],+ constant uint& chunk_len [[buffer(7)]],+ constant uint& num_chunks [[buffer(8)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]]+) {+ threadgroup float q_smem[kAttnMaxQPerKV * kAttnMaxHeadDim];+ threadgroup float reduce_scratch[kAttnMaxQPerKV * kAttnMaxSimdGroups];+ threadgroup float bcast[kAttnMaxQPerKV];++ const uint HD = attn_fc_head_dim(params.head_dim);+ const uint NQ = attn_fc_num_q_heads(params.num_q_heads);+ const uint NKV = attn_fc_num_kv_heads(params.num_kv_heads);+ const uint NC = attn_fc_num_chunks(num_chunks);+ const uint q_per_kv = NQ / NKV;+ if (q_per_kv > kAttnMaxQPerKV) { return; }++ const uint kv_head = tg_id / NC;+ const uint chunk = tg_id % NC;+ const uint q_base = kv_head * q_per_kv;+ const uint key_bytes_per_token = params.key_bytes_per_head * NKV;+ const uint value_bytes_per_token = params.value_bytes_per_head * NKV;+ const uint p_start = params.kv_start + chunk * chunk_len;+ uint p_end = p_start + chunk_len;+ if (p_end > params.seq_len) { p_end = params.seq_len; }++ for (uint qg = 0; qg < q_per_kv; ++qg) {+ device const half* Q_row = Q + (q_base + qg) * HD;+ threadgroup float* Q_s = q_smem + qg * kAttnMaxHeadDim;+ for (uint i = lid; i < HD; i += lsize) {+ if (params.q_pretransformed != 0u) {+ Q_s[i] = float(Q_row[i]);+ } else {+ const float q = float(Q_row[i]);+ Q_s[i] = attn_tq_apply_rotation(q,+ params.layer,+ kv_head,+ i,+ params.rotation_seed);+ }+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (params.q_pretransformed == 0u) {+ for (uint qg = 0; qg < q_per_kv; ++qg) {+ attn_tq_wht_inplace_fast(q_smem + qg * kAttnMaxHeadDim, HD, lid, lsize, simd_lane_id);+ }+ }++ const uint groups_per_q = max(1u, (lsize / 32u) / q_per_kv);+ const uint active_q = min(q_per_kv - 1u, simd_group_id / groups_per_q);+ const uint local_group = simd_group_id - active_q * groups_per_q;+ const uint threads_per_q = groups_per_q * 32u;+ const uint local_lid = local_group * 32u + simd_lane_id;++ constexpr uint kGQAPerThread =+ (kAttnMaxHeadDim + (kAttnThreads / kAttnMaxQPerKV) - 1) /+ (kAttnThreads / kAttnMaxQPerKV);+ float o_local[kGQAPerThread];+ for (uint k = 0; k < kGQAPerThread; ++k) { o_local[k] = 0.0f; }++ float m_run = -INFINITY;+ float d_run = 0.0f;++ for (uint p = p_start; p < p_end; ++p) {+ const uint key_head_base = p * key_bytes_per_token+ + kv_head * params.key_bytes_per_head;+ const uint value_head_base = p * value_bytes_per_token+ + kv_head * params.value_bytes_per_head;+ const device half* key_scale_ptr = reinterpret_cast<const device half*>(+ K_cache + key_head_base + params.key_scale_offset);+ const device half* value_scale_ptr = reinterpret_cast<const device half*>(+ V_cache + value_head_base + params.value_scale_offset);+ const float key_scale = float(*key_scale_ptr);+ const float value_scale = float(*value_scale_ptr);++ float partial = 0.0f;+ for (uint i = local_lid; i < HD; i += threads_per_q) {+ const float k_val = attn_tq_read_packed(K_cache,+ key_head_base,+ 4u,+ params.key_packed_offset,+ HD,+ i,+ key_scale);+ partial = fma(q_smem[active_q * kAttnMaxHeadDim + i], k_val, partial);+ }++ float s = simd_sum(partial);+ if (simd_lane_id == 0) {+ reduce_scratch[active_q * kAttnMaxSimdGroups + local_group] = s;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (local_group == 0) {+ float t = (simd_lane_id < groups_per_q)+ ? reduce_scratch[active_q * kAttnMaxSimdGroups + simd_lane_id]+ : 0.0f;+ t = simd_sum(t);+ if (simd_lane_id == 0) { bcast[active_q] = t; }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ s = bcast[active_q] * params.scale;++ const float m_new = max(m_run, s);+ const float alpha = attn_softmax_exp(m_run - m_new);+ const float p_exp = attn_softmax_exp(s - m_new);+ d_run = d_run * alpha + p_exp;+ for (uint slot = 0; slot < kGQAPerThread; ++slot) { o_local[slot] *= alpha; }+ m_run = m_new;++ uint slot = 0;+ for (uint i = local_lid; i < HD; i += threads_per_q) {+ float v_val = attn_tq_read_packed(V_cache,+ value_head_base,+ 4u,+ params.value_packed_offset,+ HD,+ i,+ value_scale);+ o_local[slot] += p_exp * v_val;+ slot += 1;+ }+ }++ const uint q_head = q_base + active_q;+ const uint base = q_head * NC + chunk;+ if (local_lid == 0) {+ m_out[base] = m_run;+ d_out[base] = d_run;+ }+ device float* o_row = o_out + base * HD;+ uint slot = 0;+ for (uint i = local_lid; i < HD; i += threads_per_q) {+ o_row[i] = o_local[slot];+ slot += 1;+ }+}++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_turboquant_decode_combine(+ device const float* m_in [[buffer(0)]],+ device const float* d_in [[buffer(1)]],+ device const float* o_in [[buffer(2)]],+ device half* out [[buffer(3)]],+ constant AttentionTurboQuantKVParams& params [[buffer(4)]],+ constant uint& num_chunks [[buffer(5)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]]+) {+ threadgroup float out_smem[kAttnMaxHeadDim];+ const uint HD = attn_fc_head_dim(params.head_dim);+ const uint NQ = attn_fc_num_q_heads(params.num_q_heads);+ const uint NKV = attn_fc_num_kv_heads(params.num_kv_heads);+ const uint NC = attn_fc_num_chunks(num_chunks);+ const uint q_head = tg_id;+ const uint kv_head = q_head / (NQ / NKV);+ device const float* m_row = m_in + q_head * NC;+ device const float* d_row = d_in + q_head * NC;+ device const float* o_base = o_in + q_head * NC * HD;++ float m_glob = -INFINITY;+ for (uint c = 0; c < NC; ++c) {+ m_glob = max(m_glob, m_row[c]);+ }+ float D = 0.0f;+ for (uint c = 0; c < NC; ++c) {+ D += d_row[c] * attn_softmax_exp(m_row[c] - m_glob);+ }+ const float inv_d = (D > 0.0f) ? (1.0f / D) : 0.0f;++ for (uint i = lid; i < HD; i += lsize) {+ float acc = 0.0f;+ for (uint c = 0; c < NC; ++c) {+ acc += o_base[c * HD + i] * attn_softmax_exp(m_row[c] - m_glob);+ }+ out_smem[i] = acc * inv_d;+ }++ threadgroup_barrier(mem_flags::mem_threadgroup);+ attn_tq_wht_inplace_fast(out_smem, HD, lid, lsize, simd_lane_id);++ device half* out_row = out + q_head * HD;+ for (uint i = lid; i < HD; i += lsize) {+ out_row[i] = half(attn_tq_apply_rotation(out_smem[i],+ params.layer,+ kv_head,+ i,+ params.rotation_seed));+ }+}++// ============================================================================+// Split-KV (Flash-Decoding) decode attention — the default path.+//+// The single-pass kernels above run one threadgroup per Q head, each serially+// streaming the whole K/V history. At decode (M_q=1) that is occupancy- and+// latency-bound: 16 Q heads -> 16 threadgroups (cannot fill the GPU's cores),+// and the per-head critical path is seq_len positions long. Splitting each+// head's [kv_start, seq_len) range across `num_chunks` threadgroups turns it+// into 16 * num_chunks threadgroups whose critical path is ~seq_len/num_chunks.+//+// This D512 specialization adapts MLX v0.32.0's one-pass vector geometry. MLX+// does not instantiate its vector kernel at D512. TurboFieldfare selects this path+// for full-attention decode.+kernel void attention_decode_mlx_geometry_full_v2(+ device const half* Q [[buffer(0)]],+ device const half* K [[buffer(1)]],+ device const half* V [[buffer(2)]],+ device half* out [[buffer(3)]],+ constant uint& seq_len [[buffer(4)]],+ constant float& scale [[buffer(5)]],+ uint q_head [[threadgroup_position_in_grid]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]])+{+ constexpr uint kHeadDim = 512;+ constexpr uint kNumKVHeads = 2;+ constexpr uint kQPerKV = 8;+ constexpr uint kSIMDGroups = 32;+ constexpr uint kComponentsPerLane = 16;++ thread float q[kComponentsPerLane];+ thread float key[kComponentsPerLane];+ thread float output[kComponentsPerLane];+ threadgroup float output_exchange[kSIMDGroups * 32];+ threadgroup float max_scores[kSIMDGroups];+ threadgroup float sum_exp_scores[kSIMDGroups];++ const uint kv_head = q_head / kQPerKV;+ const uint component = simd_lid * kComponentsPerLane;+ const uint q_base = q_head * kHeadDim + component;+ for (uint i = 0; i < kComponentsPerLane; ++i) {+ q[i] = scale * float(Q[q_base + i]);+ output[i] = 0.0f;+ }++ float max_score = -INFINITY;+ float sum_exp_score = 0.0f;+ for (uint position = simd_gid; position < seq_len; position += kSIMDGroups) {+ const uint kv_base = (position * kNumKVHeads + kv_head) * kHeadDim + component;+ float score = 0.0f;+ for (uint i = 0; i < kComponentsPerLane; ++i) {+ key[i] = float(K[kv_base + i]);+ score += q[i] * key[i];+ }+ score = simd_sum(score);++ const float new_max = max(max_score, score);+ const float old_factor = fast::exp(max_score - new_max);+ const float score_factor = fast::exp(score - new_max);+ max_score = new_max;+ sum_exp_score = sum_exp_score * old_factor + score_factor;+ for (uint i = 0; i < kComponentsPerLane; ++i) {+ output[i] = output[i] * old_factor + score_factor * float(V[kv_base + i]);+ }+ }++ if (simd_lid == 0) {+ max_scores[simd_gid] = max_score;+ sum_exp_scores[simd_gid] = sum_exp_score;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ max_score = max_scores[simd_lid];+ const float merged_max = simd_max(max_score);+ const float merge_factor = fast::exp(max_score - merged_max);+ sum_exp_score = simd_sum(sum_exp_scores[simd_lid] * merge_factor);++ for (uint i = 0; i < kComponentsPerLane; ++i) {+ output_exchange[simd_lid * kSIMDGroups + simd_gid] = output[i];+ threadgroup_barrier(mem_flags::mem_threadgroup);+ float merged = simd_sum(+ output_exchange[simd_gid * kSIMDGroups + simd_lid] * merge_factor);+ output[i] = sum_exp_score == 0.0f ? merged : merged / sum_exp_score;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }++ if (simd_lid == 0) {+ const uint out_base = q_head * kHeadDim + simd_gid * kComponentsPerLane;+ for (uint i = 0; i < kComponentsPerLane; ++i) {+ out[out_base + i] = half(output[i]);+ }+ }+}++// Pass 1 (attention_decode_partial): grid = num_q_heads * num_chunks. Each TG+// runs the same online-softmax recurrence over its chunk [p_start, p_end) and+// writes the UN-normalized partial state (m_chunk, d_chunk, o_chunk[head_dim])+// to scratch — no division yet.+// Pass 2 (attention_decode_combine): grid = num_q_heads. Each TG merges its+// head's num_chunks partials with the standard online-softmax rescale+// (m_glob = max_c m_c; D = Σ d_c·e^{m_c−m_glob}; O = Σ o_c·e^{m_c−m_glob}) and+// writes out[i] = O[i] / D in FP16.+//+// At num_chunks == 1 the chunk spans the whole [kv_start, seq_len) range and+// the partial is the exact single-pass accumulation; the combine's only chunk+// has m_glob == m_chunk so e^0 == 1 and out == o/d — byte-identical to the+// single-pass kernels above. num_chunks > 1 changes the FP rounding of the+// partial sums only (same position summation order), not the algorithm.+// ============================================================================++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_decode_partial(+ device const half* Q [[buffer(0)]],+ device const half* K [[buffer(1)]],+ device const half* V [[buffer(2)]],+ device float* m_out [[buffer(3)]], // [num_q_heads * num_chunks]+ device float* d_out [[buffer(4)]], // [num_q_heads * num_chunks]+ device float* o_out [[buffer(5)]], // [num_q_heads * num_chunks * head_dim]+ constant uint& head_dim [[buffer(6)]],+ constant uint& num_q_heads [[buffer(7)]],+ constant uint& num_kv_heads [[buffer(8)]],+ constant uint& seq_len [[buffer(9)]],+ constant uint& kv_start [[buffer(10)]],+ constant uint& chunk_len [[buffer(11)]],+ constant uint& num_chunks [[buffer(12)]],+ constant float& scale [[buffer(13)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float q_smem[kAttnMaxHeadDim];+ threadgroup float reduce_scratch[kAttnMaxSimdGroups];+ threadgroup float bcast;+ const uint HD = attn_fc_head_dim(head_dim);+ const uint NQ = attn_fc_num_q_heads(num_q_heads);+ const uint NKV = attn_fc_num_kv_heads(num_kv_heads);+ const uint NC = attn_fc_num_chunks(num_chunks);++ const uint q_head = tg_id / NC;+ const uint chunk = tg_id % NC;+ const uint p_start = kv_start + chunk * chunk_len;+ uint p_end = p_start + chunk_len;+ if (p_end > seq_len) { p_end = seq_len; }++ const uint kv_head = q_head / (NQ / NKV);++ device const half* Q_row = Q + uint(q_head) * HD;+ for (uint i = lid; i < HD; i += lsize) {+ q_smem[i] = float(Q_row[i]);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ constexpr uint kPerThread = (kAttnMaxHeadDim + kAttnThreads - 1) / kAttnThreads;+ float o_local[kPerThread];+ for (uint k = 0; k < kPerThread; ++k) { o_local[k] = 0.0f; }++ float m_run = -INFINITY;+ float d_run = 0.0f;++ // p_start can land past the end when num_chunks > range length (the tail+ // chunks are empty); the loop simply does not execute and the partial is+ // (-inf, 0, 0), which the combine weights to zero via e^{-inf}.+ for (uint p = p_start; p < p_end; ++p) {+ const uint phys_p = attn_ring_slot(p);+ device const half* K_row = K + (phys_p * NKV + kv_head) * HD;+ device const half* V_row = V + (phys_p * NKV + kv_head) * HD;++ float partial = 0.0f;+ for (uint i = lid; i < HD; i += lsize) {+ partial = fma(q_smem[i], float(K_row[i]), partial);+ }+ float s = block_reduce_sum(partial,+ simd_lane_id, simd_group_id, simdgroups,+ reduce_scratch, &bcast);+ s *= attn_fc_scale(scale);++ const float m_new = max(m_run, s);+ const float alpha = attn_softmax_exp(m_run - m_new);+ const float p_exp = attn_softmax_exp(s - m_new);+ d_run = d_run * alpha + p_exp;++ uint slot = 0;+ for (uint i = lid; i < HD; i += lsize) {+ o_local[slot] = o_local[slot] * alpha + p_exp * float(V_row[i]);+ slot += 1;+ }+ m_run = m_new;+ }++ const uint base = uint(q_head) * NC + chunk;+ if (lid == 0) { m_out[base] = m_run; d_out[base] = d_run; }+ device float* o_row = o_out + base * HD;+ uint slot = 0;+ for (uint i = lid; i < HD; i += lsize) {+ o_row[i] = o_local[slot];+ slot += 1;+ }+}++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_decode_gqa_swa_partial(+ device const half* Q [[buffer(0)]],+ device const half* K [[buffer(1)]],+ device const half* V [[buffer(2)]],+ device float* m_out [[buffer(3)]], // [num_q_heads * num_chunks]+ device float* d_out [[buffer(4)]], // [num_q_heads * num_chunks]+ device float* o_out [[buffer(5)]], // [num_q_heads * num_chunks * head_dim]+ constant uint& head_dim [[buffer(6)]],+ constant uint& num_q_heads [[buffer(7)]],+ constant uint& num_kv_heads [[buffer(8)]],+ constant uint& seq_len [[buffer(9)]],+ constant uint& kv_start [[buffer(10)]],+ constant uint& chunk_len [[buffer(11)]],+ constant uint& num_chunks [[buffer(12)]],+ constant float& scale [[buffer(13)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float q_smem[kAttnMaxQPerKV * kAttnMaxHeadDim];+ threadgroup float reduce_scratch[kAttnMaxQPerKV * kAttnMaxSimdGroups];+ threadgroup float bcast[kAttnMaxQPerKV];+ const uint HD = attn_fc_head_dim(head_dim);+ const uint NQ = attn_fc_num_q_heads(num_q_heads);+ const uint NKV = attn_fc_num_kv_heads(num_kv_heads);+ const uint NC = attn_fc_num_chunks(num_chunks);++ const uint q_per_kv = NQ / NKV;+ if (q_per_kv > kAttnMaxQPerKV) { return; }++ const uint kv_head = tg_id / NC;+ const uint chunk = tg_id % NC;+ const uint p_start = kv_start + chunk * chunk_len;+ uint p_end = p_start + chunk_len;+ if (p_end > seq_len) { p_end = seq_len; }++ const uint q_base = kv_head * q_per_kv;+ for (uint qg = 0; qg < q_per_kv; ++qg) {+ device const half* Q_row = Q + (q_base + qg) * HD;+ threadgroup float* Q_s = q_smem + qg * kAttnMaxHeadDim;+ for (uint i = lid; i < HD; i += lsize) {+ Q_s[i] = float(Q_row[i]);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const uint groups_per_q = max(1u, simdgroups / q_per_kv);+ const uint active_q = min(q_per_kv - 1u, simd_group_id / groups_per_q);+ const uint local_group = simd_group_id - active_q * groups_per_q;+ const uint threads_per_q = groups_per_q * 32u;+ const uint local_lid = local_group * 32u + simd_lane_id;++ constexpr uint kGQAPerThread =+ (kAttnMaxHeadDim + (kAttnThreads / kAttnMaxQPerKV) - 1) /+ (kAttnThreads / kAttnMaxQPerKV);+ float o_local[kGQAPerThread];+ for (uint k = 0; k < kGQAPerThread; ++k) { o_local[k] = 0.0f; }++ float m_run = -INFINITY;+ float d_run = 0.0f;++ for (uint p = p_start; p < p_end; ++p) {+ const uint phys_p = attn_ring_slot(p);+ device const half* K_row = K + (phys_p * NKV + kv_head) * HD;+ device const half* V_row = V + (phys_p * NKV + kv_head) * HD;++ float partial = 0.0f;+ for (uint i = local_lid; i < HD; i += threads_per_q) {+ const float k_val = float(K_row[i]);+ partial = fma(q_smem[active_q * kAttnMaxHeadDim + i], k_val, partial);+ }++ float s = simd_sum(partial);+ if (simd_lane_id == 0) {+ reduce_scratch[active_q * kAttnMaxSimdGroups + local_group] = s;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (local_group == 0) {+ float t = (simd_lane_id < groups_per_q)+ ? reduce_scratch[active_q * kAttnMaxSimdGroups + simd_lane_id]+ : 0.0f;+ t = simd_sum(t);+ if (simd_lane_id == 0) { bcast[active_q] = t; }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ s = bcast[active_q] * attn_fc_scale(scale);++ const float m_new = max(m_run, s);+ const float alpha = attn_softmax_exp(m_run - m_new);+ const float p_exp = attn_softmax_exp(s - m_new);+ d_run = d_run * alpha + p_exp;+ for (uint slot = 0; slot < kGQAPerThread; ++slot) { o_local[slot] *= alpha; }+ m_run = m_new;++ uint slot = 0;+ for (uint i = local_lid; i < HD; i += threads_per_q) {+ o_local[slot] += p_exp * float(V_row[i]);+ slot += 1;+ }+ }++ const uint q_head = q_base + active_q;+ const uint base = uint(q_head) * NC + chunk;+ if (local_lid == 0) { m_out[base] = m_run; d_out[base] = d_run; }+ device float* o_row = o_out + base * HD;+ uint slot = 0;+ for (uint i = local_lid; i < HD; i += threads_per_q) {+ o_row[i] = o_local[slot];+ slot += 1;+ }+}++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_decode_combine(+ device const float* m_in [[buffer(0)]], // [num_q_heads * num_chunks]+ device const float* d_in [[buffer(1)]],+ device const float* o_in [[buffer(2)]], // [num_q_heads * num_chunks * head_dim]+ device half* out [[buffer(3)]], // [num_q_heads * head_dim]+ constant uint& head_dim [[buffer(4)]],+ constant uint& num_chunks [[buffer(5)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]]+) {+ const uint HD = attn_fc_head_dim(head_dim);+ const uint NC = attn_fc_num_chunks(num_chunks);+ const uint q_head = tg_id;+ device const float* m_row = m_in + uint(q_head) * NC;+ device const float* d_row = d_in + uint(q_head) * NC;+ device const float* o_base = o_in + uint(q_head) * NC * HD;++ // num_chunks is small (<= a few dozen); each thread recomputes the global+ // max and denominator rather than pay a threadgroup reduction + barriers.+ float m_glob = -INFINITY;+ for (uint c = 0; c < NC; ++c) { m_glob = max(m_glob, m_row[c]); }+ float D = 0.0f;+ for (uint c = 0; c < NC; ++c) { D += d_row[c] * attn_softmax_exp(m_row[c] - m_glob); }+ const float inv_d = (D > 0.0f) ? (1.0f / D) : 0.0f;++ device half* out_row = out + uint(q_head) * HD;+ for (uint i = lid; i < HD; i += lsize) {+ float acc = 0.0f;+ for (uint c = 0; c < NC; ++c) {+ acc += o_base[c * HD + i] * attn_softmax_exp(m_row[c] - m_glob);+ }+ out_row[i] = half(acc * inv_d);+ }+}diff --git a/Sources/TurboFieldfare/Metal/Fusions/fused.metal b/Sources/TurboFieldfare/Metal/Fusions/fused.metalnew file mode 100644index 00000000..beb2f761--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Fusions/fused.metal@@ -0,0 +1,375 @@+#include <metal_stdlib>+using namespace metal;++// ============================================================================+// fused.metal — current decode fusions:+// fused_qkv_epilogue: per-head Q/K/V RMSNorm + NeoX RoPE after projection.+// fused_post_attn_setup: post-attention residual + pre-FFN/router norms.+// fused_layer_tail: real Gemma 4 decoder-layer tail.+// ============================================================================++constant constexpr uint kFusedThreads = 256;+constant constexpr uint kFusedMaxSimdGroups = kFusedThreads / 32; // 8+constant constexpr uint kFusedGroupSize = 64;+// Threadgroup-memory cap for the normalized-hidden staging slot. Sized for+// D=2816 (production hidden dim) with headroom; consumes 8 KB per threadgroup.+constant constexpr uint kFusedMaxD = 4096;+constant constexpr uint kFusedMaxHeadDim = 512;+constant uint FC_FUSED_D [[function_constant(80)]];+constant uint FC_FUSED_N [[function_constant(81)]];+constant uint FC_FUSED_HEAD_DIM [[function_constant(82)]];+constant uint FC_FUSED_NUM_Q_HEADS [[function_constant(83)]];+constant uint FC_FUSED_NUM_KV_HEADS [[function_constant(84)]];+constant uint FC_FUSED_ROTARY [[function_constant(85)]];+constant bool FC_FUSED_USE_FC [[function_constant(86)]];++static inline bool fused_use_fc() {+ return is_function_constant_defined(FC_FUSED_USE_FC) && FC_FUSED_USE_FC;+}++static inline uint fused_fc_d(constant uint& D) {+ return (fused_use_fc() && is_function_constant_defined(FC_FUSED_D)) ? FC_FUSED_D : D;+}++static inline uint fused_fc_n(constant uint& N) {+ return (fused_use_fc() && is_function_constant_defined(FC_FUSED_N)) ? FC_FUSED_N : N;+}++static inline uint fused_fc_head_dim(constant uint& head_dim) {+ return (fused_use_fc() && is_function_constant_defined(FC_FUSED_HEAD_DIM)) ? FC_FUSED_HEAD_DIM : head_dim;+}++static inline uint fused_fc_num_q_heads(constant uint& num_q_heads) {+ return (fused_use_fc() && is_function_constant_defined(FC_FUSED_NUM_Q_HEADS)) ? FC_FUSED_NUM_Q_HEADS : num_q_heads;+}++static inline uint fused_fc_num_kv_heads(constant uint& num_kv_heads) {+ return (fused_use_fc() && is_function_constant_defined(FC_FUSED_NUM_KV_HEADS)) ? FC_FUSED_NUM_KV_HEADS : num_kv_heads;+}++static inline uint fused_fc_rotary(constant uint& rotary) {+ return (fused_use_fc() && is_function_constant_defined(FC_FUSED_ROTARY)) ? FC_FUSED_ROTARY : rotary;+}++inline void fused_rope_neox_pair(thread float& x0,+ thread float& x1,+ uint pair_index,+ uint head_dim,+ float position,+ float theta_base)+{+ const float exponent = -float(2u * pair_index) / float(head_dim);+ const float freq = pow(theta_base, exponent);+ const float angle = position * freq;+ const float c = cos(angle);+ const float s = sin(angle);+ const float r0 = x0 * c - x1 * s;+ const float r1 = x0 * s + x1 * c;+ x0 = r0;+ x1 = r1;+}++// ============================================================================+// fused_qkv_epilogue — real Gemma 4 Q/K/V per-head post-processing.+//+// Replaces the cb1 chain after Q/K/V projection:+// rmsnorm_bf16w_perhead(Q, q_norm) -> rmsnorm_bf16w_perhead(K, k_norm)+// -> rmsnorm_no_scale_perhead(V) -> rope_neox(Q) -> rope_neox(K)+//+// One threadgroup owns one logical head. Q and K use BF16 weights shared across+// heads; V uses no-scale RMSNorm. For Q/K, the normalized per-head values are+// rounded to half in threadgroup memory before RoPE, preserving the standalone+// kernel boundary where RMSNorm writes FP16 and RoPE reads FP16.+// ============================================================================++[[kernel, max_total_threads_per_threadgroup(kFusedThreads)]]+void fused_qkv_epilogue(+ device half* q [[buffer(0)]], // [num_q_heads, head_dim]+ device half* k [[buffer(1)]], // [num_kv_heads, head_dim]+ device half* v [[buffer(2)]], // [num_kv_heads, head_dim]+ device const bfloat* q_weight [[buffer(3)]], // [head_dim]+ device const bfloat* k_weight [[buffer(4)]], // [head_dim]+ constant uint& head_dim [[buffer(5)]],+ constant uint& num_q_heads [[buffer(6)]],+ constant uint& num_kv_heads [[buffer(7)]],+ constant uint& position [[buffer(8)]],+ constant float& theta_base [[buffer(9)]],+ constant uint& rotated_pairs [[buffer(10)]],+ constant float& rms_eps [[buffer(11)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]],+ uint head_group [[threadgroup_position_in_grid]]+) {+ threadgroup half head_tg[kFusedMaxHeadDim];+ threadgroup float partial[kFusedMaxSimdGroups];++ const uint HD = fused_fc_head_dim(head_dim);+ const uint NQ = fused_fc_num_q_heads(num_q_heads);+ const uint NKV = fused_fc_num_kv_heads(num_kv_heads);+ const uint RP = fused_fc_rotary(rotated_pairs);++ const bool is_q = head_group < NQ;+ const bool is_k = !is_q && head_group < (NQ + NKV);+ const bool is_v = !is_q && !is_k && head_group < (NQ + 2u * NKV);+ if (!is_q && !is_k && !is_v) return;++ const uint local_head = is_q ? head_group : (head_group - NQ) % NKV;+ device half* dst = is_q ? (q + local_head * HD)+ : (is_k ? (k + local_head * HD)+ : (v + local_head * HD));+ device const half* src = dst;+ device const bfloat* w = is_q ? q_weight : k_weight;++ float acc = 0.0f;+ for (uint i = lid; i < HD; i += lsize) {+ float xv = float(src[i]);+ acc = fma(xv, xv, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane_id == 0) {+ partial[simd_group_id] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float sum = (simd_lane_id < simdgroups) ? partial[simd_lane_id] : 0.0f;+ sum = simd_sum(sum);+ if (simd_lane_id == 0) {+ partial[0] = rsqrt(sum / float(HD) + rms_eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float inv = partial[0];+ for (uint i = lid; i < HD; i += lsize) {+ float xv = float(src[i]) * inv;+ if (!is_v) {+ xv *= float(w[i]);+ }+ head_tg[i] = half(xv);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (is_v) {+ for (uint i = lid; i < HD; i += lsize) {+ dst[i] = head_tg[i];+ }+ return;+ }++ const uint half_dim = HD / 2u;+ for (uint pair = lid; pair < half_dim; pair += lsize) {+ float x0 = float(head_tg[pair]);+ float x1 = float(head_tg[half_dim + pair]);+ if (pair < RP) {+ fused_rope_neox_pair(x0, x1, pair, HD, float(position), theta_base);+ }+ dst[pair] = half(x0);+ dst[half_dim + pair] = half(x1);+ }+}++// ============================================================================+// fused_layer_tail — real Gemma 4 decoder-layer tail.+//+// Replaces the cb2 chain:+// rmsnorm_bf16w(h2, post_ffn_2) -> residual_add(h1, ...)+// -> rmsnorm_bf16w(..., post_ffn) -> residual_add(hidden, ...)+// -> layer-scalar multiply+//+// The two RMSNorm reductions copy rmsnorm.metal's two-stage reduction order.+// Elementwise adds and scalar multiply preserve the same FP16 stage boundaries+// as the standalone kernels: h1+h2_norm is rounded to half before the second+// reduction, and hidden+post_norm is rounded to half before multiplying by the+// half-cast layer scalar.+// ============================================================================++[[kernel, max_total_threads_per_threadgroup(kFusedThreads)]]+void fused_post_attn_setup(+ device half* hidden [[buffer(0)]], // [D] FP16 in-place+ device const half* attn [[buffer(1)]], // [D] FP16+ device half* dense_x [[buffer(2)]], // [D] FP16+ device half* routed_x [[buffer(3)]], // [D] FP16+ device half* router_x [[buffer(4)]], // [D] FP16+ device const bfloat* w_post_attn [[buffer(5)]], // [D] BF16+ device const bfloat* w_pre_ffn [[buffer(6)]], // [D] BF16+ device const bfloat* w_pre_ffn2 [[buffer(7)]], // [D] BF16+ constant uint& D [[buffer(8)]],+ constant float& rms_eps [[buffer(9)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup half attn_norm_tg[kFusedMaxD];+ threadgroup half hidden_tg[kFusedMaxD];+ threadgroup float partial[kFusedMaxSimdGroups];+ const uint DD = fused_fc_d(D);++ float acc = 0.0f;+ for (uint i = lid; i < DD; i += lsize) {+ float v = float(attn[i]);+ acc = fma(v, v, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane_id == 0) {+ partial[simd_group_id] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float sum = (simd_lane_id < simdgroups) ? partial[simd_lane_id] : 0.0f;+ sum = simd_sum(sum);+ if (simd_lane_id == 0) {+ partial[0] = rsqrt(sum / float(DD) + rms_eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float attn_inv = partial[0];+ for (uint i = lid; i < DD; i += lsize) {+ attn_norm_tg[i] = half(float(attn[i]) * attn_inv * float(w_post_attn[i]));+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ acc = 0.0f;+ for (uint i = lid; i < DD; i += lsize) {+ half h = half(float(hidden[i]) + float(attn_norm_tg[i]));+ hidden_tg[i] = h;+ hidden[i] = h;+ float hf = float(h);+ acc = fma(hf, hf, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane_id == 0) {+ partial[simd_group_id] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float sum = (simd_lane_id < simdgroups) ? partial[simd_lane_id] : 0.0f;+ sum = simd_sum(sum);+ if (simd_lane_id == 0) {+ partial[0] = rsqrt(sum / float(DD) + rms_eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float hidden_inv = partial[0];+ for (uint i = lid; i < DD; i += lsize) {+ const float h = float(hidden_tg[i]) * hidden_inv;+ dense_x[i] = half(h * float(w_pre_ffn[i]));+ routed_x[i] = half(h * float(w_pre_ffn2[i]));+ router_x[i] = half(h);+ }+}++[[kernel, max_total_threads_per_threadgroup(kFusedThreads)]]+void fused_layer_tail(+ device const half* h2 [[buffer(0)]], // [D] FP16+ device const half* h1 [[buffer(1)]], // [D] FP16+ device half* hidden [[buffer(2)]], // [D] FP16 in-place+ device const bfloat* w_postffn2 [[buffer(3)]], // [D] BF16+ device const bfloat* w_postffn [[buffer(4)]], // [D] BF16+ constant uint& D [[buffer(5)]],+ constant float& rms_eps [[buffer(6)]],+ constant float& layer_scalar [[buffer(7)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup half tmp_tg[kFusedMaxD];+ threadgroup half h12_tg[kFusedMaxD];+ threadgroup float partial[kFusedMaxSimdGroups];+ const uint DD = fused_fc_d(D);++ float acc = 0.0f;+ for (uint i = lid; i < DD; i += lsize) {+ float v = float(h2[i]);+ acc = fma(v, v, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane_id == 0) {+ partial[simd_group_id] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float v = (simd_lane_id < simdgroups) ? partial[simd_lane_id] : 0.0f;+ v = simd_sum(v);+ if (simd_lane_id == 0) {+ float mean_sq = v / float(DD);+ partial[0] = rsqrt(mean_sq + rms_eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float inv_h2 = partial[0];+ for (uint i = lid; i < DD; i += lsize) {+ tmp_tg[i] = half(float(h2[i]) * inv_h2 * float(w_postffn2[i]));+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const uint D4 = DD / 4u;+ threadgroup half4* h12_4 = reinterpret_cast<threadgroup half4*>(h12_tg);+ threadgroup half4* tmp_4 = reinterpret_cast<threadgroup half4*>(tmp_tg);+ device const half4* h1_4 = reinterpret_cast<device const half4*>(h1);+ for (uint i = lid; i < D4; i += lsize) {+ h12_4[i] = h1_4[i] + tmp_4[i];+ }+ const uint tailStart = D4 * 4u;+ for (uint i = tailStart + lid; i < DD; i += lsize) {+ h12_tg[i] = h1[i] + tmp_tg[i];+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ acc = 0.0f;+ for (uint i = lid; i < DD; i += lsize) {+ float v = float(h12_tg[i]);+ acc = fma(v, v, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane_id == 0) {+ partial[simd_group_id] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float v = (simd_lane_id < simdgroups) ? partial[simd_lane_id] : 0.0f;+ v = simd_sum(v);+ if (simd_lane_id == 0) {+ float mean_sq = v / float(DD);+ partial[0] = rsqrt(mean_sq + rms_eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float inv_h12 = partial[0];+ for (uint i = lid; i < DD; i += lsize) {+ tmp_tg[i] = half(float(h12_tg[i]) * inv_h12 * float(w_postffn[i]));+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ device half4* hidden4 = reinterpret_cast<device half4*>(hidden);+ for (uint i = lid; i < D4; i += lsize) {+ hidden4[i] = hidden4[i] + tmp_4[i];+ }+ for (uint i = tailStart + lid; i < DD; i += lsize) {+ hidden[i] = hidden[i] + tmp_tg[i];+ }+ threadgroup_barrier(mem_flags::mem_device);++ const half hScale = half(layer_scalar);+ for (uint i = lid; i < D4; i += lsize) {+ hidden4[i] = hidden4[i] * hScale;+ }+ for (uint i = tailStart + lid; i < DD; i += lsize) {+ hidden[i] = hidden[i] * hScale;+ }+}diff --git a/Sources/TurboFieldfare/Metal/KVCache/turboquant.metal b/Sources/TurboFieldfare/Metal/KVCache/turboquant.metalnew file mode 100644index 00000000..6825905f--- /dev/null+++ b/Sources/TurboFieldfare/Metal/KVCache/turboquant.metal@@ -0,0 +1,238 @@+#include <metal_stdlib>+using namespace metal;++// Fused Walsh-Hadamard transform and K4/V4 Lloyd-Max cache packing.+// One threadgroup handles each flattened (token, head) pair.++constant constexpr float kTQCodebook4[16] = {+ -2.7326f, -2.0690f, -1.6181f, -1.2562f,+ -0.9424f, -0.6568f, -0.3881f, -0.1284f,+ 0.1284f, 0.3881f, 0.6568f, 0.9424f,+ 1.2562f, 1.6181f, 2.0690f, 2.7326f+};++constant constexpr float kTQDecision4[15] = {+ (-2.7326f + -2.0690f) * 0.5f,+ (-2.0690f + -1.6181f) * 0.5f,+ (-1.6181f + -1.2562f) * 0.5f,+ (-1.2562f + -0.9424f) * 0.5f,+ (-0.9424f + -0.6568f) * 0.5f,+ (-0.6568f + -0.3881f) * 0.5f,+ (-0.3881f + -0.1284f) * 0.5f,+ (-0.1284f + 0.1284f) * 0.5f,+ ( 0.1284f + 0.3881f) * 0.5f,+ ( 0.3881f + 0.6568f) * 0.5f,+ ( 0.6568f + 0.9424f) * 0.5f,+ ( 0.9424f + 1.2562f) * 0.5f,+ ( 1.2562f + 1.6181f) * 0.5f,+ ( 1.6181f + 2.0690f) * 0.5f,+ ( 2.0690f + 2.7326f) * 0.5f+};++inline uint tq_nearest_index4(float v) {+ uint idx = 0;+ idx += (v >= kTQDecision4[ 0]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 1]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 2]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 3]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 4]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 5]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 6]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 7]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 8]) ? 1u : 0u;+ idx += (v >= kTQDecision4[ 9]) ? 1u : 0u;+ idx += (v >= kTQDecision4[10]) ? 1u : 0u;+ idx += (v >= kTQDecision4[11]) ? 1u : 0u;+ idx += (v >= kTQDecision4[12]) ? 1u : 0u;+ idx += (v >= kTQDecision4[13]) ? 1u : 0u;+ idx += (v >= kTQDecision4[14]) ? 1u : 0u;+ return idx;+}++inline float tq_centroid4(uint idx) {+ return kTQCodebook4[idx];+}++// =========================================================================+// Walsh-Hadamard transform+//+// Iterative butterfly, log2(D) stages. Each stage:+// stride s = 1, 2, 4, ..., D/2+// for each (i, j=i+s) with (i & s) == 0:+// a = x[i]; b = x[j]+// x[i] = (a + b) * INV_SQRT2+// x[j] = (a - b) * INV_SQRT2+//+// One threadgroup per (token, head). D threads, one element per thread held in+// threadgroup memory. Cross-thread butterflies are handled by reading the+// partner element across the threadgroup with a barrier between stages. The+// largest supported head uses 2 KiB of shared float storage, keeping the fused+// cache-write path bounded.+// =========================================================================++constant constexpr float kInvSqrt2 = 0.7071067811865475f;++struct TurboQuantWHTParams {+ uint num_heads;+ uint layer;+ uint rotation_seed;+ uint apply_rotation;+};++inline ulong tq_mix64(ulong z) {+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;+ return z ^ (z >> 31);+}++inline uint tq_rotation_sign(uint layer, uint head, uint dim, uint seed) {+ ulong z = ulong(seed);+ z ^= ulong(layer) * 0x9E3779B97F4A7C15ul;+ z ^= ulong(head) * 0xBF58476D1CE4E5B9ul;+ z ^= ulong(dim) * 0x94D049BB133111EBul;+ return uint(tq_mix64(z) >> 63);+}++inline float tq_apply_rotation(float v,+ constant TurboQuantWHTParams& params,+ uint pair,+ uint dim) {+ if (params.apply_rotation == 0u) {+ return v;+ }+ const uint head = pair % params.num_heads;+ return tq_rotation_sign(params.layer, head, dim, params.rotation_seed) != 0u ? -v : v;+}++inline float wht_body(float v,+ threadgroup float* shared,+ uint lid,+ uint D,+ uint simd_lane) {+ // FP32 throughout for stability; D=512 with FP16 amax ~1 produces a+ // post-WHT scale roughly sqrt(D)=22, well within FP16 range, but+ // intermediate sums overflow if accumulated in FP16.+ for (uint stride = 1u; stride < 32u; stride <<= 1u) {+ float other = simd_shuffle_xor(v, stride);+ v = ((simd_lane & stride) == 0u)+ ? (v + other) * kInvSqrt2+ : (other - v) * kInvSqrt2;+ }++ shared[lid] = v;+ for (uint stride = 32u; stride < D; stride <<= 1u) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if ((lid & stride) == 0u) {+ uint j = lid | stride;+ float a = shared[lid];+ float b = shared[j];+ shared[lid] = (a + b) * kInvSqrt2;+ shared[j] = (a - b) * kInvSqrt2;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ return shared[lid];+}++struct TurboQuantKVWriteParams {+ uint D;+ uint num_heads;+ uint bytes_per_head;+ uint packed_offset;+ uint scale_offset;+ uint token_base;+ uint bytes_per_token;+};++constant uint FC_TQ_D [[function_constant(100)]];+constant uint FC_TQ_NUM_HEADS [[function_constant(101)]];+constant bool FC_TQ_USE_FC [[function_constant(103)]];++static inline bool tq_use_fc() {+ return is_function_constant_defined(FC_TQ_USE_FC) && FC_TQ_USE_FC;+}++static inline uint tq_kv_fc_d(constant TurboQuantKVWriteParams& params) {+ return (tq_use_fc() && is_function_constant_defined(FC_TQ_D)) ? FC_TQ_D : params.D;+}++static inline uint tq_kv_fc_num_heads(constant TurboQuantKVWriteParams& params) {+ return (tq_use_fc() && is_function_constant_defined(FC_TQ_NUM_HEADS)) ? FC_TQ_NUM_HEADS : params.num_heads;+}++static inline uint tq_kv_write_head_base(constant TurboQuantKVWriteParams& params, uint pair) {+ const uint num_heads = tq_kv_fc_num_heads(params);+ const uint token_in_span = pair / num_heads;+ const uint head = pair % num_heads;+ return token_in_span * params.bytes_per_token + head * params.bytes_per_head;+}++[[kernel, max_total_threads_per_threadgroup(512)]]+void turboquant_quant_kv_write_wht(+ device const half* x [[buffer(0)]], // [pairs, D] FP16, pre-WHT+ device uint8_t* cache [[buffer(1)]], // [heads, packed values + scale]+ constant TurboQuantKVWriteParams& params [[buffer(2)]],+ constant TurboQuantWHTParams& wht_params [[buffer(3)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint pair [[threadgroup_position_in_grid]],+ uint simd_lane [[thread_index_in_simdgroup]],+ uint simd_group [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ const uint D = tq_kv_fc_d(params);+ threadgroup float values[512];+ threadgroup float partial[16];++ const uint base = pair * D;+ float v = tq_apply_rotation(float(x[base + lid]), wht_params, pair, lid);+ v = wht_body(v, values, lid, D, simd_lane);+ values[lid] = float(half(v));+ threadgroup_barrier(mem_flags::mem_threadgroup);++ float acc = 0.0f;+ for (uint i = lid; i < D; i += lsize) {+ float w = values[i];+ acc = fma(w, w, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane == 0) {+ partial[simd_group] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ threadgroup float l2_inv_tg;+ threadgroup float l2_scale_tg;+ if (simd_group == 0) {+ float sum = (simd_lane < simdgroups) ? partial[simd_lane] : 0.0f;+ sum = simd_sum(sum);+ if (simd_lane == 0) {+ float s = sqrt(max(sum / float(D), 1e-12f));+ l2_scale_tg = s;+ l2_inv_tg = 1.0f / s;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const uint head_base = tq_kv_write_head_base(params, pair);++ if (lid == 0) {+ device half* scale = reinterpret_cast<device half*>(cache + head_base + params.scale_offset);+ *scale = half(l2_scale_tg);+ }++ threadgroup uint8_t code4[1024];+ const float inv = l2_inv_tg;+ for (uint i = lid; i < D; i += lsize) {+ float qv = values[i] * inv;+ code4[i] = uint8_t(tq_nearest_index4(qv));+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (lid < D / 2u) {+ uint d0 = lid * 2u;+ uint packed = (uint(code4[d0 + 0]) & 0xFu)+ | ((uint(code4[d0 + 1]) & 0xFu) << 4);+ cache[head_base + params.packed_offset + lid] = uint8_t(packed);+ }+}diff --git a/Sources/TurboFieldfare/Metal/MoE/moe.metal b/Sources/TurboFieldfare/Metal/MoE/moe.metalnew file mode 100644index 00000000..ef27b765--- /dev/null+++ b/Sources/TurboFieldfare/Metal/MoE/moe.metal@@ -0,0 +1,482 @@+#include <metal_stdlib>+using namespace metal;++constant constexpr uint kMoEGroupSize = 64;+constant constexpr uint kMaxStreamedExperts = 8;+constant constexpr float kGeluSqrt2OverPi = 0.7978845608028654f;+constant constexpr float kGeluCubicCoeff = 0.044715f;++constant uint FC_ROUTER_NUM_EXPERTS [[function_constant(40)]];+constant uint FC_ROUTER_D [[function_constant(41)]];+constant uint FC_ROUTER_TOP_K [[function_constant(42)]];+constant bool FC_ROUTER_USE_FC [[function_constant(43)]];++constant uint FC_MOE_D [[function_constant(0)]];+constant uint FC_MOE_F [[function_constant(1)]];+constant uint FC_MOE_TOP_K [[function_constant(2)]];+constant bool FC_MOE_USE_FC [[function_constant(3)]];++static inline uint router_fc_num_experts(constant uint& num_experts) {+ return (is_function_constant_defined(FC_ROUTER_USE_FC) &&+ FC_ROUTER_USE_FC &&+ is_function_constant_defined(FC_ROUTER_NUM_EXPERTS))+ ? FC_ROUTER_NUM_EXPERTS+ : num_experts;+}++static inline uint router_fc_d(constant uint& D) {+ return (is_function_constant_defined(FC_ROUTER_USE_FC) &&+ FC_ROUTER_USE_FC &&+ is_function_constant_defined(FC_ROUTER_D))+ ? FC_ROUTER_D+ : D;+}++static inline uint moe_fc_d(constant uint& D) {+ return (is_function_constant_defined(FC_MOE_USE_FC) &&+ FC_MOE_USE_FC &&+ is_function_constant_defined(FC_MOE_D)) ? FC_MOE_D : D;+}++static inline uint moe_fc_f(constant uint& F) {+ return (is_function_constant_defined(FC_MOE_USE_FC) &&+ FC_MOE_USE_FC &&+ is_function_constant_defined(FC_MOE_F)) ? FC_MOE_F : F;+}++static inline uint moe_fc_top_k(constant uint& top_k) {+ return (is_function_constant_defined(FC_MOE_USE_FC) &&+ FC_MOE_USE_FC &&+ is_function_constant_defined(FC_MOE_TOP_K)) ? FC_MOE_TOP_K : top_k;+}++static inline float gelu_pytorch_tanh(float x) {+ const float x3 = x * x * x;+ float inner = kGeluSqrt2OverPi * (x + kGeluCubicCoeff * x3);+ // Clamping avoids Metal tanh producing NaN at large magnitudes while being+ // equivalent to the saturated result at FP32 precision.+ inner = clamp(inner, -20.0f, 20.0f);+ return 0.5f * x * (1.0f + tanh(inner));+}++struct ExpertOffsets {+ uint gate_W_off;+ uint gate_s_off;+ uint gate_b_off;+ uint up_W_off;+ uint up_s_off;+ uint up_b_off;+ uint down_W_off;+ uint down_s_off;+ uint down_b_off;+};++struct RoutedBlobs {+ device const uint8_t* blob[kMaxStreamedExperts];+};++static inline void router_gemv_gemma4_body(+ device const uint8_t* W,+ device const bfloat* scales,+ device const bfloat* biases,+ device const half* hidden,+ device const bfloat* effective_scale,+ device float* out_logits,+ constant uint& num_experts,+ constant uint& D,+ uint rows_per_tg,+ uint tg_idx,+ uint sg_idx,+ uint lane+) {+ const uint NE = router_fc_num_experts(num_experts);+ const uint DD = router_fc_d(D);+ const uint e = tg_idx * rows_per_tg + sg_idx;+ if (e >= NE) return;++ const uint n_groups = DD / kMoEGroupSize;+ device const uint8_t* W_row = W + uint(e) * DD;+ device const bfloat* s_row = scales + uint(e) * n_groups;+ device const bfloat* b_row = biases + uint(e) * n_groups;++ float acc = 0.0f;+ for (uint g = 0; g < n_groups; ++g) {+ const float s = float(s_row[g]);+ const float b = float(b_row[g]);+ const uint idx = g * kMoEGroupSize + lane * 2u;+ const float q0 = float(uint(W_row[idx]));+ const float q1 = float(uint(W_row[idx + 1u]));+ const float x0 = float(hidden[idx]) * float(effective_scale[idx]);+ const float x1 = float(hidden[idx + 1u]) * float(effective_scale[idx + 1u]);+ acc = fma(s, q0 * x0 + q1 * x1, acc);+ acc = fma(b, x0 + x1, acc);+ }+ acc = simd_sum(acc);+ if (lane == 0) out_logits[e] = acc;+}++kernel void router_gemv_gemma4_r4(+ device const uint8_t* W [[buffer(0)]],+ device const bfloat* scales [[buffer(1)]],+ device const bfloat* biases [[buffer(2)]],+ device const half* hidden [[buffer(3)]],+ device const bfloat* effective_scale [[buffer(4)]],+ device float* out_logits [[buffer(5)]],+ constant uint& num_experts [[buffer(6)]],+ constant uint& D [[buffer(7)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ router_gemv_gemma4_body(W, scales, biases, hidden, effective_scale,+ out_logits, num_experts, D, 4, tg_idx, sg_idx, lane);+}++kernel void router_topk_select_k8(+ device const float* logits [[buffer(0)]],+ device const bfloat* per_expert_scale [[buffer(1)]],+ device uint* out_indices [[buffer(2)]],+ device half* out_weights [[buffer(3)]],+ constant uint& num_experts [[buffer(4)]],+ uint tid [[thread_position_in_threadgroup]]+) {+ if (tid != 0) return;+ const uint NE = router_fc_num_experts(num_experts);+ uint top_idx[8];+ float top_score[8];+ for (uint i = 0; i < 8; ++i) {+ top_idx[i] = 0u;+ top_score[i] = -INFINITY;+ }++ for (uint e = 0; e < NE; ++e) {+ const float s = logits[e];+ if (s <= top_score[7]) continue;+ uint pos = 8u;+ for (uint i = 0; i < 8; ++i) {+ if (s > top_score[i] || (s == top_score[i] && e < top_idx[i])) {+ pos = i;+ break;+ }+ }+ if (pos >= 8u) continue;+ for (uint i = 7; i > pos; --i) {+ top_idx[i] = top_idx[i - 1];+ top_score[i] = top_score[i - 1];+ }+ top_idx[pos] = e;+ top_score[pos] = s;+ }++ const float max_s = top_score[0];+ float sum_exp = 0.0f;+ float exps[8];+ for (uint i = 0; i < 8; ++i) {+ const float ex = fast::exp(top_score[i] - max_s);+ exps[i] = ex;+ sum_exp += ex;+ }+ for (uint i = 0; i < 8; ++i) {+ const uint expert_idx = top_idx[i];+ const float weight = exps[i] / sum_exp;+ out_indices[i] = expert_idx;+ out_weights[i] = half(weight * float(per_expert_scale[expert_idx]));+ }+}++// Each SIMD computes one affine INT4 row. Four adjacent groups are loaded as+// aligned 32-bit chunks; remaining groups use one byte per lane.+static inline float moe_int4_gemv_row_simd_dev_vec(+ device const uint8_t* W,+ device const bfloat* S,+ device const bfloat* B,+ device const half* x,+ uint row,+ uint N,+ uint lane+) {+ const uint n_groups = N / kMoEGroupSize;+ const uint row_bytes = N / 2;+ device const uint8_t* W_row = W + uint(row) * row_bytes;+ device const bfloat* s_row = S + uint(row) * n_groups;+ device const bfloat* b_row = B + uint(row) * n_groups;++ float acc = 0.0f;+ const uint full_blocks = n_groups / 4;+ for (uint blk = 0; blk < full_blocks; ++blk) {+ const uint byte_base = blk * 128u + lane * 4u;+ const uint w4 = *((device const uint*)(W_row + byte_base));+ const uint g = blk * 4u + (lane >> 3);+ const float s = float(s_row[g]);+ const float b = float(b_row[g]);+ const uint elem = byte_base * 2u;+ const half4 xa = *((device const half4*)(x + elem));+ const half4 xb = *((device const half4*)(x + elem + 4u));+ const uint b0 = w4 & 0xFFu;+ const uint b1 = (w4 >> 8) & 0xFFu;+ const uint b2 = (w4 >> 16) & 0xFFu;+ const uint b3 = (w4 >> 24) & 0xFFu;+ const float e0 = float(xa.x), e1 = float(xa.y);+ const float e2 = float(xa.z), e3 = float(xa.w);+ const float e4 = float(xb.x), e5 = float(xb.y);+ const float e6 = float(xb.z), e7 = float(xb.w);+ float dot = 0.0f;+ dot = fma(float(b0 & 0x0Fu), e0, dot); dot = fma(float(b0 >> 4), e1, dot);+ dot = fma(float(b1 & 0x0Fu), e2, dot); dot = fma(float(b1 >> 4), e3, dot);+ dot = fma(float(b2 & 0x0Fu), e4, dot); dot = fma(float(b2 >> 4), e5, dot);+ dot = fma(float(b3 & 0x0Fu), e6, dot); dot = fma(float(b3 >> 4), e7, dot);+ const float sum = e0 + e1 + e2 + e3 + e4 + e5 + e6 + e7;+ acc = fma(s, dot, acc);+ acc = fma(b, sum, acc);+ }+ for (uint g = full_blocks * 4u; g < n_groups; ++g) {+ const float s = float(s_row[g]);+ const float b = float(b_row[g]);+ const uint8_t byte = W_row[g * (kMoEGroupSize / 2) + lane];+ const float x0 = float(x[g * kMoEGroupSize + lane * 2u]);+ const float x1 = float(x[g * kMoEGroupSize + lane * 2u + 1u]);+ float dot = fma(float(uint(byte & 0x0Fu)), x0, 0.0f);+ dot = fma(float(uint(byte >> 4)), x1, dot);+ acc = fma(s, dot, acc);+ acc = fma(b, x0 + x1, acc);+ }+ return simd_sum(acc);+}++// Gate and up rows share activation loads. Two 16-bit loads assemble each+// 4-byte weight chunk because packed sub-tensor offsets need only be 2-byte aligned.+static inline float2 moe_int4_gate_up_rows_simd_dev_vec_u16load(+ device const uint8_t* gateW,+ device const bfloat* gateS,+ device const bfloat* gateB,+ device const uint8_t* upW,+ device const bfloat* upS,+ device const bfloat* upB,+ device const half* x,+ uint row,+ uint N,+ uint lane+) {+ const uint n_groups = N / kMoEGroupSize;+ const uint row_bytes = N / 2;+ device const uint8_t* gW_row = gateW + uint(row) * row_bytes;+ device const uint8_t* uW_row = upW + uint(row) * row_bytes;+ device const bfloat* gS_row = gateS + uint(row) * n_groups;+ device const bfloat* gB_row = gateB + uint(row) * n_groups;+ device const bfloat* uS_row = upS + uint(row) * n_groups;+ device const bfloat* uB_row = upB + uint(row) * n_groups;++ float g_acc = 0.0f;+ float u_acc = 0.0f;+ const uint full_blocks = n_groups / 4;+ for (uint blk = 0; blk < full_blocks; ++blk) {+ const uint byte_base = blk * 128u + lane * 4u;+ device const ushort* gp = (device const ushort*)(gW_row + byte_base);+ device const ushort* up = (device const ushort*)(uW_row + byte_base);+ const uint gw4 = uint(gp[0]) | (uint(gp[1]) << 16);+ const uint uw4 = uint(up[0]) | (uint(up[1]) << 16);+ const uint g = blk * 4u + (lane >> 3);+ const float gs = float(gS_row[g]);+ const float gb = float(gB_row[g]);+ const float us = float(uS_row[g]);+ const float ub = float(uB_row[g]);+ const uint elem = byte_base * 2u;+ const half4 xa = *((device const half4*)(x + elem));+ const half4 xb = *((device const half4*)(x + elem + 4u));+ const float e0 = float(xa.x), e1 = float(xa.y);+ const float e2 = float(xa.z), e3 = float(xa.w);+ const float e4 = float(xb.x), e5 = float(xb.y);+ const float e6 = float(xb.z), e7 = float(xb.w);+ const float sum = e0 + e1 + e2 + e3 + e4 + e5 + e6 + e7;++ const uint gb0 = gw4 & 0xFFu;+ const uint gb1 = (gw4 >> 8) & 0xFFu;+ const uint gb2 = (gw4 >> 16) & 0xFFu;+ const uint gb3 = (gw4 >> 24) & 0xFFu;+ float g_dot = 0.0f;+ g_dot = fma(float(gb0 & 0x0Fu), e0, g_dot); g_dot = fma(float(gb0 >> 4), e1, g_dot);+ g_dot = fma(float(gb1 & 0x0Fu), e2, g_dot); g_dot = fma(float(gb1 >> 4), e3, g_dot);+ g_dot = fma(float(gb2 & 0x0Fu), e4, g_dot); g_dot = fma(float(gb2 >> 4), e5, g_dot);+ g_dot = fma(float(gb3 & 0x0Fu), e6, g_dot); g_dot = fma(float(gb3 >> 4), e7, g_dot);++ const uint ub0 = uw4 & 0xFFu;+ const uint ub1 = (uw4 >> 8) & 0xFFu;+ const uint ub2 = (uw4 >> 16) & 0xFFu;+ const uint ub3 = (uw4 >> 24) & 0xFFu;+ float u_dot = 0.0f;+ u_dot = fma(float(ub0 & 0x0Fu), e0, u_dot); u_dot = fma(float(ub0 >> 4), e1, u_dot);+ u_dot = fma(float(ub1 & 0x0Fu), e2, u_dot); u_dot = fma(float(ub1 >> 4), e3, u_dot);+ u_dot = fma(float(ub2 & 0x0Fu), e4, u_dot); u_dot = fma(float(ub2 >> 4), e5, u_dot);+ u_dot = fma(float(ub3 & 0x0Fu), e6, u_dot); u_dot = fma(float(ub3 >> 4), e7, u_dot);++ g_acc = fma(gs, g_dot, g_acc);+ g_acc = fma(gb, sum, g_acc);+ u_acc = fma(us, u_dot, u_acc);+ u_acc = fma(ub, sum, u_acc);+ }+ for (uint g = full_blocks * 4u; g < n_groups; ++g) {+ const float gs = float(gS_row[g]);+ const float gb = float(gB_row[g]);+ const float us = float(uS_row[g]);+ const float ub = float(uB_row[g]);+ const uint8_t gbv = gW_row[g * (kMoEGroupSize / 2) + lane];+ const uint8_t ubv = uW_row[g * (kMoEGroupSize / 2) + lane];+ const float x0 = float(x[g * kMoEGroupSize + lane * 2u]);+ const float x1 = float(x[g * kMoEGroupSize + lane * 2u + 1u]);+ const float sum = x0 + x1;+ float g_dot = fma(float(uint(gbv & 0x0Fu)), x0, 0.0f);+ g_dot = fma(float(uint(gbv >> 4)), x1, g_dot);+ float u_dot = fma(float(uint(ubv & 0x0Fu)), x0, 0.0f);+ u_dot = fma(float(uint(ubv >> 4)), x1, u_dot);+ g_acc = fma(gs, g_dot, g_acc);+ g_acc = fma(gb, sum, g_acc);+ u_acc = fma(us, u_dot, u_acc);+ u_acc = fma(ub, sum, u_acc);+ }+ return float2(simd_sum(g_acc), simd_sum(u_acc));+}++static inline void moe_phase1_gate_up_act_u16load_body(+ device const RoutedBlobs& routed,+ constant ExpertOffsets& routed_offsets,+ device const half* x,+ device half* acts,+ uint D,+ uint F,+ uint top_k,+ uint rows_per_tg,+ uint tg_idx,+ uint sg_idx,+ uint lane+) {+ const uint rowg = tg_idx * rows_per_tg + sg_idx;+ if (rowg >= top_k * F) return;+ const uint slot = rowg / F;+ const uint f = rowg % F;++ device const uint8_t* base = routed.blob[slot];+ const ExpertOffsets re = routed_offsets;+ device const uint8_t* gW = base + re.gate_W_off;+ device const uint8_t* uW = base + re.up_W_off;+ device const bfloat* gS = (device const bfloat*)(base + re.gate_s_off);+ device const bfloat* uS = (device const bfloat*)(base + re.up_s_off);+ device const bfloat* gB = (device const bfloat*)(base + re.gate_b_off);+ device const bfloat* uB = (device const bfloat*)(base + re.up_b_off);++ const float2 gu = moe_int4_gate_up_rows_simd_dev_vec_u16load(+ gW, gS, gB, uW, uS, uB, x, f, D, lane);+ if (lane == 0) acts[slot * F + f] = half(gelu_pytorch_tanh(gu.x) * gu.y);+}++static inline void moe_phase1_gate_up_act_subset_u16load_body(+ device const RoutedBlobs& routed,+ constant ExpertOffsets& routed_offsets,+ device const half* x,+ device half* acts,+ device const uint* active_slots,+ uint active_count,+ uint D,+ uint F,+ uint top_k,+ uint rows_per_tg,+ uint tg_idx,+ uint sg_idx,+ uint lane+) {+ const uint rowg = tg_idx * rows_per_tg + sg_idx;+ if (rowg >= active_count * F) return;+ const uint active_idx = rowg / F;+ const uint slot = active_slots[active_idx];+ if (slot >= top_k) return;+ const uint f = rowg % F;++ device const uint8_t* base = routed.blob[slot];+ const ExpertOffsets re = routed_offsets;+ device const uint8_t* gW = base + re.gate_W_off;+ device const uint8_t* uW = base + re.up_W_off;+ device const bfloat* gS = (device const bfloat*)(base + re.gate_s_off);+ device const bfloat* uS = (device const bfloat*)(base + re.up_s_off);+ device const bfloat* gB = (device const bfloat*)(base + re.gate_b_off);+ device const bfloat* uB = (device const bfloat*)(base + re.up_b_off);++ const float2 gu = moe_int4_gate_up_rows_simd_dev_vec_u16load(+ gW, gS, gB, uW, uS, uB, x, f, D, lane);+ if (lane == 0) acts[slot * F + f] = half(gelu_pytorch_tanh(gu.x) * gu.y);+}++kernel void moe_phase1_gate_up_act_u16load(+ device const RoutedBlobs& routed [[buffer(0)]],+ constant ExpertOffsets& routed_offsets [[buffer(1)]],+ device const half* x [[buffer(2)]],+ device half* acts [[buffer(3)]],+ constant uint& D [[buffer(4)]],+ constant uint& F [[buffer(5)]],+ constant uint& top_k [[buffer(6)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ constexpr uint rows_per_tg = 8;+ moe_phase1_gate_up_act_u16load_body(+ routed, routed_offsets, x, acts, moe_fc_d(D), moe_fc_f(F),+ moe_fc_top_k(top_k), rows_per_tg, tg_idx, sg_idx, lane);+}++kernel void moe_phase1_gate_up_act_subset_u16load(+ device const RoutedBlobs& routed [[buffer(0)]],+ constant ExpertOffsets& routed_offsets [[buffer(1)]],+ device const half* x [[buffer(2)]],+ device half* acts [[buffer(3)]],+ constant uint& D [[buffer(4)]],+ constant uint& F [[buffer(5)]],+ constant uint& top_k [[buffer(6)]],+ device const uint* active_slots [[buffer(7)]],+ constant uint& active_count [[buffer(8)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ constexpr uint rows_per_tg = 8;+ moe_phase1_gate_up_act_subset_u16load_body(+ routed, routed_offsets, x, acts, active_slots, active_count,+ moe_fc_d(D), moe_fc_f(F), moe_fc_top_k(top_k), rows_per_tg,+ tg_idx, sg_idx, lane);+}++kernel void moe_phase2_down_reduce_k8(+ device const RoutedBlobs& routed [[buffer(0)]],+ constant ExpertOffsets& routed_offsets [[buffer(1)]],+ device const half* acts [[buffer(2)]],+ device const half* routing_w [[buffer(3)]],+ device const half* residual [[buffer(4)]],+ device half* y [[buffer(5)]],+ constant uint& D [[buffer(6)]],+ constant uint& F [[buffer(7)]],+ uint d [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ threadgroup float partial[8];+ const uint DD = moe_fc_d(D);+ const uint FF = moe_fc_f(F);+ if (d >= DD) return;++ device const uint8_t* base = routed.blob[sg_idx];+ const ExpertOffsets re = routed_offsets;+ device const uint8_t* dW = base + re.down_W_off;+ device const bfloat* dS = (device const bfloat*)(base + re.down_s_off);+ device const bfloat* dB = (device const bfloat*)(base + re.down_b_off);+ device const half* act_slot = acts + sg_idx * FF;++ const float value = moe_int4_gemv_row_simd_dev_vec(+ dW, dS, dB, act_slot, d, FF, lane);+ if (lane == 0) partial[sg_idx] = float(routing_w[sg_idx]) * value;+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (sg_idx == 0 && lane == 0) {+ float acc = float(residual[d]);+ acc += partial[0]; acc += partial[1]; acc += partial[2]; acc += partial[3];+ acc += partial[4]; acc += partial[5]; acc += partial[6]; acc += partial[7];+ y[d] = half(acc);+ }+}diff --git a/Sources/TurboFieldfare/Metal/Prefill/prefill.metal b/Sources/TurboFieldfare/Metal/Prefill/prefill.metalnew file mode 100644index 00000000..651681c8--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Prefill/prefill.metal@@ -0,0 +1,1113 @@+#include <metal_stdlib>+using namespace metal;++constant constexpr uint kPrefillGroupSize = 64;+constant constexpr uint kPrefillRmsMaxSimdGroups = 8;+constant constexpr uint kPrefillPostMaxD = 4096;+constant constexpr uint kPrefillRouterMaxExperts = 256;+constant constexpr uint kPrefillRouterMaxTopK = 64;+constant constexpr uint kPrefillAttentionMaxSimdGroups = 16;+constant constexpr uint kPrefillMaxTileExperts = 16;+constant constexpr float kPrefillGeluSqrt2OverPi = 0.7978845608028654f;+constant constexpr float kPrefillGeluCubicCoeff = 0.044715f;+constant uint FC_PREFILL_KV_RING_CAP [[function_constant(76)]];++static inline float prefill_gelu_pytorch_tanh(float x) {+ const float x3 = x * x * x;+ float inner = kPrefillGeluSqrt2OverPi * (x + kPrefillGeluCubicCoeff * x3);+ inner = clamp(inner, -20.0f, 20.0f);+ return 0.5f * x * (1.0f + tanh(inner));+}++kernel void prefill_embed_lookup_int4_block(+ device const uint8_t* table [[buffer(0)]],+ device const bfloat* scales [[buffer(1)]],+ device const bfloat* biases [[buffer(2)]],+ device const uint* tokens [[buffer(3)]],+ device half* out [[buffer(4)]],+ constant uint& T [[buffer(5)]],+ constant uint& D [[buffer(6)]],+ constant float& out_scale [[buffer(7)]],+ uint2 gid [[thread_position_in_grid]]+) {+ const uint d = gid.x;+ const uint t = gid.y;+ if (t >= T || d >= D) return;++ const uint token = tokens[t];+ const uint groups_per_row = D / kPrefillGroupSize;+ device const uint8_t* row_q = table + token * (D / 2u);+ device const bfloat* row_s = scales + token * groups_per_row;+ device const bfloat* row_b = biases + token * groups_per_row;++ const uint8_t byte = row_q[d >> 1];+ const uint q = (d & 1u) == 0u ? uint(byte & 0x0Fu) : uint(byte >> 4);+ const float s = float(row_s[d / kPrefillGroupSize]);+ const float b = float(row_b[d / kPrefillGroupSize]);+ out[t * D + d] = half((float(q) * s + b) * out_scale);+}++static inline float prefill_rms_block_inv(+ device const half* x,+ uint D,+ float eps,+ uint lid,+ uint lsize,+ uint simd_lane_id,+ uint simd_group_id,+ uint simdgroups,+ threadgroup float* partial+) {+ float acc = 0.0f;+ for (uint i = lid; i < D; i += lsize) {+ float v = float(x[i]);+ acc = fma(v, v, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane_id == 0) {+ partial[simd_group_id] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float v = (simd_lane_id < simdgroups) ? partial[simd_lane_id] : 0.0f;+ v = simd_sum(v);+ if (simd_lane_id == 0) {+ partial[0] = rsqrt(v / float(D) + eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ return partial[0];+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void prefill_rmsnorm_bf16w_block(+ device const half* x [[buffer(0)]],+ device const bfloat* weight [[buffer(1)]],+ device half* out [[buffer(2)]],+ constant uint& T [[buffer(3)]],+ constant uint& D [[buffer(4)]],+ constant float& eps [[buffer(5)]],+ uint row [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint lane [[thread_index_in_simdgroup]],+ uint sg [[simdgroup_index_in_threadgroup]],+ uint sgs [[simdgroups_per_threadgroup]]+) {+ if (row >= T) return;+ threadgroup float partial[kPrefillRmsMaxSimdGroups];+ device const half* xr = x + row * D;+ device half* yr = out + row * D;+ const float inv = prefill_rms_block_inv(xr, D, eps, lid, lsize, lane, sg, sgs, partial);++ for (uint i = lid; i < D; i += lsize) {+ yr[i] = half(float(xr[i]) * inv * float(weight[i]));+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void prefill_rmsnorm_bf16w_perhead_block(+ device const half* x [[buffer(0)]],+ device const bfloat* weight [[buffer(1)]],+ device half* out [[buffer(2)]],+ constant uint& T [[buffer(3)]],+ constant uint& head_dim [[buffer(4)]],+ constant uint& num_heads [[buffer(5)]],+ constant uint& token_stride_elems [[buffer(6)]],+ constant float& eps [[buffer(7)]],+ uint3 tg [[threadgroup_position_in_grid]],+ uint3 lid3 [[thread_position_in_threadgroup]],+ uint3 lsize3 [[threads_per_threadgroup]],+ uint lane [[thread_index_in_simdgroup]],+ uint sg [[simdgroup_index_in_threadgroup]],+ uint sgs [[simdgroups_per_threadgroup]]+) {+ const uint h = tg.x;+ const uint t = tg.y;+ const uint lid = lid3.x;+ const uint lsize = lsize3.x;+ if (t >= T || h >= num_heads) return;++ threadgroup float partial[kPrefillRmsMaxSimdGroups];+ device const half* xh = x + t * token_stride_elems + h * head_dim;+ device half* yh = out + t * token_stride_elems + h * head_dim;+ const float inv = prefill_rms_block_inv(xh, head_dim, eps, lid, lsize, lane, sg, sgs, partial);++ for (uint i = lid; i < head_dim; i += lsize) {+ yh[i] = half(float(xh[i]) * inv * float(weight[i]));+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void prefill_rmsnorm_no_scale_perhead_block(+ device const half* x [[buffer(0)]],+ device half* out [[buffer(1)]],+ constant uint& T [[buffer(2)]],+ constant uint& head_dim [[buffer(3)]],+ constant uint& num_heads [[buffer(4)]],+ constant uint& token_stride_elems [[buffer(5)]],+ constant float& eps [[buffer(6)]],+ uint3 tg [[threadgroup_position_in_grid]],+ uint3 lid3 [[thread_position_in_threadgroup]],+ uint3 lsize3 [[threads_per_threadgroup]],+ uint lane [[thread_index_in_simdgroup]],+ uint sg [[simdgroup_index_in_threadgroup]],+ uint sgs [[simdgroups_per_threadgroup]]+) {+ const uint h = tg.x;+ const uint t = tg.y;+ const uint lid = lid3.x;+ const uint lsize = lsize3.x;+ if (t >= T || h >= num_heads) return;++ threadgroup float partial[kPrefillRmsMaxSimdGroups];+ device const half* xh = x + t * token_stride_elems + h * head_dim;+ device half* yh = out + t * token_stride_elems + h * head_dim;+ const float inv = prefill_rms_block_inv(xh, head_dim, eps, lid, lsize, lane, sg, sgs, partial);++ for (uint i = lid; i < head_dim; i += lsize) {+ yh[i] = half(float(xh[i]) * inv);+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void prefill_post_attn_setup_block(+ device half* hidden [[buffer(0)]],+ device const half* attn [[buffer(1)]],+ device half* dense_x [[buffer(2)]],+ device half* routed_x [[buffer(3)]],+ device half* router_x [[buffer(4)]],+ device const bfloat* w_post_attn [[buffer(5)]],+ device const bfloat* w_pre_ffn [[buffer(6)]],+ device const bfloat* w_pre_ffn2 [[buffer(7)]],+ constant uint& T [[buffer(8)]],+ constant uint& D [[buffer(9)]],+ constant uint& hidden_stride_elems [[buffer(10)]],+ constant uint& attn_stride_elems [[buffer(11)]],+ constant uint& dense_stride_elems [[buffer(12)]],+ constant uint& routed_stride_elems [[buffer(13)]],+ constant uint& router_stride_elems [[buffer(14)]],+ constant float& rms_eps [[buffer(15)]],+ uint row [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint lane [[thread_index_in_simdgroup]],+ uint sg [[simdgroup_index_in_threadgroup]],+ uint sgs [[simdgroups_per_threadgroup]]+) {+ if (row >= T || D > kPrefillPostMaxD) return;++ threadgroup half attn_norm_tg[kPrefillPostMaxD];+ threadgroup half hidden_tg[kPrefillPostMaxD];+ threadgroup float partial[kPrefillRmsMaxSimdGroups];++ device half* hidden_row = hidden + row * hidden_stride_elems;+ device const half* attn_row = attn + row * attn_stride_elems;+ device half* dense_row = dense_x + row * dense_stride_elems;+ device half* routed_row = routed_x + row * routed_stride_elems;+ device half* router_row = router_x + row * router_stride_elems;++ const float attn_inv = prefill_rms_block_inv(attn_row, D, rms_eps,+ lid, lsize, lane, sg, sgs,+ partial);+ for (uint i = lid; i < D; i += lsize) {+ attn_norm_tg[i] = half(float(attn_row[i]) * attn_inv * float(w_post_attn[i]));+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ float acc = 0.0f;+ for (uint i = lid; i < D; i += lsize) {+ half h = half(float(hidden_row[i]) + float(attn_norm_tg[i]));+ hidden_tg[i] = h;+ hidden_row[i] = h;+ float hf = float(h);+ acc = fma(hf, hf, acc);+ }+ acc = simd_sum(acc);+ if (lane == 0) {+ partial[sg] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (sg == 0) {+ float sum = (lane < sgs) ? partial[lane] : 0.0f;+ sum = simd_sum(sum);+ if (lane == 0) {+ partial[0] = rsqrt(sum / float(D) + rms_eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float hidden_inv = partial[0];+ for (uint i = lid; i < D; i += lsize) {+ const float h = float(hidden_tg[i]) * hidden_inv;+ dense_row[i] = half(h * float(w_pre_ffn[i]));+ routed_row[i] = half(h * float(w_pre_ffn2[i]));+ router_row[i] = half(h);+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void prefill_layer_tail_block(+ device const half* h2 [[buffer(0)]],+ device const half* h1 [[buffer(1)]],+ device half* hidden [[buffer(2)]],+ device const bfloat* w_postffn2 [[buffer(3)]],+ device const bfloat* w_postffn [[buffer(4)]],+ constant uint& T [[buffer(5)]],+ constant uint& D [[buffer(6)]],+ constant uint& h2_stride_elems [[buffer(7)]],+ constant uint& h1_stride_elems [[buffer(8)]],+ constant uint& hidden_stride_elems [[buffer(9)]],+ constant float& rms_eps [[buffer(10)]],+ constant float& layer_scalar [[buffer(11)]],+ uint row [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint lane [[thread_index_in_simdgroup]],+ uint sg [[simdgroup_index_in_threadgroup]],+ uint sgs [[simdgroups_per_threadgroup]]+) {+ if (row >= T || D > kPrefillPostMaxD) return;++ threadgroup half tmp_tg[kPrefillPostMaxD];+ threadgroup half h12_tg[kPrefillPostMaxD];+ threadgroup float partial[kPrefillRmsMaxSimdGroups];++ device const half* h2_row = h2 + row * h2_stride_elems;+ device const half* h1_row = h1 + row * h1_stride_elems;+ device half* hidden_row = hidden + row * hidden_stride_elems;++ const float inv_h2 = prefill_rms_block_inv(h2_row, D, rms_eps,+ lid, lsize, lane, sg, sgs,+ partial);+ for (uint i = lid; i < D; i += lsize) {+ tmp_tg[i] = half(float(h2_row[i]) * inv_h2 * float(w_postffn2[i]));+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ for (uint i = lid; i < D; i += lsize) {+ h12_tg[i] = h1_row[i] + tmp_tg[i];+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ float acc = 0.0f;+ for (uint i = lid; i < D; i += lsize) {+ float v = float(h12_tg[i]);+ acc = fma(v, v, acc);+ }+ acc = simd_sum(acc);+ if (lane == 0) {+ partial[sg] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (sg == 0) {+ float sum = (lane < sgs) ? partial[lane] : 0.0f;+ sum = simd_sum(sum);+ if (lane == 0) {+ partial[0] = rsqrt(sum / float(D) + rms_eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float inv_h12 = partial[0];+ for (uint i = lid; i < D; i += lsize) {+ tmp_tg[i] = half(float(h12_tg[i]) * inv_h12 * float(w_postffn[i]));+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ for (uint i = lid; i < D; i += lsize) {+ hidden_row[i] = hidden_row[i] + tmp_tg[i];+ }+ threadgroup_barrier(mem_flags::mem_device);++ const half h_scale = half(layer_scalar);+ for (uint i = lid; i < D; i += lsize) {+ hidden_row[i] = hidden_row[i] * h_scale;+ }+}++struct PrefillTokenExpertPairMSL {+ uint token;+ uint expert;+ uint rank;+ uint weight_bits_and_reserved;+};++struct PrefillStreamedRoutedBlobsMSL {+ device const uint8_t* blob[kPrefillMaxTileExperts];+};++struct PrefillGroupedRoutedMoEStreamedParamsMSL {+ uint pair_start;+ uint pair_count;+ uint D;+ uint F;+ uint top_k;+ uint hidden_stride_elements;+ uint live_expert_count;+ uint local_expert_0;+ uint local_expert_1;+ uint local_expert_2;+ uint local_expert_3;+ uint local_expert_4;+ uint local_expert_5;+ uint local_expert_6;+ uint local_expert_7;+ uint local_expert_8;+ uint local_expert_9;+ uint local_expert_10;+ uint local_expert_11;+ uint local_expert_12;+ uint local_expert_13;+ uint local_expert_14;+ uint local_expert_15;+ uint gate_W_off;+ uint gate_s_off;+ uint gate_b_off;+ uint up_W_off;+ uint up_s_off;+ uint up_b_off;+ uint down_W_off;+ uint down_s_off;+ uint down_b_off;+};++static inline uint prefill_streamed_local_expert_id(+ constant PrefillGroupedRoutedMoEStreamedParamsMSL& p,+ uint slot+) {+ switch (slot) {+ case 0: return p.local_expert_0;+ case 1: return p.local_expert_1;+ case 2: return p.local_expert_2;+ case 3: return p.local_expert_3;+ case 4: return p.local_expert_4;+ case 5: return p.local_expert_5;+ case 6: return p.local_expert_6;+ case 7: return p.local_expert_7;+ case 8: return p.local_expert_8;+ case 9: return p.local_expert_9;+ case 10: return p.local_expert_10;+ case 11: return p.local_expert_11;+ case 12: return p.local_expert_12;+ case 13: return p.local_expert_13;+ case 14: return p.local_expert_14;+ default: return p.local_expert_15;+ }+}++static inline float prefill_moe_int4_gemv_row_dev(+ device const uint8_t* W,+ device const bfloat* S,+ device const bfloat* B,+ device const half* x,+ uint row,+ uint N+) {+ const uint groups = N / kPrefillGroupSize;+ const uint row_bytes = N / 2u;+ device const uint8_t* W_row = W + row * row_bytes;+ device const bfloat* s_row = S + row * groups;+ device const bfloat* b_row = B + row * groups;++ float acc = 0.0f;+ for (uint g = 0; g < groups; ++g) {+ const float scale = float(s_row[g]);+ const float bias = float(b_row[g]);+ device const uint8_t* Wg = W_row + g * (kPrefillGroupSize / 2u);+ device const half* xg = x + g * kPrefillGroupSize;+ float dot_qx = 0.0f;+ float sum_x = 0.0f;+ for (uint k = 0; k < kPrefillGroupSize / 2u; ++k) {+ const uint8_t packed = Wg[k];+ const float x0 = float(xg[2u * k]);+ const float x1 = float(xg[2u * k + 1u]);+ dot_qx = fma(float(uint(packed & 0x0Fu)), x0, dot_qx);+ dot_qx = fma(float(uint(packed >> 4)), x1, dot_qx);+ sum_x += x0 + x1;+ }+ acc = fma(scale, dot_qx, acc);+ acc = fma(bias, sum_x, acc);+ }+ return acc;+}++static inline float prefill_moe_int4_gemv_row_tg(+ device const uint8_t* W,+ device const bfloat* S,+ device const bfloat* B,+ threadgroup const half* x,+ uint row,+ uint N+) {+ const uint groups = N / kPrefillGroupSize;+ const uint row_bytes = N / 2u;+ device const uint8_t* W_row = W + row * row_bytes;+ device const bfloat* s_row = S + row * groups;+ device const bfloat* b_row = B + row * groups;++ float acc = 0.0f;+ for (uint g = 0; g < groups; ++g) {+ const float scale = float(s_row[g]);+ const float bias = float(b_row[g]);+ device const uint8_t* Wg = W_row + g * (kPrefillGroupSize / 2u);+ threadgroup const half* xg = x + g * kPrefillGroupSize;+ float dot_qx = 0.0f;+ float sum_x = 0.0f;+ for (uint k = 0; k < kPrefillGroupSize / 2u; ++k) {+ const uint8_t packed = Wg[k];+ const float x0 = float(xg[2u * k]);+ const float x1 = float(xg[2u * k + 1u]);+ dot_qx = fma(float(uint(packed & 0x0Fu)), x0, dot_qx);+ dot_qx = fma(float(uint(packed >> 4)), x1, dot_qx);+ sum_x += x0 + x1;+ }+ acc = fma(scale, dot_qx, acc);+ acc = fma(bias, sum_x, acc);+ }+ return acc;+}++kernel void prefill_router_gemma4_block(+ device const uint8_t* W [[buffer(0)]],+ device const bfloat* scales [[buffer(1)]],+ device const bfloat* biases [[buffer(2)]],+ device const half* hidden [[buffer(3)]],+ device const bfloat* effective_scale [[buffer(4)]],+ device const bfloat* per_expert_scale [[buffer(5)]],+ device uint* out_indices [[buffer(6)]],+ device half* out_weights [[buffer(7)]],+ constant uint& T [[buffer(8)]],+ constant uint& num_experts [[buffer(9)]],+ constant uint& D [[buffer(10)]],+ constant uint& top_k [[buffer(11)]],+ constant uint& hidden_stride [[buffer(12)]],+ uint row [[threadgroup_position_in_grid]],+ uint tid [[thread_position_in_threadgroup]],+ uint tg_size [[threads_per_threadgroup]]+) {+ if (row >= T) return;+ threadgroup float scores[kPrefillRouterMaxExperts];+ const uint NE = min(num_experts, kPrefillRouterMaxExperts);+ const uint KK = min(top_k, kPrefillRouterMaxTopK);+ device const half* row_hidden = hidden + row * hidden_stride;++ for (uint e = tid; e < NE; e += tg_size) {+ const uint n_groups = D / kPrefillGroupSize;+ device const uint8_t* W_row = W + e * D;+ device const bfloat* s_row = scales + e * n_groups;+ device const bfloat* b_row = biases + e * n_groups;++ float acc = 0.0f;+ for (uint g = 0; g < n_groups; ++g) {+ float s = float(s_row[g]);+ float b = float(b_row[g]);+ device const uint8_t* Wg = W_row + g * kPrefillGroupSize;+ device const half* xg = row_hidden + g * kPrefillGroupSize;+ device const bfloat* eg = effective_scale + g * kPrefillGroupSize;+ float dot_qx = 0.0f;+ float sum_x = 0.0f;+ for (uint k = 0; k < kPrefillGroupSize; ++k) {+ float q = float(uint(Wg[k]));+ float xv = float(xg[k]) * float(eg[k]);+ dot_qx = fma(q, xv, dot_qx);+ sum_x += xv;+ }+ acc = fma(s, dot_qx, acc);+ acc = fma(b, sum_x, acc);+ }+ scores[e] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (tid == 0) {+ uint top_idx[kPrefillRouterMaxTopK];+ float top_score[kPrefillRouterMaxTopK];+ for (uint i = 0; i < kPrefillRouterMaxTopK; ++i) {+ top_idx[i] = 0u;+ top_score[i] = -INFINITY;+ }++ for (uint e = 0; e < NE; ++e) {+ float s = scores[e];+ if (KK > 0 && s <= top_score[KK - 1]) continue;+ uint pos = KK;+ for (uint i = 0; i < KK; ++i) {+ if (s > top_score[i] || (s == top_score[i] && e < top_idx[i])) {+ pos = i;+ break;+ }+ }+ if (pos >= KK) continue;+ for (uint i = KK - 1; i > pos; --i) {+ top_idx[i] = top_idx[i - 1];+ top_score[i] = top_score[i - 1];+ }+ top_idx[pos] = e;+ top_score[pos] = s;+ }++ float max_s = top_score[0];+ float sum_exp = 0.0f;+ float exps[kPrefillRouterMaxTopK];+ for (uint i = 0; i < KK; ++i) {+ float e = fast::exp(top_score[i] - max_s);+ exps[i] = e;+ sum_exp += e;+ }+ for (uint i = 0; i < KK; ++i) {+ const uint expert_idx = top_idx[i];+ const float w = exps[i] / sum_exp;+ const float gain = float(per_expert_scale[expert_idx]);+ out_indices[row * top_k + i] = expert_idx;+ out_weights[row * top_k + i] = half(w * gain);+ }+ }+}++kernel void prefill_moe_reduce_token_major(+ device const half* route_partials [[buffer(0)]],+ device const half* route_weights [[buffer(1)]],+ device half* h2 [[buffer(2)]],+ constant uint& T [[buffer(3)]],+ constant uint& top_k [[buffer(4)]],+ constant uint& D [[buffer(5)]],+ uint2 gid [[thread_position_in_grid]]+) {+ const uint d = gid.x;+ const uint t = gid.y;+ if (t >= T || d >= D) return;++ float acc = 0.0f;+ for (uint r = 0; r < top_k; ++r) {+ const uint partial_index = (t * top_k + r) * D + d;+ acc = fma(float(route_weights[t * top_k + r]),+ float(route_partials[partial_index]),+ acc);+ }+ h2[t * D + d] = half(acc);+}++kernel void prefill_grouped_routed_moe_batched_phase1(+ device const half* hidden [[buffer(0)]],+ device const PrefillTokenExpertPairMSL* sorted_pairs [[buffer(1)]],+ device half* gate_up_act_scratch [[buffer(7)]],+ device const PrefillStreamedRoutedBlobsMSL& routed [[buffer(9)]],+ constant PrefillGroupedRoutedMoEStreamedParamsMSL& p [[buffer(10)]],+ uint2 gid [[thread_position_in_grid]]+) {+ const uint f = gid.x;+ const uint pair_local = gid.y;+ if (f >= p.F || pair_local >= p.pair_count) return;++ const PrefillTokenExpertPairMSL pair = sorted_pairs[p.pair_start + pair_local];+ uint local_slot = kPrefillMaxTileExperts;+ for (uint slot = 0; slot < p.live_expert_count; ++slot) {+ if (prefill_streamed_local_expert_id(p, slot) == pair.expert) {+ local_slot = slot;+ break;+ }+ }+ if (local_slot >= p.live_expert_count) return;++ device const uint8_t* expert = routed.blob[local_slot];+ device const half* x = hidden + pair.token * p.hidden_stride_elements;+ device const uint8_t* gate_W = expert + p.gate_W_off;+ device const bfloat* gate_s = reinterpret_cast<device const bfloat*>(expert + p.gate_s_off);+ device const bfloat* gate_b = reinterpret_cast<device const bfloat*>(expert + p.gate_b_off);+ device const uint8_t* up_W = expert + p.up_W_off;+ device const bfloat* up_s = reinterpret_cast<device const bfloat*>(expert + p.up_s_off);+ device const bfloat* up_b = reinterpret_cast<device const bfloat*>(expert + p.up_b_off);++ const float gate = prefill_moe_int4_gemv_row_dev(gate_W, gate_s, gate_b, x, f, p.D);+ const float up = prefill_moe_int4_gemv_row_dev(up_W, up_s, up_b, x, f, p.D);+ const uint row_elements = p.pair_count * p.F;+ const uint index = pair_local * p.F + f;+ gate_up_act_scratch[index] = half(gate);+ gate_up_act_scratch[row_elements + index] = half(up);+ gate_up_act_scratch[2u * row_elements + index] =+ half(prefill_gelu_pytorch_tanh(gate) * up);+}++kernel void prefill_grouped_routed_moe_batched_down(+ device const PrefillTokenExpertPairMSL* sorted_pairs [[buffer(1)]],+ device half* route_partials [[buffer(5)]],+ device const half* gate_up_act_scratch [[buffer(7)]],+ device half* down_scratch [[buffer(8)]],+ device const PrefillStreamedRoutedBlobsMSL& routed [[buffer(9)]],+ constant PrefillGroupedRoutedMoEStreamedParamsMSL& p [[buffer(10)]],+ uint2 gid [[thread_position_in_grid]]+) {+ const uint d = gid.x;+ const uint pair_local = gid.y;+ if (d >= p.D || pair_local >= p.pair_count) return;++ const PrefillTokenExpertPairMSL pair = sorted_pairs[p.pair_start + pair_local];+ uint local_slot = kPrefillMaxTileExperts;+ for (uint slot = 0; slot < p.live_expert_count; ++slot) {+ if (prefill_streamed_local_expert_id(p, slot) == pair.expert) {+ local_slot = slot;+ break;+ }+ }+ if (local_slot >= p.live_expert_count) return;++ device const uint8_t* expert = routed.blob[local_slot];+ device const uint8_t* down_W = expert + p.down_W_off;+ device const bfloat* down_s = reinterpret_cast<device const bfloat*>(expert + p.down_s_off);+ device const bfloat* down_b = reinterpret_cast<device const bfloat*>(expert + p.down_b_off);+ device const half* act = gate_up_act_scratch + 2u * p.pair_count * p.F + pair_local * p.F;+ const half value = half(prefill_moe_int4_gemv_row_dev(down_W, down_s, down_b, act, d, p.F));+ down_scratch[pair_local * p.D + d] = value;+ route_partials[(pair.token * p.top_k + pair.rank) * p.D + d] = value;+}++kernel void prefill_dequant_int4_qmm_f16_block(+ device const uint8_t* W [[buffer(0)]],+ device const bfloat* scales [[buffer(1)]],+ device const bfloat* biases [[buffer(2)]],+ device const half* X [[buffer(3)]],+ device half* Y [[buffer(4)]],+ constant uint& T [[buffer(5)]],+ constant uint& N [[buffer(6)]],+ constant uint& K [[buffer(7)]],+ uint2 tid [[thread_position_in_threadgroup]],+ uint2 tgid [[threadgroup_position_in_grid]]+) {+ const uint n = tgid.x * 8u + tid.x;+ const uint t = tgid.y * 8u + tid.y;+ if (t >= T || n >= N) return;++ const uint groups = K / kPrefillGroupSize;+ const uint row_bytes = K / 2u;+ device const uint8_t* w_row = W + n * row_bytes;+ device const bfloat* s_row = scales + n * groups;+ device const bfloat* b_row = biases + n * groups;+ device const half* x_row = X + t * K;++ float acc = 0.0f;+ for (uint g = 0; g < groups; ++g) {+ const float scale = float(s_row[g]);+ const float bias = float(b_row[g]);+ const uint group_base = g * kPrefillGroupSize;+ for (uint kk = 0; kk < kPrefillGroupSize; ++kk) {+ const uint k = group_base + kk;+ const uint8_t packed = w_row[k >> 1];+ const uint q = (k & 1u) == 0u ? uint(packed & 0x0Fu) : uint(packed >> 4);+ const float w = fma(float(q), scale, bias);+ acc = fma(w, float(x_row[k]), acc);+ }+ }+ Y[t * N + n] = half(acc);+}++static inline void prefill_rope_apply_neox_pair(+ device half* head_ptr,+ uint i,+ uint half_dim,+ uint freq_divisor,+ float position,+ float theta_base+) {+ const float exponent = -float(2u * i) / float(freq_divisor);+ const float freq = pow(theta_base, exponent);+ const float angle = position * freq;+ const float c = cos(angle);+ const float s = sin(angle);++ const uint i0 = i;+ const uint i1 = half_dim + i;+ const float x0 = float(head_ptr[i0]);+ const float x1 = float(head_ptr[i1]);+ head_ptr[i0] = half(x0 * c - x1 * s);+ head_ptr[i1] = half(x0 * s + x1 * c);+}++kernel void prefill_rope_default_neox_block(+ device half* data [[buffer(0)]],+ constant uint& start_position [[buffer(1)]],+ constant uint& head_dim [[buffer(2)]],+ constant uint& num_heads [[buffer(3)]],+ constant uint& token_stride_elems [[buffer(4)]],+ constant float& theta_base [[buffer(5)]],+ uint3 gid [[thread_position_in_grid]]+) {+ const uint i = gid.x;+ const uint h = gid.y;+ const uint t = gid.z;+ const uint half_dim = head_dim / 2u;+ if (i >= half_dim) return;+ if (h >= num_heads) return;++ device half* head_ptr = data + t * token_stride_elems + h * head_dim;+ prefill_rope_apply_neox_pair(head_ptr, i, half_dim, head_dim,+ float(start_position + t), theta_base);+}++kernel void prefill_rope_proportional_neox_block(+ device half* data [[buffer(0)]],+ constant uint& start_position [[buffer(1)]],+ constant uint& head_dim [[buffer(2)]],+ constant uint& num_heads [[buffer(3)]],+ constant uint& token_stride_elems [[buffer(4)]],+ constant float& theta_base [[buffer(5)]],+ constant uint& rotated_pairs [[buffer(6)]],+ uint3 gid [[thread_position_in_grid]]+) {+ const uint i = gid.x;+ const uint h = gid.y;+ const uint t = gid.z;+ if (i >= rotated_pairs) return;+ if (h >= num_heads) return;++ const uint half_dim = head_dim / 2u;+ device half* head_ptr = data + t * token_stride_elems + h * head_dim;+ prefill_rope_apply_neox_pair(head_ptr, i, half_dim, head_dim,+ float(start_position + t), theta_base);+}++struct PrefillAttentionParams {+ uint startPosition;+ uint queryCount;+ uint headDim;+ uint numQHeads;+ uint numKVHeads;+ uint kvValidCount;+ uint slidingWindow;+ uint kvTokenStrideElements;+ uint qTokenStrideElements;+ uint oTokenStrideElements;+ float scale;+};++static inline uint prefill_kv_slot(uint logical) {+ return (is_function_constant_defined(FC_PREFILL_KV_RING_CAP) &&+ FC_PREFILL_KV_RING_CAP != 0u)+ ? (logical % FC_PREFILL_KV_RING_CAP)+ : logical;+}++static inline float prefill_attention_tg_sum(+ float value,+ uint lane,+ uint simd_group,+ uint simdgroups,+ threadgroup float* partial+) {+ float s = simd_sum(value);+ if (lane == 0u) {+ partial[simd_group] = s;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group == 0u) {+ float v = lane < simdgroups ? partial[lane] : 0.0f;+ v = simd_sum(v);+ if (lane == 0u) {+ partial[0] = v;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ return partial[0];+}++static inline float prefill_attention_tg_sum_single_bank(+ float value,+ uint lane,+ uint simd_group,+ uint simdgroups,+ threadgroup float* partial+) {+ const float result = prefill_attention_tg_sum(+ value, lane, simd_group, simdgroups, partial);+ // A single scratch bank needs an explicit reader-to-next-writer edge.+ threadgroup_barrier(mem_flags::mem_threadgroup);+ return result;+}++[[kernel, max_total_threads_per_threadgroup(512)]]+kernel void attention_prefill_causal_tiled(+ device const half* Q [[buffer(0)]],+ device const half* K [[buffer(1)]],+ device const half* V [[buffer(2)]],+ device half* O [[buffer(3)]],+ constant PrefillAttentionParams& p [[buffer(4)]],+ uint3 tg [[threadgroup_position_in_grid]],+ uint3 tid [[thread_position_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]],+ uint simd_group [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ const uint t = tg.x;+ const uint qh = tg.y;+ if (t >= p.queryCount || qh >= p.numQHeads) return;++ threadgroup float partial[2u * kPrefillAttentionMaxSimdGroups];++ const uint d = tid.x;+ const bool owns = d < p.headDim;+ const uint q_per_kv = p.numQHeads / p.numKVHeads;+ const uint kvh = qh / q_per_kv;+ const uint abs_q = p.startPosition + t;+ uint first = 0u;+ if (p.slidingWindow != 0u && abs_q + 1u > p.slidingWindow) {+ first = abs_q + 1u - p.slidingWindow;+ }+ const uint last_exclusive = min(p.kvValidCount, abs_q + 1u);++ device const half* q_row = Q + t * p.qTokenStrideElements + qh * p.headDim;+ float row_max = -INFINITY;+ float row_sum = 0.0f;+ float acc = 0.0f;++ for (uint key = first; key < last_exclusive; ++key) {+ const uint phys_key = prefill_kv_slot(key);+ device const half* k_row = K + phys_key * p.kvTokenStrideElements + kvh * p.headDim;+ const float qv = owns ? float(q_row[d]) : 0.0f;+ const float kv = owns ? float(k_row[d]) : 0.0f;+ const uint bank = key & 1u;+ const float score = prefill_attention_tg_sum(+ qv * kv,+ lane,+ simd_group,+ simdgroups,+ partial + bank * kPrefillAttentionMaxSimdGroups) * p.scale;++ const float new_max = max(row_max, score);+ const float old_scale = row_sum > 0.0f ? fast::exp(row_max - new_max) : 0.0f;+ const float new_scale = fast::exp(score - new_max);+ if (owns) {+ device const half* v_row = V + phys_key * p.kvTokenStrideElements + kvh * p.headDim;+ acc = fma(new_scale, float(v_row[d]), acc * old_scale);+ }+ row_sum = row_sum * old_scale + new_scale;+ row_max = new_max;+ }++ if (owns) {+ device half* out_row = O + t * p.oTokenStrideElements + qh * p.headDim;+ out_row[d] = row_sum > 0.0f ? half(acc / row_sum) : half(0.0f);+ }+}++struct PrefillTurboQuantAttentionParams {+ uint startPosition;+ uint queryCount;+ uint headDim;+ uint numQHeads;+ uint numKVHeads;+ uint kvValidCount;+ uint slidingWindow;+ uint qTokenStrideElements;+ uint oTokenStrideElements;+ float scale;+ uint layer;+ uint rotationSeed;+ uint keyBytesPerHead;+ uint keyPackedOffset;+ uint keyScaleOffset;+ uint valueBytesPerHead;+ uint valuePackedOffset;+ uint valueScaleOffset;+};++constant constexpr float kPrefillTQCodebook4[16] = {+ -2.7326f, -2.0690f, -1.6181f, -1.2562f,+ -0.9424f, -0.6568f, -0.3881f, -0.1284f,+ 0.1284f, 0.3881f, 0.6568f, 0.9424f,+ 1.2562f, 1.6181f, 2.0690f, 2.7326f+};++static inline float prefill_tq_centroid(uint idx) {+ return kPrefillTQCodebook4[idx];+}++static inline ulong prefill_tq_mix64(ulong z) {+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;+ return z ^ (z >> 31);+}++static inline bool prefill_tq_rotation_is_negative(uint layer,+ uint head,+ uint dim,+ uint seed) {+ ulong z = ulong(seed);+ z ^= ulong(layer) * 0x9E3779B97F4A7C15ul;+ z ^= ulong(head) * 0xBF58476D1CE4E5B9ul;+ z ^= ulong(dim) * 0x94D049BB133111EBul;+ return (prefill_tq_mix64(z) >> 63) != 0ul;+}++static inline float prefill_tq_apply_rotation(float v,+ uint layer,+ uint head,+ uint dim,+ uint seed) {+ return prefill_tq_rotation_is_negative(layer, head, dim, seed) ? -v : v;+}++static inline void prefill_tq_wht_inplace(threadgroup float* data,+ uint D,+ uint lid,+ uint lsize) {+ for (uint stride = 1u; stride < D; stride <<= 1u) {+ for (uint j = lid; j < D / 2u; j += lsize) {+ const uint block = j / stride;+ const uint lane = j - block * stride;+ const uint a_idx = block * stride * 2u + lane;+ const uint b_idx = a_idx + stride;+ const float a = data[a_idx];+ const float b = data[b_idx];+ data[a_idx] = (a + b) * 0.7071067811865475f;+ data[b_idx] = (a - b) * 0.7071067811865475f;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }+}++static inline uint prefill_tq_read_index(device const uint8_t* cache,+ uint head_base,+ uint packed_offset,+ uint dim) {+ const uint packed_base = head_base + packed_offset;+ const uint byte = dim >> 1u;+ const uint shift = (dim & 1u) << 2u;+ return (uint(cache[packed_base + byte]) >> shift) & 0xFu;+}++static inline float prefill_tq_read_packed(device const uint8_t* cache,+ uint head_base,+ uint packed_offset,+ uint dim,+ float scale) {+ return prefill_tq_centroid(+ prefill_tq_read_index(cache, head_base, packed_offset, dim)) * scale;+}++[[kernel, max_total_threads_per_threadgroup(256)]]+kernel void attention_prefill_turboquant_causal_tiled(+ device const half* Q [[buffer(0)]],+ device const uint8_t* K_cache [[buffer(1)]],+ device const uint8_t* V_cache [[buffer(2)]],+ device half* O [[buffer(3)]],+ constant PrefillTurboQuantAttentionParams& p [[buffer(4)]],+ uint3 tg [[threadgroup_position_in_grid]],+ uint3 tid3 [[thread_position_in_threadgroup]],+ uint3 lsize3 [[threads_per_threadgroup]],+ uint lane [[thread_index_in_simdgroup]],+ uint simd_group [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ const uint t = tg.x;+ const uint qh = tg.y;+ if (t >= p.queryCount || qh >= p.numQHeads) return;++ threadgroup float q_smem[512];+ threadgroup float out_smem[512];+ threadgroup float partial[kPrefillAttentionMaxSimdGroups];++ const uint D = p.headDim;+ const uint tid = tid3.x;+ const uint lsize = lsize3.x;+ const uint q_per_kv = p.numQHeads / p.numKVHeads;+ const uint kvh = qh / q_per_kv;+ const uint key_bytes_per_token = p.keyBytesPerHead * p.numKVHeads;+ const uint value_bytes_per_token = p.valueBytesPerHead * p.numKVHeads;+ const uint abs_q = p.startPosition + t;++ uint first = 0u;+ if (p.slidingWindow != 0u && abs_q + 1u > p.slidingWindow) {+ first = abs_q + 1u - p.slidingWindow;+ }+ const uint last_exclusive = min(p.kvValidCount, abs_q + 1u);++ device const half* q_row = Q + t * p.qTokenStrideElements + qh * D;+ for (uint i = tid; i < D; i += lsize) {+ const float qv = float(q_row[i]);+ q_smem[i] = prefill_tq_apply_rotation(qv, p.layer, kvh, i, p.rotationSeed);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ prefill_tq_wht_inplace(q_smem, D, tid, lsize);++ float row_max = -INFINITY;+ float row_sum = 0.0f;+ float acc0 = 0.0f;+ float acc1 = 0.0f;+ const uint d0 = tid;+ const uint d1 = tid + lsize;+ const bool owns0 = d0 < D;+ const bool owns1 = d1 < D;++ for (uint key = first; key < last_exclusive; ++key) {+ const uint key_head_base = key * key_bytes_per_token + kvh * p.keyBytesPerHead;+ const uint value_head_base = key * value_bytes_per_token + kvh * p.valueBytesPerHead;+ const device half* key_scale_ptr = reinterpret_cast<const device half*>(+ K_cache + key_head_base + p.keyScaleOffset);+ const device half* value_scale_ptr = reinterpret_cast<const device half*>(+ V_cache + value_head_base + p.valueScaleOffset);+ const float key_scale = float(*key_scale_ptr);+ const float value_scale = float(*value_scale_ptr);++ float partial_dot = 0.0f;+ for (uint i = tid; i < D; i += lsize) {+ const float k_val = prefill_tq_read_packed(K_cache,+ key_head_base,+ p.keyPackedOffset,+ i,+ key_scale);+ partial_dot = fma(q_smem[i], k_val, partial_dot);+ }++ float score = prefill_attention_tg_sum_single_bank(+ partial_dot, lane, simd_group, simdgroups, partial);+ score *= p.scale;++ const float new_max = max(row_max, score);+ const float old_scale = row_sum > 0.0f ? fast::exp(row_max - new_max) : 0.0f;+ const float new_scale = fast::exp(score - new_max);+ if (owns0) {+ const float v0 = prefill_tq_read_packed(V_cache,+ value_head_base,+ p.valuePackedOffset,+ d0,+ value_scale);+ acc0 = fma(new_scale, v0, acc0 * old_scale);+ }+ if (owns1) {+ const float v1 = prefill_tq_read_packed(V_cache,+ value_head_base,+ p.valuePackedOffset,+ d1,+ value_scale);+ acc1 = fma(new_scale, v1, acc1 * old_scale);+ }+ row_sum = row_sum * old_scale + new_scale;+ row_max = new_max;+ }++ if (owns0) {+ out_smem[d0] = row_sum > 0.0f ? acc0 / row_sum : 0.0f;+ }+ if (owns1) {+ out_smem[d1] = row_sum > 0.0f ? acc1 / row_sum : 0.0f;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ prefill_tq_wht_inplace(out_smem, D, tid, lsize);++ if (owns0) {+ device half* out_row = O + t * p.oTokenStrideElements + qh * D;+ const float value0 = prefill_tq_apply_rotation(+ out_smem[d0], p.layer, kvh, d0, p.rotationSeed);+ out_row[d0] = half(value0);+ if (owns1) {+ const float value1 = prefill_tq_apply_rotation(+ out_smem[d1], p.layer, kvh, d1, p.rotationSeed);+ out_row[d1] = half(value1);+ }+ }+}diff --git a/Sources/TurboFieldfare/Metal/Primitives/rmsnorm.metal b/Sources/TurboFieldfare/Metal/Primitives/rmsnorm.metalnew file mode 100644index 00000000..66a11223--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Primitives/rmsnorm.metal@@ -0,0 +1,175 @@+#include <metal_stdlib>+using namespace metal;++// ============================================================================+// rmsnorm — RMS-norm over hidden dim.+//+// inv = rsqrt(mean(x[i]^2) + eps)+// y[i] = x[i] * inv * weight[i]+//+// FP32 accumulator (numerical stability: D=2816 with FP16 inputs can overflow+// FP16 sum-of-squares once activations grow past ~1.2 in magnitude).+// FP16 storage in and out. Learned weights are BF16 where present.+//+// Dispatch: one threadgroup per row, 256 threads per group. Two-stage block+// reduce — SIMD-group simd_sum, then a single SIMD-group merges the partials.+// ============================================================================++// Threadgroup memory carries at most simdgroups_per_threadgroup = 256/32 = 8+// partial sums. Slot 0 is reused after the merge to broadcast the final inv.+constant constexpr uint kRmsMaxSimdGroups = 8;+constant uint FC_RMS_D [[function_constant(30)]];+constant bool FC_RMS_USE_FC [[function_constant(31)]];++static inline uint rms_fc_d(constant uint& D) {+ return (is_function_constant_defined(FC_RMS_USE_FC) &&+ FC_RMS_USE_FC &&+ is_function_constant_defined(FC_RMS_D)) ? FC_RMS_D : D;+}++// Common block reduction. Returns `inv = rsqrt(mean(x^2) + eps)` broadcast to+// every thread via threadgroup memory slot 0.+static inline float rms_block_inv(+ device const half* x,+ uint D,+ float eps,+ uint lid,+ uint lsize,+ uint simd_lane_id,+ uint simd_group_id,+ uint simdgroups,+ threadgroup float* partial+) {+ float acc = 0.0f;+ for (uint i = lid; i < D; i += lsize) {+ float v = float(x[i]);+ acc = fma(v, v, acc);+ }+ acc = simd_sum(acc);+ if (simd_lane_id == 0) {+ partial[simd_group_id] = acc;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float v = (simd_lane_id < simdgroups) ? partial[simd_lane_id] : 0.0f;+ v = simd_sum(v);+ if (simd_lane_id == 0) {+ float mean_sq = v / float(D);+ partial[0] = rsqrt(mean_sq + eps);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ return partial[0];+}++// Gemma 4 RMS norms ship as BF16 weight vectors (all 30 layers' input /+// post-attn / pre-FFN / post-FFN norms, plus q/k_norm). Math is identical to+// the no-scale form below, with a learned weight applied after normalization.+[[kernel, max_total_threads_per_threadgroup(256)]]+void rmsnorm_bf16w(+ device const half* x [[buffer(0)]], // [D] FP16+ device const bfloat* weight [[buffer(1)]], // [D] BF16+ device half* out [[buffer(2)]], // [D] FP16+ constant uint& D [[buffer(3)]],+ constant float& eps [[buffer(4)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float partial[kRmsMaxSimdGroups];+ const uint DD = rms_fc_d(D);+ const float inv = rms_block_inv(x, DD, eps, lid, lsize,+ simd_lane_id, simd_group_id, simdgroups,+ partial);++ for (uint i = lid; i < DD; i += lsize) {+ float xv = float(x[i]);+ float wv = float(weight[i]);+ out[i] = half(xv * inv * wv);+ }+}++// Gemma 4 applies q_norm/k_norm+// (BF16 weight, shared across heads) and v_norm (no-scale) to each attention+// head independently. These kernels process all heads in one dispatch, with+// one threadgroup per head, avoiding a chain of tiny serialized encoders.+// Math is identical to the single-row kernels applied per head.+[[kernel, max_total_threads_per_threadgroup(256)]]+void rmsnorm_bf16w_perhead(+ device const half* x [[buffer(0)]], // [numHeads * headDim] FP16+ device const bfloat* weight [[buffer(1)]], // [headDim] BF16, shared per head+ device half* out [[buffer(2)]], // [numHeads * headDim] FP16+ constant uint& headDim [[buffer(3)]],+ constant float& eps [[buffer(4)]],+ uint head [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float partial[kRmsMaxSimdGroups];+ const uint HD = rms_fc_d(headDim);+ device const half* xh = x + head * HD;+ device half* oh = out + head * HD;+ const float inv = rms_block_inv(xh, HD, eps, lid, lsize,+ simd_lane_id, simd_group_id, simdgroups, partial);+ for (uint i = lid; i < HD; i += lsize) {+ float xv = float(xh[i]);+ float wv = float(weight[i]);+ oh[i] = half(xv * inv * wv);+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void rmsnorm_no_scale_perhead(+ device const half* x [[buffer(0)]], // [numHeads * headDim] FP16+ device half* out [[buffer(1)]], // [numHeads * headDim] FP16+ constant uint& headDim [[buffer(2)]],+ constant float& eps [[buffer(3)]],+ uint head [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float partial[kRmsMaxSimdGroups];+ const uint HD = rms_fc_d(headDim);+ device const half* xh = x + head * HD;+ device half* oh = out + head * HD;+ const float inv = rms_block_inv(xh, HD, eps, lid, lsize,+ simd_lane_id, simd_group_id, simdgroups, partial);+ for (uint i = lid; i < HD; i += lsize) {+ oh[i] = half(float(xh[i]) * inv);+ }+}++// Gemma 4 v_norm and the MoE router's internal norm are no-scale RMSNorm:+// y[i] = x[i] * rsqrt(mean(x^2) + eps). There is no resident weight tensor.+[[kernel, max_total_threads_per_threadgroup(256)]]+void rmsnorm_no_scale(+ device const half* x [[buffer(0)]], // [D] FP16+ device half* out [[buffer(1)]], // [D] FP16+ constant uint& D [[buffer(2)]],+ constant float& eps [[buffer(3)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float partial[kRmsMaxSimdGroups];+ const uint DD = rms_fc_d(D);+ const float inv = rms_block_inv(x, DD, eps, lid, lsize,+ simd_lane_id, simd_group_id, simdgroups,+ partial);++ for (uint i = lid; i < DD; i += lsize) {+ float xv = float(x[i]);+ out[i] = half(xv * inv);+ }+}diff --git a/Sources/TurboFieldfare/Metal/Primitives/rope.metal b/Sources/TurboFieldfare/Metal/Primitives/rope.metalnew file mode 100644index 00000000..799ce209--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Primitives/rope.metal@@ -0,0 +1,98 @@+#include <metal_stdlib>+using namespace metal;++constant uint FC_ROPE_HEAD_DIM [[function_constant(50)]];+constant uint FC_ROPE_NUM_HEADS [[function_constant(51)]];+constant uint FC_ROPE_ROTATED_PAIRS [[function_constant(52)]];+constant bool FC_ROPE_USE_FC [[function_constant(53)]];++static inline uint rope_head_dim(constant uint& runtime_value) {+ return (is_function_constant_defined(FC_ROPE_USE_FC) &&+ FC_ROPE_USE_FC &&+ is_function_constant_defined(FC_ROPE_HEAD_DIM))+ ? FC_ROPE_HEAD_DIM+ : runtime_value;+}+static inline uint rope_num_heads(constant uint& runtime_value) {+ return (is_function_constant_defined(FC_ROPE_USE_FC) &&+ FC_ROPE_USE_FC &&+ is_function_constant_defined(FC_ROPE_NUM_HEADS))+ ? FC_ROPE_NUM_HEADS+ : runtime_value;+}++static inline uint rope_rotated_pairs(constant uint& runtime_value) {+ return (is_function_constant_defined(FC_ROPE_USE_FC) &&+ FC_ROPE_USE_FC &&+ is_function_constant_defined(FC_ROPE_ROTATED_PAIRS))+ ? FC_ROPE_ROTATED_PAIRS+ : runtime_value;+}++static inline void apply_neox_pair(+ device half* head,+ uint pair,+ uint half_dim,+ uint frequency_divisor,+ float position,+ float theta+) {+ const float exponent = -float(2u * pair) / float(frequency_divisor);+ const float angle = position * pow(theta, exponent);+ const float cosine = cos(angle);+ const float sine = sin(angle);+ const uint lower = pair;+ const uint upper = half_dim + pair;+ const float x0 = float(head[lower]);+ const float x1 = float(head[upper]);+ head[lower] = half(x0 * cosine - x1 * sine);+ head[upper] = half(x0 * sine + x1 * cosine);+}++kernel void rope_default_neox(+ device half* data [[buffer(0)]],+ constant uint& position [[buffer(1)]],+ constant uint& head_dim [[buffer(2)]],+ constant uint& num_heads [[buffer(3)]],+ constant float& theta [[buffer(4)]],+ uint3 gid [[thread_position_in_grid]]+) {+ const uint pair = gid.x;+ const uint head_index = gid.y;+ const uint token_index = gid.z;+ const uint dimension = rope_head_dim(head_dim);+ const uint heads = rope_num_heads(num_heads);+ const uint half_dimension = dimension / 2u;+ if (pair >= half_dimension || head_index >= heads) return;++ device half* head = data+ + token_index * heads * dimension+ + head_index * dimension;+ apply_neox_pair(head, pair, half_dimension, dimension,+ float(position), theta);+}++kernel void rope_proportional_neox(+ device half* data [[buffer(0)]],+ constant uint& position [[buffer(1)]],+ constant uint& head_dim [[buffer(2)]],+ constant uint& num_heads [[buffer(3)]],+ constant float& theta [[buffer(4)]],+ constant uint& rotated_pairs [[buffer(5)]],+ uint3 gid [[thread_position_in_grid]]+) {+ const uint pair = gid.x;+ const uint head_index = gid.y;+ const uint token_index = gid.z;+ const uint dimension = rope_head_dim(head_dim);+ const uint heads = rope_num_heads(num_heads);+ const uint active_pairs = rope_rotated_pairs(rotated_pairs);+ if (pair >= active_pairs || head_index >= heads) return;++ const uint half_dimension = dimension / 2u;+ device half* head = data+ + token_index * heads * dimension+ + head_index * dimension;+ apply_neox_pair(head, pair, half_dimension, dimension,+ float(position), theta);+}diff --git a/Sources/TurboFieldfare/Metal/Quant/dequant_int4.metal b/Sources/TurboFieldfare/Metal/Quant/dequant_int4.metalnew file mode 100644index 00000000..9ba2b8e7--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Quant/dequant_int4.metal@@ -0,0 +1,244 @@+#include <metal_stdlib>+using namespace metal;++// ============================================================================+// dequant_int4 — MLX `affine` 4-bit dequant.+//+// Layout (per row of length N):+// W : N/2 bytes. Low nibble of byte k = component 2k (unsigned 0..15),+// high nibble = component 2k+1.+// scales : N/64 BF16, one per group of 64.+// biases : N/64 BF16, one per group of 64.+// value : w[i] = float(nibble[i]) * scale[i/64] + bias[i/64].+//+// Affine factoring for GEMV (sum over a group of 64):+// sum_k (q_k * s + b) * x_k = s * sum_k(q_k * x_k) + b * sum_k x_k+// so scale and bias each cost one mul + one FMA per group instead of per+// element; the per-element inner loop keeps the scalar path's FMA count.+// ============================================================================++constant constexpr uint kGroupSize = 64;+constant uint FC_INT4_M [[function_constant(20)]];+constant uint FC_INT4_N [[function_constant(21)]];+constant bool FC_INT4_USE_FC [[function_constant(22)]];+constant uint FC_INT4_QKV_MQ [[function_constant(23)]];+constant uint FC_INT4_QKV_MKV [[function_constant(24)]];+constant uint FC_INT4_QKV_N [[function_constant(25)]];+constant bool FC_INT4_QKV_USE_FC [[function_constant(26)]];++static inline uint int4_fc_m(constant uint& M) {+ return (is_function_constant_defined(FC_INT4_USE_FC) &&+ FC_INT4_USE_FC &&+ is_function_constant_defined(FC_INT4_M)) ? FC_INT4_M : M;+}++static inline uint int4_fc_n(constant uint& N) {+ return (is_function_constant_defined(FC_INT4_USE_FC) &&+ FC_INT4_USE_FC &&+ is_function_constant_defined(FC_INT4_N)) ? FC_INT4_N : N;+}++static inline uint int4_qkv_fc_mq(constant uint& Mq) {+ return (is_function_constant_defined(FC_INT4_QKV_USE_FC) &&+ FC_INT4_QKV_USE_FC &&+ is_function_constant_defined(FC_INT4_QKV_MQ)) ? FC_INT4_QKV_MQ : Mq;+}++static inline uint int4_qkv_fc_mkv(constant uint& Mkv) {+ return (is_function_constant_defined(FC_INT4_QKV_USE_FC) &&+ FC_INT4_QKV_USE_FC &&+ is_function_constant_defined(FC_INT4_QKV_MKV)) ? FC_INT4_QKV_MKV : Mkv;+}++static inline uint int4_qkv_fc_n(constant uint& N) {+ return (is_function_constant_defined(FC_INT4_QKV_USE_FC) &&+ FC_INT4_QKV_USE_FC &&+ is_function_constant_defined(FC_INT4_QKV_N)) ? FC_INT4_QKV_N : N;+}++inline uint nib_lo(uint8_t b) { return uint(b & 0x0F); }+inline uint nib_hi(uint8_t b) { return uint(b >> 4); }+++kernel void embed_lookup_int4(+ device const uint8_t* table [[buffer(0)]], // [V, D/2] nibbles+ device const bfloat* scales [[buffer(1)]], // [V, D/64] BF16+ device const bfloat* biases [[buffer(2)]], // [V, D/64] BF16+ device half* out [[buffer(3)]], // [D] FP16+ constant uint& token_id [[buffer(4)]],+ constant uint& D [[buffer(5)]],+ constant float& out_scale [[buffer(6)]], // pass 1.0 to disable+ uint gid [[thread_position_in_grid]]+) {+ if (gid >= D) return;+ const uint groups_per_row = D / kGroupSize;+ device const uint8_t* row_q = table + uint(token_id) * (D / 2u);+ device const bfloat* row_s = scales + uint(token_id) * groups_per_row;+ device const bfloat* row_b = biases + uint(token_id) * groups_per_row;+ uint8_t byte = row_q[gid >> 1];+ uint q = (gid & 1u) ? uint(byte >> 4) : uint(byte & 0xFu);+ float s = float(row_s[gid / kGroupSize]);+ float b = float(row_b[gid / kGroupSize]);+ out[gid] = half((float(q) * s + b) * out_scale);+}++// y[m] = sum_{n} W[m, n] * x[n]. One-SIMD-per-row variant: 32 threads+// cooperate on a single output row, each handling 2 elements per group of 64+// (one byte → two nibbles). simd_sum reduces across the group; lane 0 writes.+//+// Requires N % 64 == 0 (per group of 64). Validated at the wrapper.+// Each threadgroup handles eight consecutive rows, one SIMD per row. The+// larger work unit gives the scheduler enough independent rows while sharing+// the L1-cached input-vector reads.+static inline void dequant_int4_gemv_simd_body(+ device const uint8_t* W,+ device const bfloat* scales,+ device const bfloat* biases,+ device const half* x,+ device half* y,+ uint M,+ uint N,+ uint rows_per_tg,+ uint tg_idx,+ uint sg_idx,+ uint lane+) {+ const uint row = tg_idx * rows_per_tg + sg_idx;+ if (row >= M) return;+ const uint n_groups = N / kGroupSize;+ const uint row_bytes = N / 2;+ device const uint8_t* W_row = W + uint(row) * row_bytes;+ device const bfloat* s_row = scales + uint(row) * n_groups;+ device const bfloat* b_row = biases + uint(row) * n_groups;++ float acc = 0.0f;+ // The vectorized row path reads+ // weights a uint (4 bytes = 8 nibbles) and x as half4 in 4-group (128-byte)+ // blocks, with a scalar byte-per-lane remainder. Within a block the 32+ // lanes split 8-per-group, each handling 8 contiguous elements of one+ // 64-element group, so the affine factoring s·Σqx + b·Σx is preserved+ // (simd_sum aggregates; s/b are constant within a group). Aligned: row+ // stride N/2 and weightsOffset are multiples of 4; x is+ // half4-aligned (lane*8 elements). N=2816/4096/8192 → 44/64/128 groups, all+ // exact 4-blocks; the remainder covers any non-multiple-of-4 group count.+ const uint full_blocks = n_groups / 4;+ for (uint blk = 0; blk < full_blocks; ++blk) {+ const uint byte_base = blk * 128u + lane * 4u;+ // Read the 4-byte weight chunk as two ushorts. The resident weight+ // tensors are 2-byte aligned but NOT 4-byte aligned (BF16 scale/bias+ // regions leave a 2-aligned weightsOffset), so a `uint*` load would be+ // misaligned (undefined → garbage); a `ushort*` load is safe (row stride+ // N/2, weightsOffset, and byte_base are all even) and halves the loads+ // vs byte-by-byte.+ device const ushort* wp = (device const ushort*)(W_row + byte_base);+ const uint w4 = uint(wp[0]) | (uint(wp[1]) << 16);+ const uint g = blk * 4u + (lane >> 3);+ const float s = float(s_row[g]);+ const float b = float(b_row[g]);+ const uint elem = byte_base * 2u;+ const half4 xa = *((device const half4*)(x + elem));+ const half4 xb = *((device const half4*)(x + elem + 4u));+ const uint b0 = w4 & 0xFFu;+ const uint b1 = (w4 >> 8) & 0xFFu;+ const uint b2 = (w4 >> 16) & 0xFFu;+ const uint b3 = (w4 >> 24) & 0xFFu;+ const float e0 = float(xa.x), e1 = float(xa.y), e2 = float(xa.z), e3 = float(xa.w);+ const float e4 = float(xb.x), e5 = float(xb.y), e6 = float(xb.z), e7 = float(xb.w);+ float dot = 0.0f;+ dot = fma(float(b0 & 0x0Fu), e0, dot); dot = fma(float(b0 >> 4), e1, dot);+ dot = fma(float(b1 & 0x0Fu), e2, dot); dot = fma(float(b1 >> 4), e3, dot);+ dot = fma(float(b2 & 0x0Fu), e4, dot); dot = fma(float(b2 >> 4), e5, dot);+ dot = fma(float(b3 & 0x0Fu), e6, dot); dot = fma(float(b3 >> 4), e7, dot);+ const float sum = e0 + e1 + e2 + e3 + e4 + e5 + e6 + e7;+ acc = fma(s, dot, acc);+ acc = fma(b, sum, acc);+ }+ for (uint g = full_blocks * 4u; g < n_groups; ++g) {+ const float s = float(s_row[g]);+ const float b = float(b_row[g]);+ const uint8_t byte = W_row[g * (kGroupSize / 2) + lane];+ const float x0 = float(x[g * kGroupSize + lane * 2u]);+ const float x1 = float(x[g * kGroupSize + lane * 2u + 1u]);+ float dot = fma(float(uint(byte & 0x0Fu)), x0, 0.0f);+ dot = fma(float(uint(byte >> 4)), x1, dot);+ const float sum = x0 + x1;+ acc = fma(s, dot, acc);+ acc = fma(b, sum, acc);+ }+ acc = simd_sum(acc);+ if (lane == 0) {+ y[row] = half(acc);+ }+}++kernel void dequant_int4_gemv_simd(+ device const uint8_t* W [[buffer(0)]],+ device const bfloat* scales [[buffer(1)]],+ device const bfloat* biases [[buffer(2)]],+ device const half* x [[buffer(3)]],+ device half* y [[buffer(4)]],+ constant uint& M [[buffer(5)]],+ constant uint& N [[buffer(6)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ constexpr uint rows_per_tg = 8;+ const uint MM = int4_fc_m(M);+ const uint NN = int4_fc_n(N);+ dequant_int4_gemv_simd_body(W, scales, biases, x, y, MM, NN,+ rows_per_tg, tg_idx, sg_idx, lane);+}+++kernel void dequant_int4_qkv_gemv_simd(+ device const uint8_t* qW [[buffer(0)]],+ device const bfloat* qScales [[buffer(1)]],+ device const bfloat* qBiases [[buffer(2)]],+ device const uint8_t* kW [[buffer(3)]],+ device const bfloat* kScales [[buffer(4)]],+ device const bfloat* kBiases [[buffer(5)]],+ device const uint8_t* vW [[buffer(6)]],+ device const bfloat* vScales [[buffer(7)]],+ device const bfloat* vBiases [[buffer(8)]],+ device const half* x [[buffer(9)]],+ device half* qY [[buffer(10)]],+ device half* kY [[buffer(11)]],+ device half* vY [[buffer(12)]],+ constant uint& Mq [[buffer(13)]],+ constant uint& Mkv [[buffer(14)]],+ constant uint& N [[buffer(15)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ constexpr uint rows_per_tg = 8;+ const uint QQ = int4_qkv_fc_mq(Mq);+ const uint KK = int4_qkv_fc_mkv(Mkv);+ const uint NN = int4_qkv_fc_n(N);+ const uint global_row = tg_idx * rows_per_tg + sg_idx;+ const uint total_rows = QQ + 2u * KK;+ if (global_row >= total_rows) { return; }++ device const uint8_t* W;+ device const bfloat* scales;+ device const bfloat* biases;+ device half* y;+ uint local_row;+ uint M;+ if (global_row < QQ) {+ W = qW; scales = qScales; biases = qBiases; y = qY;+ local_row = global_row;+ M = QQ;+ } else if (global_row < QQ + KK) {+ W = kW; scales = kScales; biases = kBiases; y = kY;+ local_row = global_row - QQ;+ M = KK;+ } else {+ W = vW; scales = vScales; biases = vBiases; y = vY;+ local_row = global_row - QQ - KK;+ M = KK;+ }+ dequant_int4_gemv_simd_body(W, scales, biases, x, y, M, NN,+ 1u, local_row, 0u, lane);+}diff --git a/Sources/TurboFieldfare/Metal/Quant/dequant_int8.metal b/Sources/TurboFieldfare/Metal/Quant/dequant_int8.metalnew file mode 100644index 00000000..3c21521c--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Quant/dequant_int8.metal@@ -0,0 +1,154 @@+#include <metal_stdlib>+using namespace metal;++// ============================================================================+// dequant_int8 — MLX `affine` 8-bit dequant.+//+// Layout per weight row of length N:+// q : N unsigned bytes, range 0..255.+// scales : N/64 BF16, one per group of 64.+// biases : N/64 BF16, one per group of 64.+// value : w[i] = float(q[i]) * scale[i/64] + bias[i/64].+//+// Fused dequant + GEMV for the router and shared expert projections.+// ============================================================================++constant constexpr uint kInt8GroupSize = 64;+constant constexpr uint kRowsPerTGInt8 = 8;+constant uint FC_INT8_M [[function_constant(70)]];+constant uint FC_INT8_N [[function_constant(71)]];+constant bool FC_INT8_USE_FC [[function_constant(72)]];+constant uint FC_SHARED_INT8_ROWS_PER_TG [[function_constant(73)]];+constant constexpr float kInt8GeluSqrt2OverPi = 0.7978845608028654f;+constant constexpr float kInt8GeluCubicCoeff = 0.044715f;++static inline uint int8_fc_m(constant uint& M) {+ return (is_function_constant_defined(FC_INT8_USE_FC) &&+ FC_INT8_USE_FC &&+ is_function_constant_defined(FC_INT8_M)) ? FC_INT8_M : M;+}++static inline uint int8_fc_n(constant uint& N) {+ return (is_function_constant_defined(FC_INT8_USE_FC) &&+ FC_INT8_USE_FC &&+ is_function_constant_defined(FC_INT8_N)) ? FC_INT8_N : N;+}+static inline uint shared_int8_rows_per_tg() {+ return is_function_constant_defined(FC_SHARED_INT8_ROWS_PER_TG)+ ? FC_SHARED_INT8_ROWS_PER_TG+ : kRowsPerTGInt8;+}++inline float int8_gelu_pytorch_tanh(float x) {+ float x3 = x * x * x;+ float inner = kInt8GeluSqrt2OverPi * (x + kInt8GeluCubicCoeff * x3);+ inner = clamp(inner, -20.0f, 20.0f);+ return 0.5f * x * (1.0f + tanh(inner));+}++// y[m] = sum_{n} W[m, n] * x[n]. One-SIMD-per-row variant: 32 threads+// cooperate on a single output row, each handling 2 elements per group of 64.+// Mirror of `dequant_int4_gemv_simd` but with one byte per element (no nibble+// unpack). Dispatch: threadgroupsPerGrid=(M,1,1), threadsPerThreadgroup=(32,1,1).+// See `dequant_int4_gemv_simd` for the multi-row-per-TG rationale; same trick+// applied here so the M=2112/2816 shared MLP GEMVs and the M=262144 lm_head+// stay in the GPU's preferred 256-thread/TG zone.+[[kernel, max_total_threads_per_threadgroup(256)]]+kernel void dequant_int8_gemv_simd(+ device const uint8_t* W [[buffer(0)]],+ device const bfloat* scales [[buffer(1)]],+ device const bfloat* biases [[buffer(2)]],+ device const half* x [[buffer(3)]],+ device half* y [[buffer(4)]],+ constant uint& M [[buffer(5)]],+ constant uint& N [[buffer(6)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ const uint MM = int8_fc_m(M);+ const uint NN = int8_fc_n(N);+ const uint row = tg_idx * kRowsPerTGInt8 + sg_idx;+ if (row >= MM) return;+ const uint n_groups = NN / kInt8GroupSize;+ device const uint8_t* W_row = W + uint(row) * NN;+ device const bfloat* s_row = scales + uint(row) * n_groups;+ device const bfloat* b_row = biases + uint(row) * n_groups;++ float acc = 0.0f;+ for (uint g = 0; g < n_groups; ++g) {+ float s = float(s_row[g]);+ float b = float(b_row[g]);+ uint i0 = g * kInt8GroupSize + lane * 2;+ uint i1 = i0 + 1;+ float q0 = float(uint(W_row[i0]));+ float q1 = float(uint(W_row[i1]));+ float x0 = float(x[i0]);+ float x1 = float(x[i1]);+ float dot_qx = q0 * x0 + q1 * x1;+ float sum_x = x0 + x1;+ acc = fma(s, dot_qx, acc);+ acc = fma(b, sum_x, acc);+ }+ acc = simd_sum(acc);+ if (lane == 0) {+ y[row] = half(acc);+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+kernel void shared_int8_gate_up_act_simd(+ device const uint8_t* gateW [[buffer(0)]],+ device const bfloat* gateScales [[buffer(1)]],+ device const bfloat* gateBiases [[buffer(2)]],+ device const uint8_t* upW [[buffer(3)]],+ device const bfloat* upScales [[buffer(4)]],+ device const bfloat* upBiases [[buffer(5)]],+ device const half* x [[buffer(6)]],+ device half* act [[buffer(7)]],+ constant uint& M [[buffer(8)]],+ constant uint& N [[buffer(9)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint sg_idx [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]+) {+ const uint MM = int8_fc_m(M);+ const uint NN = int8_fc_n(N);+ const uint row = tg_idx * shared_int8_rows_per_tg() + sg_idx;+ if (row >= MM) return;+ const uint n_groups = NN / kInt8GroupSize;+ device const uint8_t* gate_row = gateW + row * NN;+ device const uint8_t* up_row = upW + row * NN;+ device const bfloat* gate_s_row = gateScales + row * n_groups;+ device const bfloat* gate_b_row = gateBiases + row * n_groups;+ device const bfloat* up_s_row = upScales + row * n_groups;+ device const bfloat* up_b_row = upBiases + row * n_groups;++ float gate_acc = 0.0f;+ float up_acc = 0.0f;+ for (uint g = 0; g < n_groups; ++g) {+ uint i0 = g * kInt8GroupSize + lane * 2u;+ uint i1 = i0 + 1u;+ float x0 = float(x[i0]);+ float x1 = float(x[i1]);+ float sum_x = x0 + x1;++ float gate_dot = float(uint(gate_row[i0])) * x0+ + float(uint(gate_row[i1])) * x1;+ gate_acc = fma(float(gate_s_row[g]), gate_dot, gate_acc);+ gate_acc = fma(float(gate_b_row[g]), sum_x, gate_acc);++ float up_dot = float(uint(up_row[i0])) * x0+ + float(uint(up_row[i1])) * x1;+ up_acc = fma(float(up_s_row[g]), up_dot, up_acc);+ up_acc = fma(float(up_b_row[g]), sum_x, up_acc);+ }++ gate_acc = simd_sum(gate_acc);+ up_acc = simd_sum(up_acc);+ if (lane == 0) {+ float gate_half = float(half(gate_acc));+ float up_half = float(half(up_acc));+ act[row] = half(int8_gelu_pytorch_tanh(gate_half) * up_half);+ }+}diff --git a/Sources/TurboFieldfare/Metal/Sampling/logit.metal b/Sources/TurboFieldfare/Metal/Sampling/logit.metalnew file mode 100644index 00000000..748e5375--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Sampling/logit.metal@@ -0,0 +1,787 @@+#include <metal_stdlib>+using namespace metal;++// ============================================================================+// logit.metal — output-head kernels (#12, #13 in the inventory).+//+// logit_softcap_softmax Apply 30 * tanh(z / 30) to raw logits and produce a+// numerically-stable softmax over V=262144.+// sample Sample a single token id from softmaxed probs.+// Supports greedy (temperature=0), temperature, top-k,+// top-p with a seeded PRNG.+//+// Both kernels run in a single threadgroup of 256 threads. V is far too large+// to fit in threadgroup memory (262144 * 4 B = 1 MB), so reductions are done+// in two stages: each thread strides over V, then a SIMD-group + cross-SIMD+// merge collapses partials. Threadgroup memory stores only one float per+// SIMD-group (up to 8 lanes for 256-thread groups on Apple silicon).+// ============================================================================++constant constexpr uint kLogitMaxSimdGroups = 8;+constant constexpr float kSampleTopMaxK = 256.0f; // cap for top-k mask scan++// ----------------------------------------------------------------------------+// K8: logit_softcap_softmax+//+// Online safe softmax (Milakov & Gimelshein, arXiv:1805.02867). Each thread+// walks its stride of V and maintains a running (m, d) pair: m is the max+// softcap'd logit seen so far, d is sum(exp(logit_i - m)). On every new logit+// the rule is:+//+// m_new = max(m, z')+// d_new = d * exp(m - m_new) + exp(z' - m_new)+//+// Softcap is applied inline before the max update — going through DRAM with a+// separate softcap pass costs 1 MB of round-trip traffic.+//+// After the per-thread loop the (m, d) pairs are merged across the threadgroup+// using the same rule, broadcast, and a second pass writes normalized FP16+// probabilities.+// ----------------------------------------------------------------------------++inline float softcap_value(float z, float softcap) {+ // tanh saturates well before |z/softcap|=10, so values like +1e3 collapse+ // cleanly to softcap=30 without exp overflow downstream.+ return softcap * precise::tanh(z / softcap);+}++inline float logit_softmax_exp(float x) {+ return fast::exp(x);+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void logit_softcap_softmax(+ device const half* logits [[buffer(0)]], // [V] FP16+ device half* probs [[buffer(1)]], // [V] FP16+ constant uint& V [[buffer(2)]],+ constant float& softcap [[buffer(3)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ // Per-SIMD-group partials for both the running max and the running sum.+ // Sized for the worst case of 8 SIMD-groups (256 threads / 32-lane SIMD).+ threadgroup float partial_m[kLogitMaxSimdGroups];+ threadgroup float partial_d[kLogitMaxSimdGroups];+ threadgroup float final_m;+ threadgroup float final_inv_d;++ // -log-of-zero sentinel: any real logit beats this on the first compare.+ float m = -INFINITY;+ float d = 0.0f;++ for (uint i = lid; i < V; i += lsize) {+ float z = softcap_value(float(logits[i]), softcap);+ float mn = max(m, z);+ // Guard against the (-inf, -inf) → (-inf, NaN) case on the first iter.+ float scale = (m == -INFINITY) ? 0.0f : logit_softmax_exp(m - mn);+ d = d * scale + logit_softmax_exp(z - mn);+ m = mn;+ }++ // -- SIMD-group reduce.+ // simd_max gives the SIMD-wide max in one instruction; we then rescale our+ // own d to that common max so all 32 lanes share a comparable d term.+ float m_simd = simd_max(m);+ // Lanes that saw no element (m == -inf) must contribute 0, not NaN: when an+ // entire SIMD group is empty (V < threads_per_threadgroup, e.g. small-vocab+ // toy models) m_simd is also -inf, and exp(-inf - -inf) = exp(NaN) = NaN+ // would poison the sum. 0 * NaN is NaN, so guard before the multiply.+ float d_simd = simd_sum((m == -INFINITY) ? 0.0f : d * logit_softmax_exp(m - m_simd));++ if (simd_lane_id == 0) {+ partial_m[simd_group_id] = m_simd;+ partial_d[simd_group_id] = d_simd;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // -- Cross-SIMD merge in SIMD-group 0. Up to kLogitMaxSimdGroups partials.+ if (simd_group_id == 0) {+ float mp = (simd_lane_id < simdgroups) ? partial_m[simd_lane_id] : -INFINITY;+ float dp = (simd_lane_id < simdgroups) ? partial_d[simd_lane_id] : 0.0f;++ float m_all = simd_max(mp);+ // Same rescale trick, same empty-lane guard as above: an empty partial+ // (mp == -inf) contributes 0, never NaN.+ float d_all = simd_sum((mp == -INFINITY) ? 0.0f : dp * logit_softmax_exp(mp - m_all));++ if (simd_lane_id == 0) {+ final_m = m_all;+ // Reciprocal once so the normalize loop is a single multiply.+ final_inv_d = 1.0f / d_all;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const float m_final = final_m;+ const float inv_d_final = final_inv_d;++ for (uint i = lid; i < V; i += lsize) {+ float z = softcap_value(float(logits[i]), softcap);+ probs[i] = half(logit_softmax_exp(z - m_final) * inv_d_final);+ }+}++// ----------------------------------------------------------------------------+// K9: sample+//+// Reads softmaxed probabilities and writes one token id. Behaviour:+//+// temperature == 0 greedy argmax (the top-k / top-p / rng inputs are+// ignored; the argmax of probs is also the argmax of+// logits because softmax is monotonic).+// temperature > 0 top-p filters against the full normalized probability+// distribution, top-k caps the surviving set, then+// temperature reweights only that final categorical+// draw. This matches mlx-lm's sampler-chain order.+//+// xorshift64 is chosen for two reasons: it has a single 64-bit state (cheap+// to seed and to broadcast through threadgroup memory) and the output is bit-+// reproducible across hardware and compilers, which is what the tests assert.+// ----------------------------------------------------------------------------++// Thomas's "xorshift64*" variant — period 2^64-1, bias is negligible for+// sampling and the multiplier scrambles low-bit correlation. We only call it+// from one thread per dispatch, so contention is a non-issue.+inline uint64_t xorshift64(thread uint64_t& s) {+ s ^= s << 13;+ s ^= s >> 7;+ s ^= s << 17;+ return s * 2685821657736338717ULL;+}++inline float uniform01(thread uint64_t& s) {+ // Use the top 24 bits as a [0,1) float — matches IEEE-754 mantissa width+ // so the result is exactly representable.+ uint32_t bits = uint32_t(xorshift64(s) >> 40);+ return float(bits) * (1.0f / 16777216.0f);+}++// Counter-based SplitMix64 keeps Gumbel draws deterministic across replays at+// a fixed seed without a precomputed random buffer.+inline uint64_t lmhead_splitmix64(uint64_t x) {+ x = x + 0x9E3779B97F4A7C15ull;+ x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;+ x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;+ return x ^ (x >> 31);+}++inline float lmhead_gumbel_for(uint64_t seed, uint position, uint row) {+ // Domain separation: mix (seed, position, row) by xors before the+ // splitmix scramble so adjacent rows yield independent draws.+ uint64_t key = seed ^ (uint64_t(position) * 0xD2B74407B1CE6E93ull) ^ uint64_t(row);+ uint64_t r = lmhead_splitmix64(key);+ // [0, 1) with 24 mantissa bits; clamp away from zero/one so the double-log+ // can never overflow. 1/16777216 maps to ~5.96e-8, well above FP32 ULP.+ uint32_t bits = uint32_t(r >> 40);+ float u = (float(bits) + 0.5f) * (1.0f / 16777216.0f);+ return -log(-log(u));+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void sample(+ device const half* probs [[buffer(0)]], // [V] FP16+ device uint* out_token [[buffer(1)]], // [1] UInt32+ constant uint& V [[buffer(2)]],+ constant float& temperature [[buffer(3)]],+ constant uint& top_k [[buffer(4)]],+ constant float& top_p [[buffer(5)]],+ constant uint64_t& seed [[buffer(6)]],+ constant uint& position [[buffer(7)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float partial_val[kLogitMaxSimdGroups];+ threadgroup uint partial_idx[kLogitMaxSimdGroups];+ threadgroup uint chosen;++ // ------------------------------------------------------------------+ // Greedy path (temperature == 0). Pure argmax(probs).+ // Softmax is monotonic, so we can argmax over probs directly without+ // looking back at the raw logits.+ // ------------------------------------------------------------------+ if (temperature <= 0.0f) {+ float best_v = -INFINITY;+ uint best_i = 0;++ for (uint i = lid; i < V; i += lsize) {+ float p = float(probs[i]);+ if (p > best_v) {+ best_v = p;+ best_i = i;+ }+ }++ // SIMD-group argmax: simd_max gives the value; we need the matching+ // index, which simd_max can't return. Roll it manually: every lane+ // broadcasts (val, idx) via simd_shuffle and keeps the best pair.+ // 32-lane fan-in is one log2(32)=5-step tree but the lane-by-lane+ // scan is equally fast at this size and simpler to read.+ float m_simd = simd_max(best_v);+ uint i_simd = best_i;+ // Tie-break: lowest index wins. Lanes whose value isn't the SIMD max+ // bow out with idx = UINT_MAX so simd_min picks the surviving smallest.+ i_simd = (best_v == m_simd) ? best_i : 0xFFFFFFFFu;+ i_simd = simd_min(i_simd);++ if (simd_lane_id == 0) {+ partial_val[simd_group_id] = m_simd;+ partial_idx[simd_group_id] = i_simd;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float v = (simd_lane_id < simdgroups) ? partial_val[simd_lane_id] : -INFINITY;+ uint i = (simd_lane_id < simdgroups) ? partial_idx[simd_lane_id] : 0xFFFFFFFFu;+ float m_all = simd_max(v);+ uint i_all = (v == m_all) ? i : 0xFFFFFFFFu;+ i_all = simd_min(i_all);+ if (simd_lane_id == 0) {+ out_token[0] = i_all;+ }+ }+ return;+ }++ // ------------------------------------------------------------------+ // Fast stochastic path: no top-k, no top-p. Sampling from p^(1/T)/Z is+ // exactly argmax_i(log(p_i)/T + g_i) with iid Gumbel noise g_i — one+ // parallel V-pass, same shape as the greedy argmax above. The top-k+ // extraction loop below costs k full V-passes (k clamps to 256 when+ // top_k is "disabled"), which measured at ~2.6 s/token at V=262144;+ // this path replaces it for the common plain-temperature case.+ // ------------------------------------------------------------------+ if (top_k == 0u && (top_p <= 0.0f || top_p >= 1.0f)) {+ float inv_t = 1.0f / temperature;+ float best_v = -INFINITY;+ uint best_i = 0xFFFFFFFFu;++ for (uint i = lid; i < V; i += lsize) {+ float p = float(probs[i]);+ if (!(p > 0.0f)) continue;+ float s = inv_t * log(p) + lmhead_gumbel_for(seed, position, i);+ if (s > best_v) {+ best_v = s;+ best_i = i;+ }+ }++ float m_simd = simd_max(best_v);+ uint i_simd = (best_v == m_simd) ? best_i : 0xFFFFFFFFu;+ i_simd = simd_min(i_simd);++ if (simd_lane_id == 0) {+ partial_val[simd_group_id] = m_simd;+ partial_idx[simd_group_id] = i_simd;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float v = (simd_lane_id < simdgroups) ? partial_val[simd_lane_id] : -INFINITY;+ uint i = (simd_lane_id < simdgroups) ? partial_idx[simd_lane_id] : 0xFFFFFFFFu;+ float m_all = simd_max(v);+ uint i_all = (v == m_all) ? i : 0xFFFFFFFFu;+ i_all = simd_min(i_all);+ if (simd_lane_id == 0) {+ // All-zero probs cannot occur post-softmax, but a fully+ // skipped scan would leave UINT_MAX; fall back to index 0.+ out_token[0] = (i_all == 0xFFFFFFFFu) ? 0u : i_all;+ }+ }+ return;+ }++ // ------------------------------------------------------------------+ // Truncating stochastic path (top-k and/or top-p set).+ //+ // 1. Find the top-k threshold by repeatedly extracting the max and+ // storing it in a small threadgroup buffer (k <= kSampleTopMaxK).+ // 2. Top-p truncates against the full-vocabulary probability mass.+ // 3. Temperature reweights the survivors as p^(1/T).+ // 4. CDF inverse-transform sample with the seeded PRNG.+ //+ // We use a *single* thread for the top-k / top-p / sample logic. Each+ // top-k slot costs one full V-pass, so explicit small top_k stays+ // tolerable; the k=256 worst case is exactly what the fast path above+ // removes from the default configuration.+ // ------------------------------------------------------------------++ // -- Threadgroup buffers for the sampler state. 256 floats + 256 indices+ // = 3 KB, comfortably inside the 32 KB threadgroup limit on Apple9+.+ threadgroup float topk_val[256];+ threadgroup uint topk_idx[256];+ threadgroup uint topk_count;++ // Effective k. top_k == 0 disables top-k entirely; we represent that as+ // k = V (subject to the kSampleTopMaxK working-buffer cap).+ uint k_req = (top_k == 0u) ? V : top_k;+ uint k = min(k_req, uint(kSampleTopMaxK));+ k = min(k, V);+ float inv_temp = 1.0f / temperature;++ if (lid == 0) {+ topk_count = 0;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // -- Extract top-k via k repeated argmax passes.+ // For each slot: every thread scans its V-stride for the argmax that+ // hasn't already been claimed, then we reduce across the threadgroup.+ // Claimed slots are tracked by index, not by zeroing the input — leaves+ // the probs buffer untouched (it's `device const`).+ for (uint slot = 0; slot < k; ++slot) {+ float best_v = -INFINITY;+ uint best_i = 0xFFFFFFFFu;++ for (uint i = lid; i < V; i += lsize) {+ float p = float(probs[i]);+ // Skip already-claimed indices.+ bool claimed = false;+ for (uint c = 0; c < slot; ++c) {+ if (topk_idx[c] == i) { claimed = true; break; }+ }+ if (claimed) continue;+ if (p > best_v) {+ best_v = p;+ best_i = i;+ }+ }++ float m_simd = simd_max(best_v);+ uint i_simd = (best_v == m_simd) ? best_i : 0xFFFFFFFFu;+ i_simd = simd_min(i_simd);++ if (simd_lane_id == 0) {+ partial_val[simd_group_id] = m_simd;+ partial_idx[simd_group_id] = i_simd;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ float v = (simd_lane_id < simdgroups) ? partial_val[simd_lane_id] : -INFINITY;+ uint i = (simd_lane_id < simdgroups) ? partial_idx[simd_lane_id] : 0xFFFFFFFFu;+ float m_all = simd_max(v);+ uint i_all = (v == m_all) ? i : 0xFFFFFFFFu;+ i_all = simd_min(i_all);+ if (simd_lane_id == 0) {+ topk_val[slot] = m_all;+ topk_idx[slot] = i_all;+ topk_count = slot + 1;+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }++ // -- Top-p truncation and sample, single-threaded (k <= 256 elements).+ if (lid == 0) {+ // Drop trailing invalid slots. When the working set k exceeds the+ // number of rankable entries (high temperature flattens ties; the tail+ // can exhaust before k slots fill), a slot's reduction yields a -INF+ // value / UINT_MAX index. Those sort last (descending by mass), so the+ // first invalid slot bounds the real count. Slot 0 is the global argmax+ // and is always valid, so kept >= 1 holds whenever V > 0.+ uint kept = 0;+ while (kept < topk_count+ && topk_idx[kept] < V+ && isfinite(topk_val[kept])) {+ kept += 1;+ }+ // mlx-lm applies Top-P before Top-K. The probabilities still carry+ // their full-vocabulary normalization here, so comparing the raw+ // descending cumulative mass to top_p produces the same intersection+ // without sorting the entire vocabulary. If Top-64 holds less than+ // top_p mass, all 64 survive and Top-K is the limiting filter.+ if (top_p > 0.0f && top_p < 1.0f) {+ float cum = 0.0f;+ uint cut = kept;+ for (uint i = 0; i < kept; ++i) {+ cum += topk_val[i];+ if (cum >= top_p) { cut = i + 1; break; }+ }+ kept = cut;+ }++ // MLX applies temperature in categorical_sampling after both filters.+ for (uint i = 0; i < kept; ++i) {+ if (temperature != 1.0f) {+ topk_val[i] = pow(topk_val[i], inv_temp);+ }+ }++ // Sum the reweighted surviving mass for inverse-CDF sampling.+ float surviving = 0.0f;+ for (uint i = 0; i < kept; ++i) surviving += topk_val[i];++ uint64_t rng = seed;+ // One xorshift step before sampling so identical seeds across calls+ // don't produce the same first draw when the seed is small (a few+ // bits short of full entropy on xorshift's first output).+ (void)xorshift64(rng);+ float u = uniform01(rng) * surviving;++ // Pick by walking the CDF until we cross u. With kept <= 256 this is+ // a tight loop and stays inside L1.+ // Default to slot 0 (the global argmax — always a valid index) so a+ // CDF that never crosses u (FP rounding leaves run slightly below the+ // surviving mass) still returns a real token, never a tail sentinel.+ float run = 0.0f;+ uint picked = topk_idx[0];+ for (uint i = 0; i < kept; ++i) {+ run += topk_val[i];+ if (u <= run) { picked = topk_idx[i]; break; }+ }++ chosen = picked;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (lid == 0) {+ out_token[0] = chosen;+ }+}++// Specialized Top-64 selection. Each stage reduces sorted+// 1,024-entry tiles to 64 pairs, so the full 262,144-entry vocabulary reaches+// one final tile in three dispatches without a full-vocabulary FP32 copy.+inline bool sample_topk64_better(float lhs_value, uint lhs_index,+ float rhs_value, uint rhs_index) {+ return lhs_value > rhs_value+ || (lhs_value == rhs_value && lhs_index < rhs_index);+}++inline void sample_topk64_sort_tile(threadgroup float* values,+ threadgroup uint* indices,+ uint lid) {+ for (uint width = 2; width <= 1024; width <<= 1) {+ for (uint stride = width >> 1; stride > 0; stride >>= 1) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ for (uint i = lid; i < 1024; i += 256) {+ uint partner = i ^ stride;+ if (partner <= i) continue;++ float lhs_value = values[i];+ uint lhs_index = indices[i];+ float rhs_value = values[partner];+ uint rhs_index = indices[partner];+ bool descending = (i & width) == 0;+ bool swap = descending+ ? sample_topk64_better(rhs_value, rhs_index,+ lhs_value, lhs_index)+ : sample_topk64_better(lhs_value, lhs_index,+ rhs_value, rhs_index);+ if (swap) {+ values[i] = rhs_value;+ indices[i] = rhs_index;+ values[partner] = lhs_value;+ indices[partner] = lhs_index;+ }+ }+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void sample_topk64_stage1(+ device const half* probs [[buffer(0)]],+ device float* out_values [[buffer(1)]],+ device uint* out_indices [[buffer(2)]],+ constant uint& V [[buffer(3)]],+ uint group [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]]) {+ threadgroup float values[1024];+ threadgroup uint indices[1024];+ uint base = group * 1024;++ for (uint i = lid; i < 1024; i += 256) {+ uint source = base + i;+ bool valid = source < V;+ values[i] = valid ? float(probs[source]) : -INFINITY;+ indices[i] = valid ? source : 0xFFFFFFFFu;+ }+ sample_topk64_sort_tile(values, indices, lid);++ if (lid < 64) {+ uint destination = group * 64 + lid;+ out_values[destination] = values[lid];+ out_indices[destination] = indices[lid];+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void sample_topk64_reduce(+ device const float* in_values [[buffer(0)]],+ device const uint* in_indices [[buffer(1)]],+ device float* out_values [[buffer(2)]],+ device uint* out_indices [[buffer(3)]],+ constant uint& count [[buffer(4)]],+ uint group [[threadgroup_position_in_grid]],+ uint lid [[thread_position_in_threadgroup]]) {+ threadgroup float values[1024];+ threadgroup uint indices[1024];+ uint base = group * 1024;++ for (uint i = lid; i < 1024; i += 256) {+ uint source = base + i;+ bool valid = source < count;+ values[i] = valid ? in_values[source] : -INFINITY;+ indices[i] = valid ? in_indices[source] : 0xFFFFFFFFu;+ }+ sample_topk64_sort_tile(values, indices, lid);++ if (lid < 64) {+ uint destination = group * 64 + lid;+ out_values[destination] = values[lid];+ out_indices[destination] = indices[lid];+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void sample_topk64_final(+ device const float* in_values [[buffer(0)]],+ device const uint* in_indices [[buffer(1)]],+ device uint* out_token [[buffer(2)]],+ constant uint& count [[buffer(3)]],+ constant float& temperature [[buffer(4)]],+ constant float& top_p [[buffer(5)]],+ constant uint64_t& seed [[buffer(6)]],+ uint lid [[thread_position_in_threadgroup]]) {+ threadgroup float values[1024];+ threadgroup uint indices[1024];++ for (uint i = lid; i < 1024; i += 256) {+ bool valid = i < count;+ values[i] = valid ? in_values[i] : -INFINITY;+ indices[i] = valid ? in_indices[i] : 0xFFFFFFFFu;+ }+ sample_topk64_sort_tile(values, indices, lid);++ if (lid == 0) {+ uint kept = 0;+ while (kept < 64+ && indices[kept] != 0xFFFFFFFFu+ && isfinite(values[kept])) {+ kept += 1;+ }++ if (top_p > 0.0f && top_p < 1.0f) {+ float cumulative = 0.0f;+ uint cut = kept;+ for (uint i = 0; i < kept; ++i) {+ cumulative += values[i];+ if (cumulative >= top_p) {+ cut = i + 1;+ break;+ }+ }+ kept = cut;+ }++ float inv_temperature = 1.0f / temperature;+ for (uint i = 0; i < kept; ++i) {+ if (temperature != 1.0f) {+ values[i] = pow(values[i], inv_temperature);+ }+ }++ float surviving = 0.0f;+ for (uint i = 0; i < kept; ++i) surviving += values[i];+ uint64_t rng = seed;+ (void)xorshift64(rng);+ float u = uniform01(rng) * surviving;+ float running = 0.0f;+ uint picked = indices[0];+ for (uint i = 0; i < kept; ++i) {+ running += values[i];+ if (u <= running) {+ picked = indices[i];+ break;+ }+ }+ out_token[0] = picked;+ }+}+++// Fused greedy lm-head path. Eight SIMD groups each evaluate one INT4 row;+// a second dispatch reduces the per-threadgroup argmax summaries.+constant constexpr uint kLMHeadRowsPerTG = 8;+constant constexpr uint kLMHeadGroupSize = 64;+constant constexpr uint kLMHeadRowSummaryStride = 2;+constant uint FC_HEAD_D [[function_constant(10)]];+constant uint FC_HEAD_V [[function_constant(11)]];+constant bool FC_HEAD_USE_FC [[function_constant(13)]];++static inline uint lmhead_fc_d(constant uint& D) {+ return (is_function_constant_defined(FC_HEAD_USE_FC) &&+ FC_HEAD_USE_FC &&+ is_function_constant_defined(FC_HEAD_D)) ? FC_HEAD_D : D;+}++static inline uint lmhead_fc_v(constant uint& V) {+ return (is_function_constant_defined(FC_HEAD_USE_FC) &&+ FC_HEAD_USE_FC &&+ is_function_constant_defined(FC_HEAD_V)) ? FC_HEAD_V : V;+}++inline float lmhead_int4_gemv_row_simd_dev(device const uint8_t* W,+ device const bfloat* scales,+ device const bfloat* biases,+ device const half* x,+ uint row,+ uint D,+ uint lane) {+ const uint n_groups = D / kLMHeadGroupSize;+ const uint row_bytes = D / 2u;+ device const uint8_t* W_row = W + uint(row) * row_bytes;+ device const bfloat* s_row = scales + uint(row) * n_groups;+ device const bfloat* b_row = biases + uint(row) * n_groups;++ float acc = 0.0f;+ const uint full_blocks = n_groups / 4u;+ for (uint blk = 0; blk < full_blocks; ++blk) {+ const uint byte_base = blk * 128u + lane * 4u;+ device const ushort* wp = (device const ushort*)(W_row + byte_base);+ const uint w4 = uint(wp[0]) | (uint(wp[1]) << 16);+ const uint g = blk * 4u + (lane >> 3);+ const float s = float(s_row[g]);+ const float b = float(b_row[g]);+ const uint elem = byte_base * 2u;+ const half4 xa = *((device const half4*)(x + elem));+ const half4 xb = *((device const half4*)(x + elem + 4u));+ const uint b0 = w4 & 0xFFu;+ const uint b1 = (w4 >> 8) & 0xFFu;+ const uint b2 = (w4 >> 16) & 0xFFu;+ const uint b3 = (w4 >> 24) & 0xFFu;+ const float e0 = float(xa.x), e1 = float(xa.y), e2 = float(xa.z), e3 = float(xa.w);+ const float e4 = float(xb.x), e5 = float(xb.y), e6 = float(xb.z), e7 = float(xb.w);+ float dot = 0.0f;+ dot = fma(float(b0 & 0x0Fu), e0, dot); dot = fma(float(b0 >> 4), e1, dot);+ dot = fma(float(b1 & 0x0Fu), e2, dot); dot = fma(float(b1 >> 4), e3, dot);+ dot = fma(float(b2 & 0x0Fu), e4, dot); dot = fma(float(b2 >> 4), e5, dot);+ dot = fma(float(b3 & 0x0Fu), e6, dot); dot = fma(float(b3 >> 4), e7, dot);+ const float sum = e0 + e1 + e2 + e3 + e4 + e5 + e6 + e7;+ acc = fma(s, dot, acc);+ acc = fma(b, sum, acc);+ }+ for (uint g = full_blocks * 4u; g < n_groups; ++g) {+ const float s = float(s_row[g]);+ const float b = float(b_row[g]);+ const uint8_t byte = W_row[g * (kLMHeadGroupSize / 2) + lane];+ const float x0 = float(x[g * kLMHeadGroupSize + lane * 2u]);+ const float x1 = float(x[g * kLMHeadGroupSize + lane * 2u + 1u]);+ float dot = fma(float(uint(byte & 0x0Fu)), x0, 0.0f);+ dot = fma(float(uint(byte >> 4)), x1, dot);+ const float sum = x0 + x1;+ acc = fma(s, dot, acc);+ acc = fma(b, sum, acc);+ }+ return simd_sum(acc);+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void lm_head_greedy_int4_rows_chunk_raw(+ device const half* x_normed [[buffer(0)]],+ device const uint8_t* W [[buffer(1)]],+ device const bfloat* scales [[buffer(2)]],+ device const bfloat* biases [[buffer(3)]],+ device float* summaries [[buffer(4)]],+ constant uint& D [[buffer(5)]],+ constant uint& V [[buffer(6)]],+ uint tg_idx [[threadgroup_position_in_grid]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float partial_v[kLogitMaxSimdGroups];+ threadgroup uint partial_i[kLogitMaxSimdGroups];+ const uint DD = lmhead_fc_d(D);+ const uint VV = lmhead_fc_v(V);++ const uint row = tg_idx * kLMHeadRowsPerTG + simd_group_id;+ float best_v = -INFINITY;+ uint best_i = 0xFFFFFFFFu;++ if (row < VV) {+ float z = lmhead_int4_gemv_row_simd_dev(W, scales, biases,+ x_normed, row, DD, simd_lane_id);+ if (simd_lane_id == 0 && isfinite(z)) {+ best_v = z;+ best_i = row;+ }+ }++ if (simd_lane_id == 0) {+ partial_v[simd_group_id] = best_v;+ partial_i[simd_group_id] = best_i;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ const bool active = simd_lane_id < simdgroups;+ const float v = active ? partial_v[simd_lane_id] : -INFINITY;+ const uint idx = active ? partial_i[simd_lane_id] : 0xFFFFFFFFu;+ const float v_all = simd_max(v);+ uint i_all = (v == v_all) ? idx : 0xFFFFFFFFu;+ i_all = simd_min(i_all);+ if (simd_lane_id == 0) {+ device float* slot = summaries + tg_idx * kLMHeadRowSummaryStride;+ slot[0] = v_all;+ slot[1] = as_type<float>(i_all);+ }+ }+}++[[kernel, max_total_threads_per_threadgroup(256)]]+void lm_head_greedy_int4_rows_reduce(+ device const float* summaries [[buffer(0)]],+ device uint* out_token [[buffer(1)]],+ constant uint& row_groups [[buffer(2)]],+ uint lid [[thread_position_in_threadgroup]],+ uint lsize [[threads_per_threadgroup]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint simdgroups [[simdgroups_per_threadgroup]]+) {+ threadgroup float partial_v[kLogitMaxSimdGroups];+ threadgroup uint partial_i[kLogitMaxSimdGroups];++ float best_v = -INFINITY;+ uint best_i = 0xFFFFFFFFu;+ for (uint i = lid; i < row_groups; i += lsize) {+ device const float* slot = summaries + i * kLMHeadRowSummaryStride;+ const float v = slot[0];+ const uint idx = as_type<uint>(slot[1]);+ if (v > best_v || (v == best_v && idx < best_i)) {+ best_v = v;+ best_i = idx;+ }+ }++ float v_simd = simd_max(best_v);+ uint i_simd = (best_v == v_simd) ? best_i : 0xFFFFFFFFu;+ i_simd = simd_min(i_simd);++ if (simd_lane_id == 0) {+ partial_v[simd_group_id] = v_simd;+ partial_i[simd_group_id] = i_simd;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ if (simd_group_id == 0) {+ const bool active = simd_lane_id < simdgroups;+ const float v = active ? partial_v[simd_lane_id] : -INFINITY;+ const uint idx = active ? partial_i[simd_lane_id] : 0xFFFFFFFFu;+ const float v_all = simd_max(v);+ uint i_all = (v == v_all) ? idx : 0xFFFFFFFFu;+ i_all = simd_min(i_all);+ if (simd_lane_id == 0) {+ out_token[0] = (i_all == 0xFFFFFFFFu) ? 0u : i_all;+ }+ }+}diff --git a/Sources/TurboFieldfare/Metal/TensorCore/tensorops.metal b/Sources/TurboFieldfare/Metal/TensorCore/tensorops.metalnew file mode 100644index 00000000..aea257a1--- /dev/null+++ b/Sources/TurboFieldfare/Metal/TensorCore/tensorops.metal@@ -0,0 +1,107 @@+#include <metal_stdlib>+using namespace metal;++#if defined(__HAVE_TENSOR__)+#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>+using namespace mpp::tensor_ops;++constant constexpr uint kW4A8GroupSize = 64;+constant constexpr int kMPPAffineTileM = 64;+constant constexpr int kMPPAffineTileN = 32;+constant constexpr int kMPPAffineTileK = 64;++kernel void mpp_prefill_affine_threadgroup_f16(+ device const uint8_t* packedWeights [[buffer(0)]],+ device const bfloat* scales [[buffer(1)]],+ device const bfloat* biases [[buffer(2)]],+ device half* activations [[buffer(3)]],+ device half* output [[buffer(4)]],+ constant uint& M [[buffer(5)]],+ constant uint& N [[buffer(6)]],+ constant uint& K [[buffer(7)]],+ uint3 tgid [[threadgroup_position_in_grid]],+ uint3 lid3 [[thread_position_in_threadgroup]],+ uint3 threads3 [[threads_per_threadgroup]]) {+ constexpr auto descriptor = matmul2d_descriptor(+ kMPPAffineTileM, kMPPAffineTileN, kMPPAffineTileK,+ false, true, false);+ matmul2d<descriptor, execution_simdgroups<4>> operation;++ using device_half_tensor = tensor<device half, dextents<int32_t, 2>, tensor_inline>;+ using threadgroup_half_tensor = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>;++ threadgroup half weightTile[kMPPAffineTileN * kMPPAffineTileK];+ threadgroup_half_tensor tileB(+ weightTile,+ dextents<int32_t, 2>(kMPPAffineTileK, kMPPAffineTileN),+ array<int32_t, 2>({1, kMPPAffineTileK}));+ device_half_tensor firstA(+ activations,+ dextents<int32_t, 2>(kMPPAffineTileK, M),+ array<int32_t, 2>({1, int32_t(K)}));+ auto firstTileA = firstA.slice(+ 0,+ int32_t(tgid.y) * kMPPAffineTileM);+ auto accumulator = operation.get_destination_cooperative_tensor<+ decltype(firstTileA), decltype(tileB), float>();+ auto groupProduct = operation.get_destination_cooperative_tensor<+ decltype(firstTileA), decltype(tileB), float>();+ for (int element = 0; element < accumulator.get_capacity(); ++element) {+ accumulator[element] = 0.0f;+ }++ const uint rowBytes = K / 2u;+ const uint groupsPerRow = K / kW4A8GroupSize;+ const uint lid = lid3.x;+ const uint threads = threads3.x;+ for (uint group = 0; group < groupsPerRow; ++group) {+ for (int element = 0; element < groupProduct.get_capacity(); ++element) {+ groupProduct[element] = 0.0f;+ }+ for (uint linear = lid;+ linear < uint(kMPPAffineTileN * kMPPAffineTileK);+ linear += threads) {+ const uint localN = linear / uint(kMPPAffineTileK);+ const uint localK = linear % uint(kMPPAffineTileK);+ const uint globalN = tgid.x * uint(kMPPAffineTileN) + localN;+ if (globalN < N) {+ const uint globalK = group * uint(kMPPAffineTileK) + localK;+ const uint8_t packed = packedWeights[globalN * rowBytes + (globalK >> 1)];+ const uint q = (globalK & 1u) == 0u+ ? uint(packed & 0x0fu)+ : uint(packed >> 4);+ const float scale = float(scales[globalN * groupsPerRow + group]);+ const float bias = float(biases[globalN * groupsPerRow + group]);+ weightTile[linear] = half(fma(float(q), scale, bias));+ } else {+ weightTile[linear] = half(0.0f);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ device_half_tensor groupA(+ activations + group * uint(kMPPAffineTileK),+ dextents<int32_t, 2>(kMPPAffineTileK, M),+ array<int32_t, 2>({1, int32_t(K)}));+ auto tileA = groupA.slice(+ 0,+ int32_t(tgid.y) * kMPPAffineTileM);+ operation.run(tileA, tileB, groupProduct);+ for (int element = 0; element < accumulator.get_capacity(); ++element) {+ accumulator[element] += groupProduct[element];+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }++ for (int element = 0; element < accumulator.get_capacity(); ++element) {+ if (!accumulator.is_valid_element(element)) continue;+ const auto position = accumulator.get_multidimensional_index(element);+ const uint globalN = tgid.x * uint(kMPPAffineTileN) + uint(position[0]);+ const uint globalM = tgid.y * uint(kMPPAffineTileM) + uint(position[1]);+ if (globalM < M && globalN < N) {+ output[globalM * N + globalN] = half(accumulator[element]);+ }+ }+}++#endifdiff --git a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swiftnew file mode 100644index 00000000..99d7e22b--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift@@ -0,0 +1,71 @@+public enum RuntimeKVStorage: String, Codable, Sendable {+ case fp16+ case packedK4V4 = "packed-k4v4"+}++public enum RuntimeHeadPath: String, Codable, Sendable {+ case fusedRows = "fused-rows"+ case logits+}++public enum RuntimePrefillPolicy: String, Codable, Sendable {+ case off+ case chunked+}++public enum RuntimeExpertCachePolicy: String, Codable, Sendable {+ case lfu+ case lru+}++public struct RuntimeConfiguration: Sendable, Equatable {+ public static let allowedExpertCacheSlots = [8, 16, 24, 32]+ public static let allowedPrefillChunkTokens = [32, 64, 128]++ public let kvStorage: RuntimeKVStorage+ public let expertCacheSlots: Int+ public let expertCachePolicy: RuntimeExpertCachePolicy+ public let rdadvisePolicy: RDAdvicePolicyMode+ public let prefillPolicy: RuntimePrefillPolicy+ public let prefillChunkTokens: Int+ public let headPath: RuntimeHeadPath++ public init(expertCacheSlots: Int = 16,+ expertCachePolicy: RuntimeExpertCachePolicy = .lfu,+ rdadvisePolicy: RDAdvicePolicyMode = .off,+ prefillEnabled: Bool = true,+ prefillChunkTokens: Int = 128,+ turboQuantKVEnabled: Bool = false,+ forceLogitsHead: Bool = false) {+ precondition(Self.allowedExpertCacheSlots.contains(expertCacheSlots),+ "unsupported expert-cache slot count")+ precondition(Self.allowedPrefillChunkTokens.contains(prefillChunkTokens),+ "unsupported prefill chunk size")+ self.kvStorage = turboQuantKVEnabled ? .packedK4V4 : .fp16+ self.expertCacheSlots = expertCacheSlots+ self.expertCachePolicy = expertCachePolicy+ self.rdadvisePolicy = rdadvisePolicy+ self.prefillPolicy = prefillEnabled ? .chunked : .off+ self.prefillChunkTokens = prefillChunkTokens+ self.headPath = forceLogitsHead ? .logits : .fusedRows+ }++ public static var production: RuntimeConfiguration {+ RuntimeConfiguration()+ }++ public var fp16RingEnabled: Bool { kvStorage == .fp16 }+ public var rdadviseEnabled: Bool { rdadvisePolicy != .off }+ public var prefillConfig: PrefillRuntimeConfig {+ switch prefillPolicy {+ case .off:+ return .off+ case .chunked:+ return .production(chunkTokens: prefillChunkTokens)+ }+ }+ public var turboQuantKVEnabled: Bool { kvStorage == .packedK4V4 }+ public var modelExpertCachePolicy: ExpertCachePolicy {+ expertCachePolicy == .lru ? .lru : .lfu+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Generation/Generator.swift b/Sources/TurboFieldfare/Runtime/Generation/Generator.swiftnew file mode 100644index 00000000..d5e16e22--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Generation/Generator.swift@@ -0,0 +1,25 @@+import Foundation++public enum StopReason: Sendable, Equatable {+ case eos+ case endOfTurn+ case maxTokens+ case stopString+}++enum GeneratorError: Error, CustomStringConvertible, Equatable {+ case contextOverflow(prompt: Int, maxNew: Int, maxContext: Int)+ case invalidGenerationConfig(String)+ case emptyPrompt++ public var description: String {+ switch self {+ case .contextOverflow(let prompt, let maxNew, let maxContext):+ return "context overflow: prompt \(prompt) + maxNew \(maxNew) exceeds maxContext \(maxContext)"+ case .invalidGenerationConfig(let reason):+ return reason+ case .emptyPrompt:+ return "empty prompt"+ }+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift b/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swiftnew file mode 100644index 00000000..a36d91fd--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift@@ -0,0 +1,45 @@+import Metal++/// Produces next-token logits for the `Generator`. The production+/// implementation is `RealForwardRunner`; tests use scripted logits so decode+/// behavior stays independent of the kernel stack.+public protocol LogitProducer: AnyObject, Sendable {+ /// Clear any per-generation state, such as KV cache.+ func reset()+ /// Run one token at `position`, leaving FP16 logits in `logits`.+ func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws+}++protocol ContextWindowReporting: Sendable {+ var maxContext: Int { get }+}++public enum PrefillOutputMode: Sendable, Equatable {+ case logits+ case greedyIfAvailable+}++public enum PrefillSeed: Sendable, Equatable {+ case logitsWritten+ case greedyToken(UInt32)+}++public struct PrefillResult: Sendable, Equatable {+ public let newPosition: Int+ public let seed: PrefillSeed++ public init(newPosition: Int, seed: PrefillSeed) {+ self.newPosition = newPosition+ self.seed = seed+ }+}++protocol ChunkedPrefillRunner: LogitProducer {+ /// Prefill a prompt slice using the chunked production runtime.+ func prefillChunked(tokens: ArraySlice<Int32>,+ startPosition: Int,+ outputMode: PrefillOutputMode,+ config: PrefillRuntimeConfig,+ into logits: MTLBuffer,+ onProgress: (Int) -> Void) async throws -> PrefillResult+}diff --git a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swiftnew file mode 100644index 00000000..74745a53--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift@@ -0,0 +1,205 @@+import Foundation+import Metal++/// Streaming callbacks from `runRawCompletion`. `.prefill` reports monotonic+/// producer-defined prompt progress; scalar replay reports per token, while a+/// prefill-capable producer may report per internal chunk. `.token` fires per+/// decoded non-stop token; `.tail` carries the detokenizer flush remainder at a+/// stop boundary.+public enum RawDecodeProgress: Sendable {+ case prefill(done: Int, total: Int)+ case token(index: Int, id: Int32, delta: String)+ case tail(String)+}++public struct RawDecodeResult: Sendable {+ public let prefillTokens: Int+ public let prefillSeconds: Double+ public let newTokens: Int+ public let decodeSeconds: Double+ public let reason: StopReason+}++/// Preallocated per-generation buffers (two 512 KiB vocab buffers plus a token+/// slot) and sampler. A warm session reuses them for every token, avoiding+/// per-token Metal buffer allocation.+///+/// `@unchecked Sendable`: the buffers and sampler are exclusively owned by one+/// generation at a time — the single-in-flight guard upstream is the contract.+public struct RawCompletionScratch: @unchecked Sendable {+ let logits: MTLBuffer+ let probs: MTLBuffer+ let outToken: MTLBuffer+ let sampler: Sampler++ public init(context: MetalContext, vocab: Int) throws {+ guard let logits = context.device.makeBuffer(length: vocab * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let probs = context.device.makeBuffer(length: vocab * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let outToken = context.device.makeBuffer(length: MemoryLayout<UInt32>.size,+ options: .storageModeShared)+ else {+ throw ModelError.residentBufferWrapFailed+ }+ self.logits = logits+ self.probs = probs+ self.outToken = outToken+ self.sampler = try Sampler(context: context, vocab: vocab)+ }+}++extension GenerationConfig {+ /// A pure-greedy config can use the fused head's GPU argmax+ /// (`RealForwardRunner.lastGreedyToken`) instead of sampling from the+ /// logits buffer. Anything else needs real logits.+ public var isPureGreedy: Bool {+ temperature == 0 && repetitionPenalty == 1+ }++}++/// Raw-completion prefill + decode loop shared by the CLI and the Mac app.+/// Consumes pre-encoded `promptIds` (BOS + verbatim encode upstream — no chat+/// template). Stop handling, detokenizer flush ordering, and history append+/// ordering are shared by both front ends.+///+/// When the producer runs the fused lm_head (`RealForwardRunner` default) the+/// logits buffer is never written; the loop then requires a pure-greedy config+/// and reads `lastGreedyToken`. Callers with sampling configs must construct+/// the runner with `forceLogitsHead: true`.+public func runRawCompletion(producer: any LogitProducer,+ tokenizer: GFTokenizer,+ promptIds: [Int32],+ config: GenerationConfig,+ context: MetalContext,+ scratch: RawCompletionScratch,+ prefillConfig: PrefillRuntimeConfig = .defaultChunked,+ onProgress: (RawDecodeProgress) -> Void) async throws -> RawDecodeResult {+ try config.validate()+ guard !promptIds.isEmpty else {+ throw GeneratorError.emptyPrompt+ }+ let fusedRunner = producer as? RealForwardRunner+ let fusedGreedy = fusedRunner?.usesFusedGreedyHead == true+ guard !fusedGreedy || config.isPureGreedy else {+ throw PrefillError.unsupportedPrefillSeed(+ "the fused-head producer cannot serve this sampling configuration; use a logits head")+ }++ var detok = GFDetokenizer(tokenizer: tokenizer)+ var history: [Int32] = []+ history.reserveCapacity(promptIds.count + config.maxNewTokens)++ if let context = producer as? any ContextWindowReporting,+ promptIds.count + config.maxNewTokens > context.maxContext {+ throw GeneratorError.contextOverflow(prompt: promptIds.count,+ maxNew: config.maxNewTokens,+ maxContext: context.maxContext)+ }+ producer.reset()+ let prefillStart = Date()+ var position = 0+ var prefillSeed: PrefillSeed?+ switch prefillConfig.mode {+ case .chunked where producer is any ChunkedPrefillRunner:+ let chunked = producer as! any ChunkedPrefillRunner+ let mode: PrefillOutputMode = fusedGreedy ? .greedyIfAvailable : .logits+ let result = try await chunked.prefillChunked(tokens: promptIds[...],+ startPosition: position,+ outputMode: mode,+ config: prefillConfig,+ into: scratch.logits) { done in+ onProgress(.prefill(done: done, total: promptIds.count))+ }+ if mode == .logits, result.seed != .logitsWritten {+ throw PrefillError.unsupportedPrefillSeed(+ "RawCompletion chunked prefill requested logits but producer returned \(result.seed)")+ }+ if case .greedyToken = result.seed, !config.isPureGreedy {+ throw PrefillError.unsupportedPrefillSeed(+ "RawCompletion chunked prefill returned a greedy token for a sampling config")+ }+ position = result.newPosition+ prefillSeed = result.seed+ history.append(contentsOf: promptIds)+ case .chunked:+ throw PrefillError.chunkedUnsupported(+ PrefillError.chunkedRequiresChunkedRunnerReason)+ case .off:+ for t in promptIds {+ try Task.checkCancellation()+ try await producer.produce(token: t, position: position, into: scratch.logits)+ position += 1+ history.append(t)+ onProgress(.prefill(done: position, total: promptIds.count))+ }+ }++ let decodeStart = Date()+ let prefillSeconds = decodeStart.timeIntervalSince(prefillStart)+ var accumulated = ""+ var generated = 0+ var reason: StopReason = .maxTokens++ while true {+ try Task.checkCancellation()++ let tokenID: Int32+ if generated == 0, let seed = prefillSeed {+ switch seed {+ case .greedyToken(let token):+ tokenID = Int32(bitPattern: token)+ case .logitsWritten:+ tokenID = sampleOnce(scratch: scratch, context: context,+ history: history, config: config, position: generated)+ }+ } else if fusedGreedy {+ tokenID = Int32(bitPattern: fusedRunner!.lastGreedyToken)+ } else {+ tokenID = sampleOnce(scratch: scratch, context: context,+ history: history, config: config, position: generated)+ }+ generated += 1++ if tokenizer.stopTokenIDs.contains(tokenID) || config.extraStopTokens.contains(tokenID) {+ reason = tokenID == tokenizer.endOfTurnID ? .endOfTurn : .eos+ let tail = detok.flush()+ if !tail.isEmpty { onProgress(.tail(tail)) }+ break+ }++ let delta = detok.push(tokenID)+ onProgress(.token(index: generated - 1, id: tokenID, delta: delta))+ accumulated += delta++ let hitStopString = config.stopStrings.contains { !$0.isEmpty && accumulated.contains($0) }+ let hitMax = generated >= config.maxNewTokens+ if hitStopString || hitMax {+ let tail = detok.flush()+ if !tail.isEmpty { onProgress(.tail(tail)) }+ reason = hitStopString ? .stopString : .maxTokens+ break+ }++ history.append(tokenID)+ try await producer.produce(token: tokenID, position: position, into: scratch.logits)+ position += 1+ }++ return RawDecodeResult(prefillTokens: promptIds.count,+ prefillSeconds: prefillSeconds,+ newTokens: generated,+ decodeSeconds: Date().timeIntervalSince(decodeStart),+ reason: reason)+}++private func sampleOnce(scratch: RawCompletionScratch, context: MetalContext,+ history: [Int32], config: GenerationConfig, position: Int) -> Int32 {+ let cb = context.queue.makeCommandBuffer()!+ scratch.sampler.sample(commandBuffer: cb, logits: scratch.logits, probs: scratch.probs,+ history: history, config: config, position: position,+ outToken: scratch.outToken)+ cb.commit(); cb.waitUntilCompleted()+ return Int32(bitPattern: scratch.outToken.contents().load(as: UInt32.self))+}diff --git a/Sources/TurboFieldfare/Runtime/Generation/Sampler.swift b/Sources/TurboFieldfare/Runtime/Generation/Sampler.swiftnew file mode 100644index 00000000..16d7b53a--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Generation/Sampler.swift@@ -0,0 +1,216 @@+import Foundation+import Metal++/// Generation knobs threaded from the caller through the `Generator` into the+/// sampler. Pure value type; one per `generate(...)` call.+///+/// Canonical home is here (the sampler is the primary consumer); `Generator`+/// reuses the same type rather than redeclaring it.+public struct GenerationConfig: Sendable {+ public var maxNewTokens: Int = 256+ public var temperature: Float = 1.0+ public var topK: Int? = nil // nil = no truncation+ public var topP: Float? = nil // nil = no nucleus truncation+ public var repetitionPenalty: Float = 1.0+ public var seed: UInt64? = nil // nil = nondeterministic+ public var stopStrings: [String] = []+ public var extraStopTokens: Set<Int32> = []++ public init(maxNewTokens: Int = 256,+ temperature: Float = 1.0,+ topK: Int? = nil,+ topP: Float? = nil,+ repetitionPenalty: Float = 1.0,+ seed: UInt64? = nil,+ stopStrings: [String] = [],+ extraStopTokens: Set<Int32> = []) {+ self.maxNewTokens = maxNewTokens+ self.temperature = temperature+ self.topK = topK+ self.topP = topP+ self.repetitionPenalty = repetitionPenalty+ self.seed = seed+ self.stopStrings = stopStrings+ self.extraStopTokens = extraStopTokens+ }++ public func validate() throws {+ guard maxNewTokens > 0 else {+ throw GeneratorError.invalidGenerationConfig(+ "maxNewTokens must be greater than zero")+ }+ guard temperature.isFinite, temperature >= 0 else {+ throw GeneratorError.invalidGenerationConfig(+ "temperature must be finite and nonnegative")+ }+ if let topK, !(1...256).contains(topK) {+ throw GeneratorError.invalidGenerationConfig(+ "topK must be between 1 and 256")+ }+ if let topP, (!topP.isFinite || topP <= 0 || topP > 1) {+ throw GeneratorError.invalidGenerationConfig(+ "topP must be greater than zero and at most one")+ }+ if temperature > 0, topK == nil, let topP, topP < 1 {+ throw GeneratorError.invalidGenerationConfig(+ "topP below one requires topK; full-vocabulary nucleus sampling is not implemented")+ }+ }++}++/// Which path a `sample(...)` call took.+enum SamplePath: Sendable, Equatable {+ case greedyGPU+ case gpuSampled+ case hostPenalty+}++/// Turns `GenerationConfig` + a logits buffer into one token id, staying+/// GPU-resident wherever the kernels allow.+///+/// The built `sample` kernel already does temperature / top-k / top-p / seeded+/// draw / greedy argmax on GPU reading softmaxed probs, so this type's job is:+/// (1) run the softcap+softmax front-end (`logit_softcap_softmax`), (2) apply+/// repetition penalty — the one policy that needs `history` random access — as+/// a single in-place CPU pass over the (shared) logits before the front-end,+/// and (3) derive a per-position seed so a fixed `seed` is reproducible across+/// token positions.+///+/// The chosen id lands in a 1-element UInt32 buffer. The generation loop reads+/// that value after the command buffer completes.+///+/// Truncation follows mlx-lm's sampler order: Top-P is computed from the+/// model's full probability distribution, Top-K caps that surviving set, and+/// temperature is applied only to the final categorical draw.+final class Sampler {+ private let softcap: LogitSoftcapSoftmax+ private let sampleKernel: Sample+ private let topK64Kernel: SampleTopK64+ let vocab: Int+ private let logitSoftcap: Float++ init(context: MetalContext, vocab: Int = 262_144,+ logitSoftcap: Float = 30.0) throws {+ self.softcap = try LogitSoftcapSoftmax(context: context)+ self.sampleKernel = try Sample(context: context)+ self.topK64Kernel = try SampleTopK64(context: context, vocab: vocab)+ self.vocab = vocab+ self.logitSoftcap = logitSoftcap+ }++ /// Encode the sampler onto `commandBuffer`. `logits` is FP16 [vocab],+ /// post-lm_head and pre-softcap, in a `.storageModeShared` buffer (the+ /// repetition-penalty path edits it in place). `probs` is a preallocated+ /// FP16 [vocab] scratch. `outToken` holds one UInt32. `position` indexes the+ /// per-position seed advance. Returns the path taken.+ @discardableResult+ func sample(commandBuffer: MTLCommandBuffer,+ logits: MTLBuffer,+ probs: MTLBuffer,+ history: [Int32],+ config: GenerationConfig,+ position: Int,+ outToken: MTLBuffer) -> SamplePath {+ let v = UInt32(vocab)++ let appliedPenalty = config.repetitionPenalty != 1.0 && !history.isEmpty+ if appliedPenalty {+ applyRepetitionPenaltyInPlace(logits: logits,+ history: history,+ penalty: config.repetitionPenalty)+ }++ softcap.encode(commandBuffer: commandBuffer,+ logits: logits, probs: probs, v: v, softcap: logitSoftcap)++ let isGreedy = config.temperature == 0+ let seed = Self.seedFor(config: config, position: position)+ if config.temperature > 0,+ config.topK == 64 {+ topK64Kernel.encode(commandBuffer: commandBuffer,+ probs: probs,+ outToken: outToken,+ temperature: config.temperature,+ topP: config.topP ?? 1.0,+ seed: seed)+ } else {+ sampleKernel.encode(commandBuffer: commandBuffer,+ probs: probs, outToken: outToken, v: v,+ temperature: isGreedy ? 0.0 : config.temperature,+ topK: UInt32(config.topK ?? 0),+ topP: config.topP ?? 1.0,+ seed: seed,+ position: UInt32(position))+ }++ if appliedPenalty { return .hostPenalty }+ return isGreedy ? .greedyGPU : .gpuSampled+ }++ // MARK: - Repetition penalty (host, in place)++ /// HF convention: for each token id seen in `history`, a positive logit is+ /// divided by `penalty`, a negative logit multiplied. Edits the shared+ /// `logits` buffer in place — no full-buffer copy, only the unique history+ /// entries are touched (counted for the audit).+ ///+ /// The penalty must act on the POST-softcap logit (HF applies it to the+ /// model's output logits, and Gemma's output includes the 30*tanh(z/30)+ /// cap). Real Gemma 4 raw logits reach the hundreds, deep in tanh+ /// saturation, where dividing the raw value by 1.1 moves the capped logit+ /// by ~nothing — the penalty silently no-ops on exactly the+ /// high-confidence tokens that form repetition loops. So: softcap the raw+ /// value, penalize, and invert through atanh so the downstream+ /// softcap+softmax kernel reproduces the penalized capped logit.+ private func applyRepetitionPenaltyInPlace(logits: MTLBuffer,+ history: [Int32],+ penalty: Float) {+ let ptr = logits.contents().bindMemory(to: Float16.self, capacity: vocab)+ var seen = Set<Int32>()+ seen.reserveCapacity(history.count)+ for id in history {+ guard id >= 0 && Int(id) < vocab, seen.insert(id).inserted else { continue }+ let i = Int(id)+ let z = Float(ptr[i])+ let penalized: Float+ if logitSoftcap > 0 {+ let capped = logitSoftcap * tanhf(z / logitSoftcap)+ let cappedPenalized = capped > 0 ? capped / penalty : capped * penalty+ // A saturated negative logit times the penalty can leave the+ // softcap's open interval; clamp inside it so atanh stays+ // finite.+ let limit = logitSoftcap * 0.9999+ let clamped = max(min(cappedPenalized, limit), -limit)+ penalized = logitSoftcap * atanhf(clamped / logitSoftcap)+ } else {+ penalized = z > 0 ? z / penalty : z * penalty+ }+ ptr[i] = Float16(penalized)+ }+ }++ // MARK: - Seed++ /// Deterministic per-position seed when `config.seed != nil` so a fixed seed+ /// reproduces across token positions; clock-derived (non-zero) otherwise.+ /// xorshift64 in the kernel has a fixed point at 0, so we never emit 0.+ static func seedFor(config: GenerationConfig, position: Int) -> UInt64 {+ if let s = config.seed {+ let mixed = Self.splitmix64(s &+ UInt64(bitPattern: Int64(position)))+ return mixed == 0 ? 0x9E3779B97F4A7C15 : mixed+ }+ var t = timespec()+ clock_gettime(CLOCK_MONOTONIC, &t)+ let raw = UInt64(bitPattern: Int64(t.tv_nsec)) &* 0x9E3779B97F4A7C15+ &+ UInt64(bitPattern: Int64(t.tv_sec))+ return raw == 0 ? 0x9E3779B97F4A7C15 : raw+ }++ private static func splitmix64(_ x: UInt64) -> UInt64 {+ var z = x &+ 0x9E3779B97F4A7C15+ z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9+ z = (z ^ (z >> 27)) &* 0x94D049BB133111EB+ return z ^ (z >> 31)+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Inference/Model.swift b/Sources/TurboFieldfare/Runtime/Inference/Model.swiftnew file mode 100644index 00000000..7cf217a1--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Inference/Model.swift@@ -0,0 +1,494 @@+import Foundation+import Metal+import Darwin++public struct ModelLoadStats: Sendable {+ public var manifestSha256Nanos: UInt64+ public var receiptValidationNanos: UInt64+ public var eagerSha256Nanos: UInt64++ public init(manifestSha256Nanos: UInt64 = 0,+ receiptValidationNanos: UInt64 = 0,+ eagerSha256Nanos: UInt64 = 0) {+ self.manifestSha256Nanos = manifestSha256Nanos+ self.receiptValidationNanos = receiptValidationNanos+ self.eagerSha256Nanos = eagerSha256Nanos+ }+}++/// Bounded routed-expert cache configuration.+public enum ExpertStreamingMode: Sendable {+ /// Read each expert into one of `slotCount` 2 MB-aligned cache slots.+ case pread(slotCount: Int)+}++/// Loaded `.gturbo/` model. Resident weights live behind one mmap'd+/// `MTLBuffer`; routed expert weights live behind per-layer streaming+/// backends opened lazily on first touch.+public struct Model {+ public let device: MTLDevice+ public let config: ArchConfig+ public let streamingMode: ExpertStreamingMode+ public let expertCachePolicy: ExpertCachePolicy+ public let integrityPolicy: ModelIntegrityPolicy++ let residentBuffer: ResidentBuffer+ let residentIndex: ResidentIndex+ let packedExpertsLayout: PackedExpertsLayout+ let manifest: Manifest+ let directoryURL: URL++ /// Lazy state. Held inside a reference box so `Model` can stay a struct+ /// while still letting accessors mutate layer state via a serial queue.+ let streamersBox: StreamersBox+ let streamersQueue: DispatchQueue++ final class StreamersBox: @unchecked Sendable {+ var streamers: [PreadExpertStreamer?]+ var layerVerified: [Bool]+ init(numLayers: Int) {+ self.streamers = Array(repeating: nil, count: numLayers)+ self.layerVerified = Array(repeating: false, count: numLayers)+ }+ }++ init(device: MTLDevice,+ config: ArchConfig,+ streamingMode: ExpertStreamingMode,+ expertCachePolicy: ExpertCachePolicy,+ integrityPolicy: ModelIntegrityPolicy,+ residentBuffer: ResidentBuffer,+ residentIndex: ResidentIndex,+ packedExpertsLayout: PackedExpertsLayout,+ manifest: Manifest,+ directoryURL: URL) {+ self.device = device+ self.config = config+ self.streamingMode = streamingMode+ self.expertCachePolicy = expertCachePolicy+ self.integrityPolicy = integrityPolicy+ self.residentBuffer = residentBuffer+ self.residentIndex = residentIndex+ self.packedExpertsLayout = packedExpertsLayout+ self.manifest = manifest+ self.directoryURL = directoryURL+ self.streamersBox = StreamersBox(numLayers: packedExpertsLayout.numLayers)+ self.streamersQueue = DispatchQueue(label: "turbo-fieldfare.expert-streamers")+ }++ // MARK: - Resident accessors++ public var embedding: TensorView {+ try! resident(name: "language_model.model.embed_tokens.weight")+ }++ /// Gemma 4 ties lm_head to the embedding. The transpose for the lm_head+ /// GEMV path is the kernel's job, not the loader's.+ public var lmHead: TensorView { embedding }++ public func qProj(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).self_attn.q_proj.weight")+ }+ public func kProj(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).self_attn.k_proj.weight")+ }+ public func vProj(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).self_attn.v_proj.weight")+ }+ public func oProj(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).self_attn.o_proj.weight")+ }+ /// Writer emits `.router.proj.weight` (no `.mlp.` segment).+ public func router(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).router.proj.weight")+ }+ /// Writer emits the shared-expert FFN as `.mlp.{gate,up,down}_proj.weight`+ /// without a `.shared_expert.` segment.+ public func sharedExpertGate(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).mlp.gate_proj.weight")+ }+ public func sharedExpertUp(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).mlp.up_proj.weight")+ }+ public func sharedExpertDown(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).mlp.down_proj.weight")+ }+ public func inputNorm(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).input_layernorm.weight")+ }+ public func postAttnNorm(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).post_attention_layernorm.weight")+ }+ public var finalNorm: TensorView {+ try! resident(name: "language_model.model.norm.weight")+ }++ // MARK: - Per-head attention norms (Q/K only)+ //+ // `q_norm` and `k_norm` are RMSNorm with learnable scale, applied per head+ // before RoPE. `v_norm` has **no learnable weight** (no-scale RMSNorm) and+ // is therefore not stored as a tensor — the runtime uses an+ // explicit no-scale variant rather than consuming a unit-weight buffer.++ public func qNorm(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).self_attn.q_norm.weight")+ }+ public func kNorm(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).self_attn.k_norm.weight")+ }++ // MARK: - Feed-forward norms+ //+ // The Gemma 4 sandwich wraps two parallel FFN branches:+ // pre_feedforward_layernorm -> dense MLP input+ // pre_feedforward_layernorm_2 -> routed expert input+ // post_feedforward_layernorm_1 -> dense MLP output+ // post_feedforward_layernorm_2 -> routed expert output+ // post_feedforward_layernorm -> combined (h1+h2) output++ public func preFFN(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).pre_feedforward_layernorm.weight")+ }+ public func preFFN2(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).pre_feedforward_layernorm_2.weight")+ }+ public func postFFN1(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).post_feedforward_layernorm_1.weight")+ }+ public func postFFN2(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).post_feedforward_layernorm_2.weight")+ }+ public func postFFN(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).post_feedforward_layernorm.weight")+ }++ // MARK: - Router auxiliaries+ //+ // `router.scale` is a per-feature multiplier on the router's input+ // (post-RMSNorm), fused with 1/sqrt(hidden_size). `per_expert_scale` is+ // applied to the top-k routing weights after softmax over top-k.++ public func routerScale(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).router.scale")+ }+ public func routerPerExpertScale(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).router.per_expert_scale")+ }++ /// Per-layer scalar gain applied to the entire residual stream at the end+ /// of the layer; shape `[1]`, BF16.+ public func layerScalar(layer L: Int) throws -> TensorView {+ try resident(name: "language_model.model.layers.\(L).layer_scalar")+ }++ /// Resolve a tensor name to a `TensorView` against the resident buffer.+ /// `fileOffset` (absolute) is converted to a buffer-relative offset by+ /// subtracting the resident region's file offset (which equals+ /// `header.indexSize`).+ func resident(name: String) throws -> TensorView {+ guard let entry = residentIndex.entries[name] else {+ throw ModelError.tensorNotFound(name: name)+ }+ let residentFileOffset = residentIndex.header.indexSize+ let relativeOffset = entry.fileOffset - residentFileOffset+ let scaleRel: UInt64 = entry.scaleSize > 0+ ? entry.scaleOffset - residentFileOffset : 0+ let biasRel: UInt64 = entry.biasSize > 0+ ? entry.biasOffset - residentFileOffset : 0+ return TensorView(+ buffer: residentBuffer.buffer,+ offset: relativeOffset,+ length: entry.sizeBytes,+ scaleOffset: scaleRel, scaleLength: entry.scaleSize,+ biasOffset: biasRel, biasLength: entry.biasSize,+ shape: entry.shape,+ dtype: entry.dtype)+ }++ // MARK: - Routed expert (lazy)++ /// First touch of layer L opens its backend + verifies SHA-256; subsequent+ /// touches reuse the open backend. The backend resolves the expert to an+ /// cache-slot `(MTLBuffer, offset)` pair.+ public func routedExpert(layer L: Int, expert E: Int) throws -> TensorView {+ try ensureLayerOpened(L)+ let backend = streamersQueue.sync { streamersBox.streamers[L]! }+ let r = try backend.loadExpert(layer: 0, expert: E)+ return TensorView(+ buffer: r.buffer,+ offset: r.offset,+ length: r.size,+ scaleOffset: 0, scaleLength: 0,+ biasOffset: 0, biasLength: 0,+ shape: (UInt32(L), UInt32(E), 0, 0),+ dtype: 0)+ }++ /// Open layer L's file + verify SHA, idempotent.+ func ensureLayerOpened(_ L: Int) throws {+ try streamersQueue.sync {+ try openLayerLocked(L)+ }+ }++ /// Best-effort overlap hook for prefill: starts the same lazy layer open on+ /// the model's streamer queue without waiting for the first expert fetch.+ public func beginOpeningRoutedExpertStreamer(layer L: Int) {+ nonisolated(unsafe) let model = self+ streamersQueue.async {+ try? model.openLayerLocked(L)+ }+ }++ private func openLayerLocked(_ L: Int) throws {+ if streamersBox.streamers[L] != nil {+ return+ }+ let basename = packedExpertsLayout.layers[L].file+ let url = directoryURL+ .appendingPathComponent("packed_experts")+ .appendingPathComponent(basename)+ guard FileManager.default.fileExists(atPath: url.path) else {+ throw ModelError.missingFile(name: "packed_experts/\(basename)")+ }+ if !streamersBox.layerVerified[L] {+ let manifestRel = "packed_experts/\(basename)"+ guard let entry = manifest.files[manifestRel] else {+ throw ModelError.missingFile(name: manifestRel)+ }+ switch integrityPolicy {+ case .fullSha256:+ try Sha256Verifier.verifyFile(at: url, named: manifestRel,+ expectedHex: entry.sha256)+ case .sizeCheckTrustedReceipt:+ try Self.verifyTrustedReceiptFileSize(url: url,+ relativePath: manifestRel,+ expectedSize: entry.size)+ }+ streamersBox.layerVerified[L] = true+ }+ let streamSize = UInt64(packedExpertsLayout.expertsPerLayer)+ * packedExpertsLayout.expertStride+ let layout = StreamLayout(+ path: url.path,+ streamOffset: 0,+ streamSize: streamSize,+ expertsPerLayer: packedExpertsLayout.expertsPerLayer,+ expertStride: packedExpertsLayout.expertStride,+ expertOffsets: packedExpertsLayout.layers[L].experts.map(\.offset))+ let slotCount: Int+ switch streamingMode {+ case .pread(let configuredSlotCount):+ slotCount = configuredSlotCount+ }+ streamersBox.streamers[L] = try PreadExpertStreamer(+ layout: layout,+ device: device,+ slotCount: slotCount,+ cachePolicy: expertCachePolicy)+ }++ /// Test hook: how many layer files have been opened so far.+ public func openLayerFileCount() -> Int {+ streamersQueue.sync { streamersBox.streamers.compactMap { $0 }.count }+ }++}++extension Model {++ /// Open a `.gturbo/` directory and return a typed handle. Eagerly verifies+ /// SHA-256 of `model_weights.bin` and `packed_experts/layout.json`; layer+ /// files are verified lazily on first `routedExpert(...)` touch.+ public static func load(directoryURL: URL,+ device: MTLDevice,+ expecting: ArchConfig = .gemma4_26B_A4B,+ streamingMode: ExpertStreamingMode = .pread(slotCount: 16),+ expertCachePolicy: ExpertCachePolicy = PreadExpertStreamer.cachePolicyDefault,+ integrityPolicy: ModelIntegrityPolicy? = nil,+ loadStats: UnsafeMutablePointer<ModelLoadStats>? = nil) throws -> Model {+ var stats = ModelLoadStats()+ defer {+ loadStats?.pointee = stats+ }+ let resolvedIntegrityPolicy = integrityPolicy ?? .fullSha256++ let manifestURL = directoryURL.appendingPathComponent("manifest.json")+ guard FileManager.default.fileExists(atPath: manifestURL.path) else {+ throw ModelError.partialInstall(path: directoryURL.path)+ }+ let manifestShaStart = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ let manifestSha = try Sha256Verifier.hashFile(at: manifestURL)+ stats.manifestSha256Nanos = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - manifestShaStart+ let manifestSize = try Self.fileSize(at: manifestURL,+ relativePath: "manifest.json")+ let receipt: VerifiedInstallReceipt?+ if resolvedIntegrityPolicy == .sizeCheckTrustedReceipt {+ let receiptStart = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ let loadedReceipt = try VerifiedInstallReceiptReader.load(directoryURL: directoryURL)+ try VerifiedInstallReceiptReader.validateManifestBinding(+ loadedReceipt,+ directoryURL: directoryURL,+ manifestSha256: manifestSha)+ stats.receiptValidationNanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - receiptStart+ receipt = loadedReceipt+ } else {+ receipt = nil+ }++ let manifest = try ManifestReader.load(directoryURL: directoryURL,+ expecting: expecting)+ if let receipt {+ let receiptStart = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ try VerifiedInstallReceiptReader.validate(receipt,+ directoryURL: directoryURL,+ manifest: manifest,+ manifestSha256: manifestSha,+ manifestSize: manifestSize)+ stats.receiptValidationNanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - receiptStart+ }++ // Verify the small, always-touched files before mapping model data.+ let weightsURL = directoryURL.appendingPathComponent("model_weights.bin")+ let layoutURL = directoryURL+ .appendingPathComponent("packed_experts")+ .appendingPathComponent("layout.json")+ guard let weightsEntry = manifest.files["model_weights.bin"] else {+ throw ModelError.missingFile(name: "model_weights.bin")+ }+ guard let layoutEntry = manifest.files["packed_experts/layout.json"] else {+ throw ModelError.missingFile(name: "packed_experts/layout.json")+ }+ let eagerShaStart = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ try Sha256Verifier.verifyFile(at: weightsURL, named: "model_weights.bin",+ expectedHex: weightsEntry.sha256)+ try Sha256Verifier.verifyFile(at: layoutURL, named: "packed_experts/layout.json",+ expectedHex: layoutEntry.sha256)+ stats.eagerSha256Nanos = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - eagerShaStart++ let residentIndex = try ResidentIndexReader.load(fileURL: weightsURL)++ // The resident index must account for the complete weights file.+ let attrs = try FileManager.default.attributesOfItem(atPath: weightsURL.path)+ if let fileSize = attrs[.size] as? UInt64 {+ let expected = residentIndex.header.indexSize + residentIndex.header.residentSize+ if fileSize != expected {+ throw ModelError.indexCorrupt(detail: """+ model_weights.bin size \(fileSize) != indexSize \+ \(residentIndex.header.indexSize) + residentSize \+ \(residentIndex.header.residentSize) = \(expected)+ """)+ }+ }++ let residentBuffer = try ResidentBuffer(+ fileURL: weightsURL,+ fileOffset: residentIndex.header.indexSize,+ residentSize: residentIndex.header.residentSize,+ device: device)++ let layout = try PackedExpertsLayoutReader.load(directoryURL: directoryURL)+ if resolvedIntegrityPolicy == .sizeCheckTrustedReceipt {+ let receiptStart = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ try validateTrustedReceiptLayerLayout(directoryURL: directoryURL,+ manifest: manifest,+ layout: layout)+ stats.receiptValidationNanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - receiptStart+ }++ return Model(+ device: device,+ config: expecting,+ streamingMode: streamingMode,+ expertCachePolicy: expertCachePolicy,+ integrityPolicy: resolvedIntegrityPolicy,+ residentBuffer: residentBuffer,+ residentIndex: residentIndex,+ packedExpertsLayout: layout,+ manifest: manifest,+ directoryURL: directoryURL)+ }++ private static func verifyTrustedReceiptFileSize(url: URL,+ relativePath: String,+ expectedSize: UInt64) throws {+ let actualSize = try fileSize(at: url, relativePath: relativePath)+ guard actualSize == expectedSize else {+ throw ModelError.trustedReceiptInvalid(+ detail: "\(relativePath) size \(actualSize) != \(expectedSize)")+ }+ }++ private static func fileSize(at url: URL, relativePath: String) throws -> UInt64 {+ let attrs = try FileManager.default.attributesOfItem(atPath: url.path)+ guard let sizeValue = attrs[.size] else {+ throw ModelError.trustedReceiptInvalid(detail: "missing size for \(relativePath)")+ }+ let actualSize: UInt64+ if let number = sizeValue as? NSNumber {+ actualSize = number.uint64Value+ } else if let value = sizeValue as? UInt64 {+ actualSize = value+ } else if let value = sizeValue as? Int {+ actualSize = UInt64(value)+ } else {+ throw ModelError.trustedReceiptInvalid(detail: "invalid size for \(relativePath)")+ }+ return actualSize+ }++ private static func validateTrustedReceiptLayerLayout(directoryURL: URL,+ manifest: Manifest,+ layout: PackedExpertsLayout) throws {+ let pageSize = UInt64(getpagesize())+ guard layout.expertStride % pageSize == 0 else {+ throw ModelError.trustedReceiptInvalid(+ detail: "expertStride \(layout.expertStride) is not page-aligned")+ }+ guard layout.numLayers == manifest.numLayers,+ layout.expertsPerLayer == manifest.expertsPerLayer,+ layout.expertStride == manifest.expertStride else {+ throw ModelError.trustedReceiptInvalid(detail: "layout does not match manifest dimensions")+ }+ for layer in layout.layers {+ guard layer.layer >= 0 && layer.layer < manifest.numLayers else {+ throw ModelError.trustedReceiptInvalid(detail: "layout layer out of range")+ }+ let relativePath = "packed_experts/\(layer.file)"+ guard let manifestEntry = manifest.files[relativePath] else {+ throw ModelError.trustedReceiptInvalid(detail: "manifest missing \(relativePath)")+ }+ let expectedSize = UInt64(layout.expertsPerLayer) * layout.expertStride+ guard manifestEntry.size == expectedSize else {+ throw ModelError.trustedReceiptInvalid(+ detail: "\(relativePath) manifest size \(manifestEntry.size) != \(expectedSize)")+ }+ let url = directoryURL+ .appendingPathComponent("packed_experts")+ .appendingPathComponent(layer.file)+ let actualSize = try fileSize(at: url, relativePath: relativePath)+ guard actualSize == expectedSize else {+ throw ModelError.trustedReceiptInvalid(+ detail: "\(relativePath) size \(actualSize) != \(expectedSize)")+ }+ guard layer.experts.count == layout.expertsPerLayer else {+ throw ModelError.trustedReceiptInvalid(detail: "\(relativePath) expert count mismatch")+ }+ for expert in layer.experts {+ guard expert.size == layout.expertStride else {+ throw ModelError.trustedReceiptInvalid(+ detail: "\(relativePath) expert \(expert.expert) size mismatch")+ }+ guard expert.offset % pageSize == 0 else {+ throw ModelError.trustedReceiptInvalid(+ detail: "\(relativePath) expert \(expert.expert) offset is not page-aligned")+ }+ guard expert.offset <= actualSize,+ expert.size <= actualSize - expert.offset else {+ throw ModelError.trustedReceiptInvalid(+ detail: "\(relativePath) expert \(expert.expert) range exceeds file size")+ }+ }+ }+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Inference/ModelExpertIO.swift b/Sources/TurboFieldfare/Runtime/Inference/ModelExpertIO.swiftnew file mode 100644index 00000000..9ae7b881--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Inference/ModelExpertIO.swift@@ -0,0 +1,157 @@+import Foundation+import Metal++public struct RoutedExpertFetchPlan: Sendable {+ public let layer: Int+ public let cachePlan: ExpertCachePlan++ public var experts: [Int] { cachePlan.experts }+ public var misses: [Int] { cachePlan.misses }+ public var hits: Int { cachePlan.hits }+ public var assignedSlots: [Int] { cachePlan.assignedSlots }++ public init(layer: Int, cachePlan: ExpertCachePlan) {+ self.layer = layer+ self.cachePlan = cachePlan+ }+}++extension Model {+ public func routedExpertOffsets(layer: Int) -> MoEExpertOffsets {+ let expert = packedExpertsLayout.expert(layer: layer, expert: 0)+ func offset(_ role: String) -> UInt32 {+ UInt32(expert.subTensors[role]?.offset ?? 0)+ }+ return MoEExpertOffsets(+ gateWOff: offset("gate"),+ gateSOff: offset("gate_scales"),+ gateBOff: offset("gate_biases"),+ upWOff: offset("up"),+ upSOff: offset("up_scales"),+ upBOff: offset("up_biases"),+ downWOff: offset("down"),+ downSOff: offset("down_scales"),+ downBOff: offset("down_biases"))+ }++ public func routedExpertPhysicalOffsets(layer: Int) -> [UInt64] {+ packedExpertsLayout.layers[layer].experts.map(\.offset)+ }++ public func adviseRoutedExperts(layer: Int,+ experts: [Int]) throws -> ExpertIOAdviceResult {+ try ensureLayerOpened(layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[layer]! }+ return streamer.adviseExpertMisses(experts: experts)+ }++ public func routedExpertAdviceByteEstimate(layer: Int,+ missCount: Int) throws -> UInt64 {+ guard missCount > 0 else { return 0 }+ try ensureLayerOpened(layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[layer]! }+ return UInt64(missCount) * streamer.layout.expertStride+ }++ public func planRoutedExperts(layer: Int,+ experts: [Int],+ avoidingSlots: Set<Int> = []) throws -> RoutedExpertFetchPlan? {+ try ensureLayerOpened(layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[layer]! }+ let validSlots = Set(avoidingSlots.filter { $0 >= 0 && $0 < streamer.slotCount })+ return RoutedExpertFetchPlan(+ layer: layer,+ cachePlan: streamer.planExpertsCached(experts: experts, avoidingSlots: validSlots))+ }++ public func planRoutedExpertsIfPossible(layer: Int,+ experts: [Int],+ avoidingSlots: Set<Int> = []) throws+ -> RoutedExpertFetchPlan? {+ try ensureLayerOpened(layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[layer]! }+ let validSlots = Set(avoidingSlots.filter { $0 >= 0 && $0 < streamer.slotCount })+ guard let cachePlan = streamer.planExpertsCachedIfPossible(+ experts: experts,+ avoidingSlots: validSlots)+ else {+ return nil+ }+ return RoutedExpertFetchPlan(layer: layer, cachePlan: cachePlan)+ }++ public func routedExpertCacheSlotCount(layer _: Int) -> Int? {+ guard case .pread(let slotCount) = streamingMode else { return nil }+ return slotCount+ }++ public func routedExpertBuffers(for plan: RoutedExpertFetchPlan) throws -> [TensorView] {+ try ensureLayerOpened(plan.layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[plan.layer]! }+ return Self.makeExpertViews(+ streamer.expertCachePlanBuffers(plan.cachePlan),+ layer: plan.layer,+ experts: plan.experts)+ }++ public func adviseRoutedExperts(plan: RoutedExpertFetchPlan) throws -> ExpertIOAdviceResult {+ try ensureLayerOpened(plan.layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[plan.layer]! }+ return streamer.adviseExpertCachePlanMisses(plan.cachePlan)+ }++ public func fetchRoutedExperts(plan: RoutedExpertFetchPlan) async throws -> [TensorView] {+ try ensureLayerOpened(plan.layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[plan.layer]! }+ return try await withCheckedThrowingContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ do {+ let buffers = try streamer.executeExpertCachePlan(plan.cachePlan)+ continuation.resume(returning: Self.makeExpertViews(+ buffers,+ layer: plan.layer,+ experts: plan.experts))+ } catch {+ continuation.resume(throwing: error)+ }+ }+ }+ }++ public func fetchRoutedExperts(layer: Int, experts: [Int]) async throws -> [TensorView] {+ try ensureLayerOpened(layer)+ let streamer = streamersQueue.sync { streamersBox.streamers[layer]! }+ return try await withCheckedThrowingContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ do {+ let buffers = try streamer.loadExpertsCached(experts: experts)+ continuation.resume(returning: Self.makeExpertViews(+ buffers,+ layer: layer,+ experts: experts))+ } catch {+ continuation.resume(throwing: error)+ }+ }+ }+ }++ private static func makeExpertViews(+ _ buffers: [(buffer: MTLBuffer, offset: UInt64, size: UInt64)],+ layer: Int,+ experts: [Int]+ ) -> [TensorView] {+ buffers.enumerated().map { index, entry in+ TensorView(+ buffer: entry.buffer,+ offset: entry.offset,+ length: entry.size,+ scaleOffset: 0,+ scaleLength: 0,+ biasOffset: 0,+ biasLength: 0,+ shape: (UInt32(layer), UInt32(experts[index]), 0, 0),+ dtype: 0)+ }+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swiftnew file mode 100644index 00000000..2d5a5cac--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift@@ -0,0 +1,1916 @@+import Foundation+import Metal++public enum RDAdvicePolicyMode: String, Codable, Sendable, Equatable {+ case `default`+ case off+ case bounded+ case adaptive++ public static func parse(_ raw: String?) -> RDAdvicePolicyMode {+ switch raw?.lowercased() {+ case "off", "none", "disabled":+ return .off+ case "bounded":+ return .bounded+ case "adaptive":+ return .adaptive+ default:+ return .default+ }+ }+}++public struct RDAdviceAdaptivePolicyConfig: Sendable, Equatable {+ public var missCap: Int+ public var byteCap: UInt64+ public var slowCallNanos: UInt64++ public init(missCap: Int,+ byteCap: UInt64,+ slowCallNanos: UInt64) {+ self.missCap = missCap+ self.byteCap = byteCap+ self.slowCallNanos = slowCallNanos+ }++ public static let conservative = RDAdviceAdaptivePolicyConfig(+ missCap: 12,+ byteCap: 384 * 1_048_576,+ slowCallNanos: 1_000_000)+}++struct RDAdviceAdaptivePolicyState: Sendable, Equatable {+ var config: RDAdviceAdaptivePolicyConfig+ private var skipUntilPosition: Int = -1+ private(set) var recentSlowCallNanos: UInt64 = 0++ init(config: RDAdviceAdaptivePolicyConfig = .conservative) {+ self.config = config+ }++ mutating func reset() {+ skipUntilPosition = -1+ recentSlowCallNanos = 0+ }++ func shouldSkip(position: Int,+ requestedMisses: Int,+ estimatedBytes: UInt64,+ canOverlapUsefulGPUWork: Bool) -> Bool {+ position <= skipUntilPosition ||+ !canOverlapUsefulGPUWork ||+ requestedMisses > config.missCap ||+ estimatedBytes > config.byteCap+ }++ mutating func update(after result: ExpertIOAdviceResult,+ position: Int) {+ recentSlowCallNanos = max(recentSlowCallNanos, result.maxCallNanos)+ if result.maxCallNanos >= config.slowCallNanos {+ skipUntilPosition = max(skipUntilPosition, position)+ }+ }+}++/// Gemma 4 real-forward decode pass.+///+/// Composes the production kernels against the `.gturbo` model:+///+/// embed_lookup_int4(token) * sqrt(H)+/// for L in 0..<30:+/// a = rmsnorm_bf16w(h, input_layernorm)+/// Q = q_proj(a) K = k_proj(a) V = (SWA) v_proj(a) | (full) k_proj(a)+/// per-head q/k_norm (bf16w), per-head v_norm (no_scale)+/// NeoX RoPE on Q + K (default for SWA, proportional for full)+/// write K and V into separate cache slots+/// attn = attention(scale=1.0, SWA window or full causal)+/// attn = o_proj(attn)+/// h = h + rmsnorm_bf16w(attn, post_attention_layernorm)+/// h1 = rmsnorm_bf16w(h, pre_feedforward_layernorm)+/// h1 = SharedExpertInt8(h1)+/// h1 = rmsnorm_bf16w(h1, post_feedforward_layernorm_1)+/// // router + routed branch+/// xr = rmsnorm_no_scale(h)+/// idx, w = router_topk_gemma4(xr, effective_scale[L], per_expert_scale[L])+/// h2 = rmsnorm_bf16w(h, pre_feedforward_layernorm_2)+/// h2 = moe_fused_ffn_streamed_routed(h2, residual=0, routedBlobs=fetch(idx), w)+/// h2 = rmsnorm_bf16w(h2, post_feedforward_layernorm_2)+/// h = h + rmsnorm_bf16w(h1 + h2, post_feedforward_layernorm)+/// h = h * layer_scalar[L]+/// logits = DequantInt4GEMV(rmsnorm_bf16w(h, model.norm), embed_table^T)+/// // final softcap and softmax happen in the Sampler.+///+/// Direct against `Model`; this is the only production decode forward path.+internal enum PrefillProjectionFamily: Sendable, Equatable {+ case q+ case kv+ case o+ case shared+ case routed+}++internal enum PrefillProjectionDispatch: Sendable, Equatable {+ case repeatedGEMV+ case qmm+}++internal enum PrefillProjectionDispatchPolicy {+ static func selectedDispatch(for family: PrefillProjectionFamily,+ chunkTokens: Int) -> PrefillProjectionDispatch {+ guard chunkTokens >= 32 else {+ return .repeatedGEMV+ }+ switch family {+ case .q:+ return .repeatedGEMV+ case .kv, .o, .shared, .routed:+ return .qmm+ }+ }+}++public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporting, @unchecked Sendable {+ private struct LayerSharedExpertProjections {+ let gate: SharedExpertInt8Proj+ let up: SharedExpertInt8Proj+ let down: SharedExpertInt8Proj+ let postF1: TensorView+ }++ private let model: Model+ private let ctx: MetalContext+ private let kv: KVCacheManager?+ private let turboQuantKV: KVCacheManager?+ private let cfg: ArchConfig++ // Kernels+ private let embedInt4: EmbedLookupInt4+ private let rms: RMSNorm+ private let int4: DequantInt4GEMV+ private let attention: Attention+ private let shared: SharedExpertInt8+ private let moe: MoE+ private let fusionHead: LMHeadChainInt4+ private let fusedQKVGEMV: FusedQKVGEMV+ private let fusedQKVEpilogue: FusedQKVEpilogue+ private let fusedPostAttentionSetup: FusedPostAttentionSetup+ private let fusedTail: FusedLayerTail+ private let turboQuantQuant: TurboQuantQuant?++ // Prefill kernels. These are initialized once per runner so the chunk path+ // cannot accidentally rebuild PSOs inside a per-layer loop.+ private let prefillEmbed: PrefillEmbedLookupInt4+ private let prefillRMS: PrefillRMSNorm+ private let prefillQMM: PrefillInt4QMM+ private let prefillMPPAffineInt4: MPPPrefillInt4QMM?+ private let prefillQKVEpilogue: PrefillQKVEpilogue+ private let prefillAttention: PrefillAttention+ private let prefillPostAttention: PrefillPostAttentionSetup+ private let prefillRouter: PrefillRouter+ private let prefillSharedExpert: PrefillSharedExpert+ private let prefillGroupedMoE: PrefillGroupedRoutedMoE+ private let prefillMoE: PrefillMoE+ private let prefillLayerTail: PrefillLayerTail+ private let prefillFinalRowHead: PrefillFinalRowHeadInt4++ // Scratch — preallocated per spec'd D / F / vocab.+ private let hidden: MTLBuffer // [D] FP16+ private let normed: MTLBuffer // [D] FP16+ private let attnOut: MTLBuffer // [N_HEADS * head_dim] FP16+ private let qScratch: MTLBuffer // [N_HEADS * head_dim] FP16+ private let kStage: MTLBuffer // [max KV heads * head_dim] FP16, current token+ private let vStage: MTLBuffer // [max KV heads * head_dim] FP16, current token+ private let oOut: MTLBuffer // [D] FP16+ private let h1Buf: MTLBuffer // [D] FP16 (dense MLP output)+ private let h2Buf: MTLBuffer // [D] FP16 (routed output)+ private let routedX: MTLBuffer // [D] FP16 (pre_feedforward_layernorm_2 output)+ private let denseX: MTLBuffer // [D] FP16 (pre_feedforward_layernorm output)+ private let denseScratchA: MTLBuffer // [F=2112] FP16+ private let routerInput: MTLBuffer // [D] FP16 (rmsnorm_no_scale(h))+ private let zeroResidual: MTLBuffer // [D] FP16 zeros — for routed branch base+ private let outIndices: MTLBuffer // [topK] UInt32+ private let outWeights: MTLBuffer // [topK] FP16+ // Persistent MoE scratch, allocated once; about 56 KiB at production shape.+ private let moeActs: MTLBuffer // [topK * FmoE] FP16+ private let moeHitActiveSlots: MTLBuffer // [topK] UInt32+ private let moeMissActiveSlots: MTLBuffer // [topK] UInt32+ private let greedyTokenBuf: MTLBuffer // 4 B UInt32 fused-head output+ private var prefillChunkState = PrefillChunkCommitState()+ private var prefillScratch: PrefillChunkScratchBuffers?++ private static let rdadviseBoundedMissCap = 12+ private static let rdadviseBoundedMaxCallNanos: UInt64 = 250_000+ private static let rdadviseAdaptiveMissCap = 12+ private static let rdadviseAdaptiveByteCap: UInt64 = 384 * 1_048_576+ private static let rdadviseAdaptiveSlowCallNanos: UInt64 = 1_000_000+ private static let turboQuantRotationSeed: UInt32 = 0xA11CE+ private static let prefillRoutedTileSchedulerConfig = PrefillRoutedTileSchedulerConfig()++ /// Per-layer `router.scale * D^-0.5` pre-folded into one BF16 buffer+ /// allocation per layer. ~168 KB total at 30 layers × 2816 BF16 — bounded+ /// host work done once at init.+ private let effectiveScaleBuffers: [MTLBuffer]+ private let sharedExpertProjections: [LayerSharedExpertProjections]++ public let maxContext: Int++ /// Per-instance head and RDADVISE modes. The fused head (default) skips the+ /// 512 KB logits write and leaves a greedy argmax in `lastGreedyToken`;+ /// callers that sample from the logits buffer (non-greedy configs) must pass+ /// `forceLogitsHead: true` or they read a never-written buffer.+ private let useFusedGreedyHead: Bool+ private let useTurboQuantKV: Bool+ public let rdadviseEnabled: Bool+ public let rdadvisePolicyMode: RDAdvicePolicyMode+ private var rdadviseSkipUntilPosition: Int = -1+ private var rdadviseAdaptiveState: RDAdviceAdaptivePolicyState+ private var rdadviseAdaptivePosition: Int = -1+ private var rdadviseAdaptivePositionBytes: UInt64 = 0+ public init(model: Model, context: MetalContext, maxContext: Int,+ runtimeConfiguration: RuntimeConfiguration = .production) throws {+ self.model = model+ self.ctx = context+ self.cfg = model.config+ self.maxContext = maxContext+ self.useFusedGreedyHead = runtimeConfiguration.headPath == .fusedRows+ let useFP16Ring = runtimeConfiguration.fp16RingEnabled+ self.rdadvisePolicyMode = runtimeConfiguration.rdadvisePolicy+ self.rdadviseAdaptiveState = RDAdviceAdaptivePolicyState(+ config: RDAdviceAdaptivePolicyConfig(+ missCap: Self.rdadviseAdaptiveMissCap,+ byteCap: Self.rdadviseAdaptiveByteCap,+ slowCallNanos: Self.rdadviseAdaptiveSlowCallNanos))+ self.rdadviseEnabled = runtimeConfiguration.rdadviseEnabled+ self.useTurboQuantKV = runtimeConfiguration.turboQuantKVEnabled+ self.kv = useTurboQuantKV+ ? nil+ : try KVCacheManager(device: context.device,+ config: cfg,+ maxContext: maxContext,+ fp16RingEnabled: useFP16Ring,+ slidingWindow: cfg.slidingWindow,+ maxPrefillChunkTokens: PrefillRuntimeConfig.maxChunkTokens)+ self.turboQuantKV = useTurboQuantKV+ ? try KVCacheManager(device: context.device,+ config: cfg,+ maxContext: maxContext,+ storageMode: .turboQuant(.k4v4NormCorrected))+ : nil++ self.embedInt4 = try EmbedLookupInt4(context: context)+ self.rms = try RMSNorm(context: context)+ self.int4 = try DequantInt4GEMV(context: context)+ self.attention = try Attention(context: context)+ self.shared = try SharedExpertInt8(context: context)+ self.moe = try MoE(context: context)+ self.fusionHead = try LMHeadChainInt4(context: context,+ maxD: cfg.hiddenSize,+ maxVocab: cfg.vocabSize)+ self.fusedQKVGEMV = try FusedQKVGEMV(context: context)+ self.fusedQKVEpilogue = try FusedQKVEpilogue(context: context)+ self.fusedPostAttentionSetup = try FusedPostAttentionSetup(context: context)+ self.fusedTail = try FusedLayerTail(context: context)+ self.turboQuantQuant = useTurboQuantKV+ ? try TurboQuantQuant(context: context)+ : nil+ self.prefillEmbed = try PrefillEmbedLookupInt4(context: context)+ self.prefillRMS = try PrefillRMSNorm(context: context)+ self.prefillQMM = try PrefillInt4QMM(context: context)+ self.prefillMPPAffineInt4 = MPPPrefillInt4QMM(context: context)+ self.prefillQKVEpilogue = try PrefillQKVEpilogue(context: context)+ self.prefillAttention = try PrefillAttention(context: context)+ self.prefillPostAttention = try PrefillPostAttentionSetup(context: context)+ self.prefillRouter = try PrefillRouter(context: context)+ self.prefillSharedExpert = try PrefillSharedExpert(context: context)+ self.prefillGroupedMoE = try PrefillGroupedRoutedMoE(context: context)+ self.prefillMoE = try PrefillMoE(context: context)+ self.prefillLayerTail = try PrefillLayerTail(context: context)+ self.prefillFinalRowHead = try PrefillFinalRowHeadInt4(context: context,+ maxD: cfg.hiddenSize)++ let device = context.device+ let D = cfg.hiddenSize+ let F = cfg.intermediateSize+ let maxQ = cfg.numHeads * max(cfg.headDim, cfg.fullHeadDim)++ func buf(_ count: Int, _ stride: Int = MemoryLayout<Float16>.size) throws -> MTLBuffer {+ guard let b = device.makeBuffer(length: max(count, 1) * stride,+ options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ return b+ }+ self.hidden = try buf(D)+ self.normed = try buf(D)+ self.attnOut = try buf(maxQ)+ self.qScratch = try buf(maxQ)+ self.kStage = try buf(max(cfg.numKVHeads * cfg.headDim,+ cfg.numFullKVHeads * cfg.fullHeadDim))+ self.vStage = try buf(max(cfg.numKVHeads * cfg.headDim,+ cfg.numFullKVHeads * cfg.fullHeadDim))+ self.oOut = try buf(D)+ self.h1Buf = try buf(D)+ self.h2Buf = try buf(D)+ self.routedX = try buf(D)+ self.denseX = try buf(D)+ self.denseScratchA = try buf(F)+ self.routerInput = try buf(D)+ self.zeroResidual = try buf(D)+ // The routed MoE kernel seeds y[d] = residual[d]; pinning this buffer+ // to zero once at init makes the routed branch's residual contribution+ // exactly zero (it's combined with the dense MLP downstream).+ memset(self.zeroResidual.contents(), 0, self.zeroResidual.length)+ self.outIndices = try buf(cfg.topKExperts, MemoryLayout<UInt32>.size)+ self.outWeights = try buf(cfg.topKExperts)+ self.moeActs = try buf(cfg.topKExperts * cfg.moeIntermediateSize)+ self.moeHitActiveSlots = try buf(cfg.topKExperts, MemoryLayout<UInt32>.size)+ self.moeMissActiveSlots = try buf(cfg.topKExperts, MemoryLayout<UInt32>.size)+ guard let tok = device.makeBuffer(length: MemoryLayout<UInt32>.size,+ options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ self.greedyTokenBuf = tok++ func sharedProj(_ view: TensorView, rows: UInt32, cols: UInt32) -> SharedExpertInt8Proj {+ SharedExpertInt8Proj(weights: view.buffer,+ scales: view.buffer,+ biases: view.buffer,+ weightsOffset: Int(view.offset),+ scalesOffset: Int(view.scaleOffset),+ biasesOffset: Int(view.biasOffset),+ rows: rows,+ cols: cols)+ }+ var sharedViews: [LayerSharedExpertProjections] = []+ sharedViews.reserveCapacity(cfg.numLayers)+ for L in 0..<cfg.numLayers {+ let gate = try model.sharedExpertGate(layer: L)+ let up = try model.sharedExpertUp(layer: L)+ let down = try model.sharedExpertDown(layer: L)+ sharedViews.append(LayerSharedExpertProjections(+ gate: sharedProj(gate, rows: UInt32(F), cols: UInt32(D)),+ up: sharedProj(up, rows: UInt32(F), cols: UInt32(D)),+ down: sharedProj(down, rows: UInt32(D), cols: UInt32(F)),+ postF1: try model.postFFN1(layer: L)))+ }+ self.sharedExpertProjections = sharedViews++ // Pre-fold 1/sqrt(D) into router.scale per layer. Each layer gets its+ // own BF16 [D] buffer — the kernel reads `effective_scale[i]` and we+ // pay for the multiply once per generation, not per token.+ var perLayer: [MTLBuffer] = []+ perLayer.reserveCapacity(cfg.numLayers)+ let invSqrtD = Float(1.0) / Float(D).squareRoot()+ let dInts = D+ for L in 0..<cfg.numLayers {+ let scaleView = try model.routerScale(layer: L)+ guard let buf = device.makeBuffer(length: dInts * MemoryLayout<UInt16>.size,+ options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ let src = scaleView.buffer.contents()+ .advanced(by: Int(scaleView.offset))+ .assumingMemoryBound(to: UInt16.self)+ let dst = buf.contents().assumingMemoryBound(to: UInt16.self)+ for i in 0..<dInts {+ let v = Quantization.bf16ToFloat(src[i]) * invSqrtD+ dst[i] = Quantization.bf16Bits(v)+ }+ buf.label = "effective_scale.L\(L)"+ perLayer.append(buf)+ }+ self.effectiveScaleBuffers = perLayer+ }++ public func reset() {+ kv?.reset()+ turboQuantKV?.reset()+ prefillChunkState.reset()+ rdadviseSkipUntilPosition = -1+ rdadviseAdaptiveState.reset()+ rdadviseAdaptivePosition = -1+ rdadviseAdaptivePositionBytes = 0+ }++ public private(set) var totalIoNanos: UInt64 = 0+ public private(set) var totalCb1Nanos: UInt64 = 0+ public private(set) var totalCb2Nanos: UInt64 = 0+ public private(set) var totalHeadNanos: UInt64 = 0+ public private(set) var totalHeadFusedNanos: UInt64 = 0+ public private(set) var lastGreedyToken: UInt32 = 0+ public var usesFusedGreedyHead: Bool { useFusedGreedyHead }+ public private(set) var totalRDAdviseNanos: UInt64 = 0+ public private(set) var totalRDAdviseCalls: UInt64 = 0+ public private(set) var totalRDAdviseBytes: UInt64 = 0+ public private(set) var totalRDAdviseFailures: UInt64 = 0+ public private(set) var totalRDAdviseSkipped: UInt64 = 0++ private func recordRDAdvice(_ result: ExpertIOAdviceResult, wallNanos: UInt64) {+ totalRDAdviseNanos &+= wallNanos+ totalRDAdviseCalls &+= UInt64(result.calls)+ totalRDAdviseBytes &+= result.bytes+ totalRDAdviseFailures &+= UInt64(result.failed)+ totalRDAdviseSkipped &+= UInt64(result.skipped)+ }++ private func shouldSkipRDAdvice(position: Int,+ requestedMisses: Int,+ estimatedBytes: UInt64,+ canOverlapUsefulGPUWork: Bool) -> ExpertIOAdviceResult? {+ switch rdadvisePolicyMode {+ case .bounded:+ if position <= rdadviseSkipUntilPosition {+ return ExpertIOAdviceResult.skipped(requested: requestedMisses,+ bytes: estimatedBytes)+ }+ if requestedMisses > Self.rdadviseBoundedMissCap {+ return ExpertIOAdviceResult.skipped(requested: requestedMisses,+ bytes: estimatedBytes)+ }+ return nil+ case .adaptive:+ if position != rdadviseAdaptivePosition {+ rdadviseAdaptivePosition = position+ rdadviseAdaptivePositionBytes = 0+ }+ let cumulativeEstimatedBytes = rdadviseAdaptivePositionBytes &+ estimatedBytes+ let shouldSkip = rdadviseAdaptiveState.shouldSkip(+ position: position,+ requestedMisses: requestedMisses,+ estimatedBytes: cumulativeEstimatedBytes,+ canOverlapUsefulGPUWork: canOverlapUsefulGPUWork)+ rdadviseAdaptivePositionBytes = cumulativeEstimatedBytes+ guard shouldSkip else { return nil }+ return ExpertIOAdviceResult.skipped(requested: requestedMisses,+ bytes: estimatedBytes)+ case .default, .off:+ return nil+ }+ }++ private func updateRDAdvicePolicy(after result: ExpertIOAdviceResult,+ position: Int) {+ switch rdadvisePolicyMode {+ case .bounded:+ if result.maxCallNanos > Self.rdadviseBoundedMaxCallNanos {+ rdadviseSkipUntilPosition = max(rdadviseSkipUntilPosition, position + 1)+ }+ case .adaptive:+ rdadviseAdaptiveState.update(after: result, position: position)+ case .default, .off:+ break+ }+ }++ public func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws {+ try prefillChunkState.requireClean(operation: "produce")+ try await produceToken(token: token,+ position: position,+ into: logits,+ emitHead: true,+ outputMode: .greedyIfAvailable)+ }++ public func prefillChunked(tokens: ArraySlice<Int32>,+ startPosition: Int,+ outputMode: PrefillOutputMode,+ config: PrefillRuntimeConfig,+ into logits: MTLBuffer,+ onProgress: (Int) -> Void) async throws -> PrefillResult {+ try prefillChunkState.requireClean(operation: "prefillChunked")+ guard config.mode == .chunked else {+ throw PrefillError.chunkedUnsupported(+ "prefillChunked requires PrefillRuntimeConfig.mode == .chunked")+ }+ guard startPosition >= 0 else {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill startPosition must be non-negative")+ }+ let kvPosition = kv?.position ?? turboQuantKV?.position ?? 0+ guard kvPosition == startPosition else {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill cursor \(kvPosition) != startPosition \(startPosition)")+ }+ guard tokens.count <= maxContext - startPosition else {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill range starting at \(startPosition) with \(tokens.count) tokens exceeds maxContext \(maxContext)")+ }+ guard !tokens.isEmpty else {+ return PrefillResult(newPosition: startPosition, seed: .logitsWritten)+ }++ let scratch = try ensurePrefillScratch(config: config)+ let spans = PrefillChunkPlanner.spans(tokenCount: tokens.count,+ startPosition: startPosition,+ config: config)+ for (spanIndex, span) in spans.enumerated() {+ let lower = tokens.index(tokens.startIndex, offsetBy: span.tokenOffset)+ let upper = tokens.index(lower, offsetBy: span.tokenCount)+ try await executePrefillChunk(+ tokens: tokens[lower..<upper],+ startPosition: span.startPosition,+ outputMode: outputMode,+ logits: logits,+ scratch: scratch,+ config: config,+ writeFinalHead: spanIndex == spans.count - 1)+ onProgress(span.completedCount)+ }+ if outputMode == .greedyIfAvailable, useFusedGreedyHead {+ return PrefillResult(newPosition: startPosition + tokens.count,+ seed: .greedyToken(lastGreedyToken))+ }+ return PrefillResult(newPosition: startPosition + tokens.count,+ seed: .logitsWritten)+ }++ @discardableResult+ private func ensurePrefillScratch(config: PrefillRuntimeConfig) throws -> PrefillChunkScratchBuffers {+ let layout = PrefillChunkScratchLayout(config: cfg, runtime: config)+ if let scratch = prefillScratch, scratch.layout == layout {+ return scratch+ }+ let scratch = try PrefillChunkScratchBuffers.allocate(device: ctx.device, layout: layout)+ prefillScratch = scratch+ return scratch+ }++ private func executePrefillChunk(tokens: ArraySlice<Int32>,+ startPosition: Int,+ outputMode: PrefillOutputMode,+ logits: MTLBuffer,+ scratch: PrefillChunkScratchBuffers,+ config: PrefillRuntimeConfig,+ writeFinalHead: Bool) async throws {+ guard !tokens.isEmpty else { return }+ if kv == nil && turboQuantKV == nil {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill attention requires fp16 or packed TurboQuant KV")+ }+ let kvPosition = kv?.position ?? turboQuantKV?.position ?? 0+ guard kvPosition == startPosition else {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill cursor \(kvPosition) != startPosition \(startPosition)")+ }+ guard startPosition >= 0, startPosition + tokens.count <= maxContext else {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill range [\(startPosition), \(startPosition + tokens.count)) exceeds maxContext \(maxContext)")+ }+ guard tokens.count <= scratch.layout.chunkTokens else {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill token count \(tokens.count) exceeds scratch chunk size \(scratch.layout.chunkTokens)")+ }+ if let kv, kv.fp16RingEnabled, let ringLayer = (0..<cfg.numLayers).first(where: {+ kv.ringCapacity(layer: $0) > 0+ }) {+ let requiredCapacity = min(maxContext, cfg.slidingWindow + config.chunkTokens)+ let ringCapacity = kv.ringCapacity(layer: ringLayer)+ guard requiredCapacity <= ringCapacity else {+ throw PrefillError.chunkedUnsupported(+ "FP16 KV ring capacity \(ringCapacity) cannot hold required capacity \(requiredCapacity) for maxContext \(maxContext), slidingWindow \(cfg.slidingWindow), and prefillChunkTokens \(config.chunkTokens)")+ }+ }++ struct LayerPrefillQKVViews {+ let inputNorm: TensorView+ let q: TensorView+ let k: TensorView+ let v: TensorView+ let o: TensorView+ let postAttention: TensorView+ let preFFN: TensorView+ let preFFN2: TensorView+ let postFFN2: TensorView+ let postFFN: TensorView+ let layerScalar: TensorView+ let qNorm: TensorView+ let kNorm: TensorView+ let router: TensorView+ let routerPerExpertScale: TensorView+ }++ let layerViews = try (0..<cfg.numLayers).map { L in+ let isFull = cfg.fullAttentionLayerMask[L] != 0+ return LayerPrefillQKVViews(+ inputNorm: try model.inputNorm(layer: L),+ q: try model.qProj(layer: L),+ k: try model.kProj(layer: L),+ v: isFull ? (try model.kProj(layer: L)) : (try model.vProj(layer: L)),+ o: try model.oProj(layer: L),+ postAttention: try model.postAttnNorm(layer: L),+ preFFN: try model.preFFN(layer: L),+ preFFN2: try model.preFFN2(layer: L),+ postFFN2: try model.postFFN2(layer: L),+ postFFN: try model.postFFN(layer: L),+ layerScalar: try model.layerScalar(layer: L),+ qNorm: try model.qNorm(layer: L),+ kNorm: try model.kNorm(layer: L),+ router: try model.router(layer: L),+ routerPerExpertScale: try model.routerPerExpertScale(layer: L))+ }++ let tokenIDs = tokens.map { UInt32(bitPattern: $0) }+ guard let tokenBuffer = ctx.device.makeBuffer(bytes: tokenIDs,+ length: tokenIDs.count * MemoryLayout<UInt32>.stride,+ options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ let D = cfg.hiddenSize+ let eps: Float = 1e-6+ let sqrtHidden = Float(D).squareRoot()+ let t = tokens.count+ let emb = model.embedding++ func encodeInt4Projection(commandBuffer: MTLCommandBuffer,+ family: PrefillProjectionFamily,+ weights: TensorView,+ x: MTLBuffer,+ y: MTLBuffer,+ rows: Int,+ columns: Int,+ tokenCount: Int,+ xStrideElements: Int,+ yStrideElements: Int) {+ if tokenCount >= 32,+ family == .q || family == .kv || family == .o,+ let candidate = prefillMPPAffineInt4 {+ let path = candidate.encode(+ commandBuffer: commandBuffer,+ weights: weights.buffer,+ weightsOffset: Int(weights.offset),+ scales: weights.buffer,+ scalesOffset: Int(weights.scaleOffset),+ biases: weights.buffer,+ biasesOffset: Int(weights.biasOffset),+ x: x,+ y: y,+ m: tokenCount,+ n: rows,+ k: columns)+ if path == .affineThreadgroupF16 {+ return+ }+ }+ if PrefillProjectionDispatchPolicy.selectedDispatch(for: family,+ chunkTokens: tokenCount) == .qmm {+ prefillQMM.encode(commandBuffer: commandBuffer,+ weights: weights.buffer,+ weightsOffset: Int(weights.offset),+ scales: weights.buffer,+ scalesOffset: Int(weights.scaleOffset),+ biases: weights.buffer,+ biasesOffset: Int(weights.biasOffset),+ x: x,+ y: y,+ t: tokenCount,+ n: rows,+ k: columns)+ return+ }+ for row in 0..<tokenCount {+ int4.encode(commandBuffer: commandBuffer,+ weights: weights.buffer,+ weightsOffset: Int(weights.offset),+ scales: weights.buffer,+ scalesOffset: Int(weights.scaleOffset),+ biases: weights.buffer,+ biasesOffset: Int(weights.biasOffset),+ x: x,+ xOffset: row * xStrideElements * MemoryLayout<Float16>.stride,+ y: y,+ yOffset: row * yStrideElements * MemoryLayout<Float16>.stride,+ m: UInt32(rows),+ n: UInt32(columns))+ }+ }++ func copyPrefillKV(commandBuffer: MTLCommandBuffer,+ source: MTLBuffer,+ destination: (buffer: MTLBuffer, offset: Int, stride: Int),+ sourceTokenOffset: Int,+ tokenCount: Int,+ bytesPerToken: Int) throws {+ guard tokenCount > 0 else { return }+ guard let blit = commandBuffer.makeBlitCommandEncoder() else {+ throw ModelError.residentBufferWrapFailed+ }+ blit.copy(from: source,+ sourceOffset: sourceTokenOffset * bytesPerToken,+ to: destination.buffer,+ destinationOffset: destination.offset,+ size: tokenCount * bytesPerToken)+ blit.endEncoding()+ }++ func copyPrefillKVToCache(commandBuffer: MTLCommandBuffer,+ kv: KVCacheManager,+ layer: Int,+ startPosition: Int,+ tokenCount: Int,+ keySource: MTLBuffer,+ valueSource: MTLBuffer,+ bytesPerToken: Int) throws {+ let capacity = kv.capacity(layer: layer)+ let physicalStart = startPosition % capacity+ let firstSpan = min(tokenCount, capacity - physicalStart)+ let keyFirst = kv.kRange(layer: layer, start: startPosition, count: firstSpan)+ let valueFirst = kv.vRange(layer: layer, start: startPosition, count: firstSpan)+ try copyPrefillKV(commandBuffer: commandBuffer,+ source: keySource,+ destination: keyFirst,+ sourceTokenOffset: 0,+ tokenCount: firstSpan,+ bytesPerToken: bytesPerToken)+ try copyPrefillKV(commandBuffer: commandBuffer,+ source: valueSource,+ destination: valueFirst,+ sourceTokenOffset: 0,+ tokenCount: firstSpan,+ bytesPerToken: bytesPerToken)+ guard firstSpan < tokenCount else { return }++ let secondCount = tokenCount - firstSpan+ let secondStart = startPosition + firstSpan+ let keySecond = kv.kRange(layer: layer, start: secondStart, count: secondCount)+ let valueSecond = kv.vRange(layer: layer, start: secondStart, count: secondCount)+ try copyPrefillKV(commandBuffer: commandBuffer,+ source: keySource,+ destination: keySecond,+ sourceTokenOffset: firstSpan,+ tokenCount: secondCount,+ bytesPerToken: bytesPerToken)+ try copyPrefillKV(commandBuffer: commandBuffer,+ source: valueSource,+ destination: valueSecond,+ sourceTokenOffset: firstSpan,+ tokenCount: secondCount,+ bytesPerToken: bytesPerToken)+ }++ prefillChunkState.markDirty(startPosition: startPosition, tokenCount: tokens.count)++ guard var cb = ctx.queue.makeCommandBuffer() else {+ throw ModelError.residentBufferWrapFailed+ }+ prefillEmbed.encode(commandBuffer: cb,+ table: emb.buffer,+ tableOffset: Int(emb.offset),+ scales: emb.buffer,+ scalesOffset: Int(emb.scaleOffset),+ biases: emb.buffer,+ biasesOffset: Int(emb.biasOffset),+ tokens: tokenBuffer,+ out: scratch.hidden,+ t: UInt32(t),+ d: UInt32(D),+ outScale: sqrtHidden)++ for L in 0..<cfg.numLayers {+ model.beginOpeningRoutedExpertStreamer(layer: L)+ let views = layerViews[L]+ let isFull = cfg.fullAttentionLayerMask[L] != 0+ let headDim = isFull ? cfg.fullHeadDim : cfg.headDim+ let numKVHeads = isFull ? cfg.numFullKVHeads : cfg.numKVHeads+ let qDim = cfg.numHeads * headDim+ let kvDim = numKVHeads * headDim++ prefillRMS.encodeBF16W(commandBuffer: cb,+ x: scratch.hidden,+ weight: views.inputNorm.buffer,+ weightOffset: Int(views.inputNorm.offset),+ out: scratch.normed,+ t: UInt32(t),+ d: UInt32(D),+ eps: eps)+ encodeInt4Projection(commandBuffer: cb,+ family: .q,+ weights: views.q,+ x: scratch.normed,+ y: scratch.q,+ rows: qDim,+ columns: D,+ tokenCount: t,+ xStrideElements: D,+ yStrideElements: qDim)+ encodeInt4Projection(commandBuffer: cb,+ family: .kv,+ weights: views.k,+ x: scratch.normed,+ y: scratch.kStage,+ rows: kvDim,+ columns: D,+ tokenCount: t,+ xStrideElements: D,+ yStrideElements: kvDim)+ encodeInt4Projection(commandBuffer: cb,+ family: .kv,+ weights: views.v,+ x: scratch.normed,+ y: scratch.vStage,+ rows: kvDim,+ columns: D,+ tokenCount: t,+ xStrideElements: D,+ yStrideElements: kvDim)++ let rotatedPairs = isFull+ ? UInt32(Double(cfg.fullHeadDim) * cfg.partialRotaryFactor / 2.0)+ : UInt32(headDim / 2)+ prefillQKVEpilogue.encode(commandBuffer: cb,+ q: scratch.q,+ k: scratch.kStage,+ v: scratch.vStage,+ qWeight: views.qNorm.buffer,+ qWeightOffset: Int(views.qNorm.offset),+ kWeight: views.kNorm.buffer,+ kWeightOffset: Int(views.kNorm.offset),+ startPosition: UInt32(startPosition),+ queryCount: UInt32(t),+ headDim: UInt32(headDim),+ numQHeads: UInt32(cfg.numHeads),+ numKVHeads: UInt32(numKVHeads),+ qTokenStrideElements: UInt32(qDim),+ kvTokenStrideElements: UInt32(kvDim),+ theta: isFull ? Float(cfg.fullRopeTheta) : Float(cfg.ropeTheta),+ rotatedPairs: rotatedPairs,+ eps: eps)++ if let kv {+ let bytes = t * kvDim * MemoryLayout<Float16>.stride+ try copyPrefillKVToCache(commandBuffer: cb,+ kv: kv,+ layer: L,+ startPosition: startPosition,+ tokenCount: t,+ keySource: scratch.kStage,+ valueSource: scratch.vStage,+ bytesPerToken: bytes / t)+ }+ if let tqKV = turboQuantKV,+ let tqQuant = turboQuantQuant,+ let layerLayout = tqKV.turboQuantLayout(layer: L) {+ let whtParams = TurboQuantWHTParams(numHeads: UInt32(numKVHeads),+ layer: UInt32(L),+ rotationSeed: Self.turboQuantRotationSeed,+ applyRotation: true)+ let keyWriteParams = TurboQuantKVWriteParams(+ d: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ roleLayout: layerLayout.key,+ tokenBase: UInt32(startPosition))+ let keyBulk = TurboQuantKVBulkWriteParams(+ kv: keyWriteParams,+ tokenCount: t,+ dstTokenBase: startPosition,+ cacheTokenCapacity: maxContext,+ sourceTokenStrideElements: kvDim)+ let keyBuffer = tqKV.quantizedKeyBuffer(layer: L, validTokenCount: maxContext)+ try tqQuant.encodeKVWriteWHTBulk(commandBuffer: cb,+ x: scratch.kStage,+ cache: keyBuffer,+ params: keyBulk,+ whtParams: whtParams)++ let valueWriteParams = TurboQuantKVWriteParams(+ d: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ roleLayout: layerLayout.value,+ tokenBase: UInt32(startPosition))+ let valueBulk = TurboQuantKVBulkWriteParams(+ kv: valueWriteParams,+ tokenCount: t,+ dstTokenBase: startPosition,+ cacheTokenCapacity: maxContext,+ sourceTokenStrideElements: kvDim)+ let valueBuffer = tqKV.quantizedValueBuffer(layer: L, validTokenCount: maxContext)+ try tqQuant.encodeKVWriteWHTBulk(commandBuffer: cb,+ x: scratch.vStage,+ cache: valueBuffer,+ params: valueBulk,+ whtParams: whtParams)+ }++ let params = PrefillAttentionParams(+ startPosition: UInt32(startPosition),+ queryCount: UInt32(t),+ headDim: UInt32(headDim),+ numQHeads: UInt32(cfg.numHeads),+ numKVHeads: UInt32(numKVHeads),+ kvValidCount: UInt32(startPosition + t),+ slidingWindow: isFull ? UInt32(startPosition + t) : UInt32(cfg.slidingWindow),+ kvTokenStrideElements: UInt32(kvDim),+ qTokenStrideElements: UInt32(qDim),+ oTokenStrideElements: UInt32(qDim),+ scale: 1.0)+ if let kv {+ let keyBuffer = kv.keyBuffer(layer: L, validTokenCount: startPosition + t)+ let valueBuffer = kv.valueBuffer(layer: L, validTokenCount: startPosition + t)+ let ringCapacity = kv.ringCapacity(layer: L)+ let activeRingCapacity = ringCapacity > 0 && startPosition + t > ringCapacity+ ? UInt32(ringCapacity)+ : 0+ prefillAttention.encodeCausal(commandBuffer: cb,+ q: scratch.q,+ k: keyBuffer,+ v: valueBuffer,+ out: scratch.attentionOutput,+ params: params,+ kvRingCapacity: activeRingCapacity)+ } else if let tqKV = turboQuantKV,+ let layerLayout = tqKV.turboQuantLayout(layer: L) {+ let keyBuffer = tqKV.quantizedKeyBuffer(+ layer: L,+ validTokenCount: startPosition + t)+ let valueBuffer = tqKV.quantizedValueBuffer(+ layer: L,+ validTokenCount: startPosition + t)+ let tqParams = PrefillTurboQuantAttentionParams(+ prefill: params,+ layer: UInt32(L),+ rotationSeed: Self.turboQuantRotationSeed,+ keyLayout: layerLayout.key,+ valueLayout: layerLayout.value)+ prefillAttention.encodeTurboQuantCausal(commandBuffer: cb,+ q: scratch.q,+ keyCache: keyBuffer,+ valueCache: valueBuffer,+ out: scratch.attentionOutput,+ params: tqParams)+ } else {+ throw PrefillError.chunkedUnsupported(+ "chunked prefill attention requires fp16 or packed TurboQuant KV")+ }+ encodeInt4Projection(commandBuffer: cb,+ family: .o,+ weights: views.o,+ x: scratch.attentionOutput,+ y: scratch.h1,+ rows: D,+ columns: qDim,+ tokenCount: t,+ xStrideElements: qDim,+ yStrideElements: D)+ prefillPostAttention.encode(commandBuffer: cb,+ hidden: scratch.hidden,+ attn: scratch.h1,+ denseX: scratch.denseX,+ routedX: scratch.routedX,+ routerX: scratch.routerX,+ postAttentionWeight: views.postAttention.buffer,+ postAttentionWeightOffset: Int(views.postAttention.offset),+ preFFNWeight: views.preFFN.buffer,+ preFFNWeightOffset: Int(views.preFFN.offset),+ preFFN2Weight: views.preFFN2.buffer,+ preFFN2WeightOffset: Int(views.preFFN2.offset),+ queryCount: UInt32(t),+ d: UInt32(D),+ hiddenStrideElements: UInt32(D),+ attnStrideElements: UInt32(D),+ denseStrideElements: UInt32(D),+ routedStrideElements: UInt32(D),+ routerStrideElements: UInt32(D),+ eps: eps)+ prefillRouter.encodeGemma4Block(+ commandBuffer: cb,+ weights: views.router.buffer,+ weightsOffset: Int(views.router.offset),+ scales: views.router.buffer,+ scalesOffset: Int(views.router.scaleOffset),+ biases: views.router.buffer,+ biasesOffset: Int(views.router.biasOffset),+ hidden: scratch.routerX,+ effectiveScale: effectiveScaleBuffers[L],+ perExpertScale: views.routerPerExpertScale.buffer,+ perExpertScaleOffset: Int(views.routerPerExpertScale.offset),+ outIndices: scratch.routeIDs,+ outWeights: scratch.routeWeights,+ queryCount: UInt32(t),+ numExperts: UInt32(cfg.numExperts),+ d: UInt32(D),+ topK: UInt32(cfg.topKExperts),+ hiddenStrideElements: UInt32(D))++ cb.commit()+ waitForCompletion(cb)+ if let error = cb.error {+ throw error+ }++ let routeCount = t * cfg.topKExperts+ let idPtr = scratch.routeIDs.contents()+ .bindMemory(to: UInt32.self, capacity: routeCount)+ let weightPtr = scratch.routeWeights.contents()+ .bindMemory(to: Float16.self, capacity: routeCount)+ var routeIDs = [UInt32]()+ routeIDs.reserveCapacity(routeCount)+ var routeWeights = [Float16]()+ routeWeights.reserveCapacity(routeCount)+ for i in 0..<routeCount {+ routeIDs.append(min(idPtr[i], UInt32(cfg.numExperts - 1)))+ routeWeights.append(weightPtr[i])+ }+ let pairs = PrefillRouter.makeTokenExpertPairs(indices: routeIDs,+ weights: routeWeights,+ queryCount: t,+ topK: cfg.topKExperts)+ let schedulerConfig = Self.prefillRoutedTileSchedulerConfig+ let routeTileExpertCount: Int+ if let slotCount = model.routedExpertCacheSlotCount(layer: L) {+ guard schedulerConfig.fitsSlotBudget(slotCount: slotCount) else {+ throw PrefillError.chunkedUnsupported(+ "prefill routed tile depth \(schedulerConfig.maxPendingDepth) with \(schedulerConfig.tileExperts) experts/tile needs \((schedulerConfig.maxPendingDepth + 1) * schedulerConfig.tileExperts) slots, has \(slotCount)")+ }+ routeTileExpertCount = min(schedulerConfig.tileExperts, slotCount)+ } else {+ routeTileExpertCount = schedulerConfig.tileExperts+ }+ let routes = try PrefillMoEGrouping.groupTokenExpertPairs(+ pairs,+ queryCount: t,+ topK: cfg.topKExperts,+ numExperts: cfg.numExperts,+ tileExpertCount: routeTileExpertCount,+ expertSortKeys: model.routedExpertPhysicalOffsets(layer: L))++ guard let sharedCB = ctx.queue.makeCommandBuffer() else {+ throw ModelError.residentBufferWrapFailed+ }+ let sharedProj = sharedExpertProjections[L]+ try prefillSharedExpert.encodeBlock(commandBuffer: sharedCB,+ x: scratch.denseX,+ y: scratch.h1,+ gate: sharedProj.gate,+ up: sharedProj.up,+ down: sharedProj.down,+ scratchAct: scratch.sharedActScratch,+ queryCount: t,+ d: D,+ intermediate: cfg.intermediateSize,+ xStrideElements: D,+ yStrideElements: D)+ prefillRMS.encodeBF16W(commandBuffer: sharedCB,+ x: scratch.h1,+ weight: sharedProj.postF1.buffer,+ weightOffset: Int(sharedProj.postF1.offset),+ out: scratch.h1,+ t: UInt32(t),+ d: UInt32(D),+ eps: eps)+ sharedCB.commit()+ waitForCompletion(sharedCB)+ if let error = sharedCB.error {+ throw error+ }++ let metadata = try prefillGroupedMoE.makeStreamedMetadataBuffers(+ device: ctx.device,+ routes: routes)+ let routedOffsets = model.routedExpertOffsets(layer: L)+ struct PendingPrefillTile {+ let tileIndex: Int+ let commandBuffer: MTLCommandBuffer+ let fetch: PrefillStreamedTileFetchResult+ let argumentBuffer: PrefillStreamedTileArgumentBuffer+ }+ var pendingTiles: [PendingPrefillTile] = []+ var tileLifetime = PrefillStreamedTileSlotLifetime()+ func drainOldestPendingTile() throws {+ guard !pendingTiles.isEmpty else { return }+ let pending = pendingTiles.removeFirst()+ withExtendedLifetime((pending.fetch, pending.argumentBuffer)) {+ waitForCompletion(pending.commandBuffer)+ }+ if let error = pending.commandBuffer.error {+ throw error+ }+ if !pending.fetch.plannedMissSlots.isEmpty {+ try tileLifetime.complete(tileIndex: pending.tileIndex)+ }+ }++ let routedTileScheduler = PrefillRoutedTileScheduler(config: schedulerConfig)+ for (tileIndex, tile) in routes.tiles.enumerated() {+ let expertIDs = try PrefillStreamedTileBinding.expertIDs(+ forTile: tileIndex,+ routes: routes)+ var plannedFetch: RoutedExpertFetchPlan?+ if !pendingTiles.isEmpty {+ let pendingAssignedSlots = pendingTiles.flatMap(\.fetch.plannedAssignedSlots)+ if !pendingAssignedSlots.isEmpty {+ let pendingSlots = Set(pendingAssignedSlots)+ let plan = try model.planRoutedExpertsIfPossible(+ layer: L,+ experts: expertIDs,+ avoidingSlots: pendingSlots)+ let decision = routedTileScheduler.decide(+ PrefillRoutedTileSchedulerInput(+ hasPendingTile: true,+ pendingDepth: pendingTiles.count,+ pendingAssignedSlots: pendingAssignedSlots,+ avoidingSlotPlanAvailable: plan != nil))+ switch decision {+ case .prefetchNext:+ guard let plan else {+ throw ModelError.indexCorrupt(+ detail: "routed tile scheduler requested missing plan")+ }+ plannedFetch = plan+ case .drainBeforeIssue:+ try drainOldestPendingTile()+ case .issueWithoutPending:+ throw ModelError.indexCorrupt(+ detail: "routed tile scheduler ignored pending tile")+ }+ } else {+ let decision = routedTileScheduler.decide(+ PrefillRoutedTileSchedulerInput(+ hasPendingTile: true,+ pendingDepth: pendingTiles.count,+ pendingAssignedSlots: [],+ avoidingSlotPlanAvailable: false))+ switch decision {+ case .drainBeforeIssue:+ try drainOldestPendingTile()+ case .issueWithoutPending, .prefetchNext:+ throw ModelError.indexCorrupt(+ detail: "routed tile scheduler failed to drain empty-slot pending tile")+ }+ }+ } else {+ let decision = routedTileScheduler.decide(+ PrefillRoutedTileSchedulerInput(+ hasPendingTile: false,+ pendingAssignedSlots: [],+ avoidingSlotPlanAvailable: false))+ switch decision {+ case .issueWithoutPending:+ break+ case .prefetchNext, .drainBeforeIssue:+ throw ModelError.indexCorrupt(+ detail: "routed tile scheduler requested pending action without pending tile")+ }+ }+ let fetch = try await PrefillStreamedTileBinding.fetchBindingForTile(+ model: model,+ layer: L,+ tileIndex: tileIndex,+ routes: routes,+ plannedFetch: plannedFetch,+ avoidingSlots: Set(pendingTiles.flatMap(\.fetch.plannedAssignedSlots)))+ try fetch.binding.validateCoversPairs(routes.sortedPairs,+ pairStart: Int(tile.pairStart),+ pairCount: Int(tile.pairCount))+ if !fetch.plannedMissSlots.isEmpty {+ try tileLifetime.begin(tileIndex: tileIndex,+ plannedSlots: fetch.plannedMissSlots)+ }+ let argumentBuffer = try prefillGroupedMoE.makeStreamedArgumentBuffer(+ device: ctx.device,+ binding: fetch.binding)+ let streamedParams = PrefillGroupedRoutedMoEStreamedParams(+ pairStart: tile.pairStart,+ pairCount: tile.pairCount,+ d: UInt32(D),+ routedIntermediate: UInt32(cfg.moeIntermediateSize),+ topK: UInt32(cfg.topKExperts),+ hiddenStrideElements: UInt32(D),+ binding: fetch.binding,+ offsets: routedOffsets)+ guard let tileCB = ctx.queue.makeCommandBuffer() else {+ throw ModelError.residentBufferWrapFailed+ }+ _ = prefillGroupedMoE.encodeStreamedBatched(+ commandBuffer: tileCB,+ hidden: scratch.routedX,+ sortedPairs: metadata.sortedPairs,+ routePartials: scratch.routePartials,+ gateUpActScratch: scratch.routedGateUpActScratch,+ downScratch: scratch.routedDownScratch,+ argumentBuffer: argumentBuffer,+ binding: fetch.binding,+ params: streamedParams,+ pairMicrobatchRows: scratch.layout.routedPairMicrobatchRows)+ tileCB.commit()+ pendingTiles.append(PendingPrefillTile(tileIndex: tileIndex,+ commandBuffer: tileCB,+ fetch: fetch,+ argumentBuffer: argumentBuffer))+ while pendingTiles.count > schedulerConfig.maxPendingDepth {+ try drainOldestPendingTile()+ }+ }+ while !pendingTiles.isEmpty {+ try drainOldestPendingTile()+ }+ guard let tailCB = ctx.queue.makeCommandBuffer() else {+ throw ModelError.residentBufferWrapFailed+ }+ prefillMoE.encodeReduceTokenMajor(commandBuffer: tailCB,+ routePartials: scratch.routePartials,+ routeWeights: scratch.routeWeights,+ h2: scratch.h2,+ queryCount: UInt32(t),+ topK: UInt32(cfg.topKExperts),+ d: UInt32(D))+ let scalarBits = views.layerScalar.buffer.contents()+ .advanced(by: Int(views.layerScalar.offset))+ .assumingMemoryBound(to: UInt16.self)[0]+ prefillLayerTail.encode(commandBuffer: tailCB,+ h2: scratch.h2,+ h1: scratch.h1,+ hidden: scratch.hidden,+ postFFN2Weight: views.postFFN2.buffer,+ postFFN2WeightOffset: Int(views.postFFN2.offset),+ postFFNWeight: views.postFFN.buffer,+ postFFNWeightOffset: Int(views.postFFN.offset),+ queryCount: UInt32(t),+ d: UInt32(D),+ h2StrideElements: UInt32(D),+ h1StrideElements: UInt32(D),+ hiddenStrideElements: UInt32(D),+ eps: eps,+ layerScalar: Quantization.bf16ToFloat(scalarBits))+ tailCB.commit()+ withExtendedLifetime(metadata) {+ waitForCompletion(tailCB)+ }+ if let error = tailCB.error {+ throw error+ }+ if L + 1 < cfg.numLayers {+ guard let nextCB = ctx.queue.makeCommandBuffer() else {+ throw ModelError.residentBufferWrapFailed+ }+ cb = nextCB+ }+ continue+ }++ if writeFinalHead {+ let finalNorm = model.finalNorm+ let lm = model.lmHead+ guard let finalCB = ctx.queue.makeCommandBuffer() else {+ throw ModelError.residentBufferWrapFailed+ }+ if outputMode == .greedyIfAvailable, useFusedGreedyHead {+ fusionHead.encodeGreedyDecode(+ commandBuffer: finalCB,+ hidden: scratch.hidden,+ hiddenOffset: (t - 1) * D * MemoryLayout<Float16>.stride,+ normWeight: finalNorm.buffer,+ normOffset: Int(finalNorm.offset),+ weights: lm.buffer,+ weightsOffset: Int(lm.offset),+ scales: lm.buffer,+ scalesOffset: Int(lm.scaleOffset),+ biases: lm.buffer,+ biasesOffset: Int(lm.biasOffset),+ outToken: greedyTokenBuf,+ d: UInt32(D),+ vocab: UInt32(cfg.vocabSize),+ rmsEps: eps)+ } else {+ prefillFinalRowHead.encodeLogits(commandBuffer: finalCB,+ hiddenBlock: scratch.hidden,+ row: t - 1,+ rowStrideElements: D,+ normWeight: finalNorm.buffer,+ normWeightOffset: Int(finalNorm.offset),+ weights: lm.buffer,+ weightsOffset: Int(lm.offset),+ scales: lm.buffer,+ scalesOffset: Int(lm.scaleOffset),+ biases: lm.buffer,+ biasesOffset: Int(lm.biasOffset),+ logits: logits,+ d: UInt32(D),+ vocab: UInt32(cfg.vocabSize),+ rmsEps: eps)+ }+ finalCB.commit()+ waitForCompletion(finalCB)+ if let error = finalCB.error {+ throw error+ }+ if outputMode == .greedyIfAvailable, useFusedGreedyHead {+ lastGreedyToken = greedyTokenBuf.contents().load(as: UInt32.self)+ }+ }++ kv?.advance(by: tokens.count)+ turboQuantKV?.advance(by: tokens.count)+ prefillChunkState.markCommitted()+ }++ private func produceToken(token: Int32,+ position: Int,+ into logits: MTLBuffer,+ emitHead: Bool,+ outputMode: PrefillOutputMode) async throws {+ let kvPosition = kv?.position ?? turboQuantKV?.position ?? 0+ guard kvPosition == position else {+ throw PrefillError.prefillCursorMismatch(+ "produce cursor \(kvPosition) != position \(position)")+ }+ guard position < maxContext else {+ throw PrefillError.prefillCursorMismatch(+ "produce position \(position) exceeds maxContext \(maxContext)")+ }+ let D = UInt32(cfg.hiddenSize)+ let FmoE = UInt32(cfg.moeIntermediateSize)+ let eps: Float = 1e-6+ let sqrtHidden = Float(cfg.hiddenSize).squareRoot()+ struct PendingRoutedCommand {+ let cb: MTLCommandBuffer+ let sharedCB: MTLCommandBuffer?+ let phase1HitCB: MTLCommandBuffer?+ let encodeAndCommitNanos: UInt64+ }+ var pendingRoutedCommand: PendingRoutedCommand?++ func finishPendingRoutedCommand(_ pending: PendingRoutedCommand,+ waitIfNeeded: Bool) {+ if waitIfNeeded {+ func wait(_ cb: MTLCommandBuffer) {+ waitForCompletion(cb)+ }+ if let sharedCB = pending.sharedCB {+ wait(sharedCB)+ }+ if let phase1HitCB = pending.phase1HitCB {+ wait(phase1HitCB)+ }+ wait(pending.cb)+ } else if let err = pending.cb.error {+ print("CB error: \(err)")+ }+ if let sharedCB = pending.sharedCB {+ if let err = sharedCB.error {+ print("CB error: \(err)")+ }+ }+ if let phase1HitCB = pending.phase1HitCB,+ let err = phase1HitCB.error {+ print("CB error: \(err)")+ }+ totalCb2Nanos &+= pending.encodeAndCommitNanos+ }++ func writeActiveSlots(_ slots: [UInt32], into buffer: MTLBuffer) {+ let ptr = buffer.contents().assumingMemoryBound(to: UInt32.self)+ for i in 0..<slots.count { ptr[i] = slots[i] }+ }++ // Embed lookup + sqrt(H) fused.+ let emb = model.embedding+ do {+ runSync { cb in+ embedInt4.encode(commandBuffer: cb,+ table: emb.buffer, tableOffset: Int(emb.offset),+ scales: emb.buffer, scalesOffset: Int(emb.scaleOffset),+ biases: emb.buffer, biasesOffset: Int(emb.biasOffset),+ out: hidden,+ tokenId: UInt32(bitPattern: token),+ d: D,+ outScale: sqrtHidden)+ }+ }++ for L in 0..<cfg.numLayers {+ let isFull = cfg.fullAttentionLayerMask[L] != 0+ let headDimL = isFull ? cfg.fullHeadDim : cfg.headDim+ let numKVL = isFull ? cfg.numFullKVHeads : cfg.numKVHeads+ let qDim = UInt32(cfg.numHeads * headDimL)+ let kvDim = UInt32(numKVL * headDimL)+ let kSlot = kv?.kSlot(layer: L, position: position) ?? (buffer: kStage, offset: 0)+ let vSlot = kv?.vSlot(layer: L, position: position) ?? (buffer: vStage, offset: 0)+ let seqLen = UInt32(position + 1)++ let inNorm = try model.inputNorm(layer: L)+ let q = try model.qProj(layer: L)+ let k = try model.kProj(layer: L)+ // v_proj only exists on SWA layers; full layers reuse k_proj.+ let vProj = isFull ? k : (try model.vProj(layer: L))+ let o = try model.oProj(layer: L)+ let postAttn = try model.postAttnNorm(layer: L)+ let qNorm = try model.qNorm(layer: L)+ let kNorm = try model.kNorm(layer: L)+ let preFFN = try model.preFFN(layer: L)+ let preFFN2 = try model.preFFN2(layer: L)+ let sharedProj = sharedExpertProjections[L]+ let postF2 = try model.postFFN2(layer: L)+ let postF = try model.postFFN(layer: L)+ let routerW = try model.router(layer: L)+ let perExpertScale = try model.routerPerExpertScale(layer: L)+ let layerScalarView = try model.layerScalar(layer: L)++ let tCb1Start = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ // Everything up to and including the router runs in a single CB:+ // the only reason to break is the CPU readback of router indices+ // needed to issue I/O for the routed-expert blobs.+ let gInputNorm: (MTLCommandBuffer) -> Void = { [self] cb in+ rms.encodeBF16W(commandBuffer: cb,+ x: hidden,+ weight: inNorm.buffer, weightOffset: Int(inNorm.offset),+ out: normed,+ d: D, eps: eps)+ }++ let gQKV: (MTLCommandBuffer) -> Void = { [self] cb in+ fusedQKVGEMV.encode(commandBuffer: cb,+ qWeights: q.buffer, qWeightsOffset: Int(q.offset),+ qScales: q.buffer, qScalesOffset: Int(q.scaleOffset),+ qBiases: q.buffer, qBiasesOffset: Int(q.biasOffset),+ kWeights: k.buffer, kWeightsOffset: Int(k.offset),+ kScales: k.buffer, kScalesOffset: Int(k.scaleOffset),+ kBiases: k.buffer, kBiasesOffset: Int(k.biasOffset),+ vWeights: vProj.buffer, vWeightsOffset: Int(vProj.offset),+ vScales: vProj.buffer, vScalesOffset: Int(vProj.scaleOffset),+ vBiases: vProj.buffer, vBiasesOffset: Int(vProj.biasOffset),+ x: normed,+ qOut: qScratch,+ kOut: kSlot.buffer, kOutOffset: kSlot.offset,+ vOut: vSlot.buffer, vOutOffset: vSlot.offset,+ qRows: qDim,+ kvRows: kvDim,+ n: D)+ }++ let gQKVEpilogue: (MTLCommandBuffer) -> Void = { [self] cb in+ let rotated = isFull+ ? UInt32(Double(cfg.fullHeadDim) * cfg.partialRotaryFactor / 2.0)+ : UInt32(headDimL / 2)+ fusedQKVEpilogue.encode(commandBuffer: cb,+ q: qScratch,+ k: kSlot.buffer,+ kOffset: kSlot.offset,+ v: vSlot.buffer,+ vOffset: vSlot.offset,+ qWeight: qNorm.buffer,+ qWeightOffset: Int(qNorm.offset),+ kWeight: kNorm.buffer,+ kWeightOffset: Int(kNorm.offset),+ headDim: UInt32(headDimL),+ numQHeads: UInt32(cfg.numHeads),+ numKVHeads: UInt32(numKVL),+ position: UInt32(position),+ theta: isFull ? Float(cfg.fullRopeTheta) : Float(cfg.ropeTheta),+ rotatedPairs: rotated,+ eps: eps)+ }++ let gTurboQuantKVWrite: (MTLCommandBuffer) -> Void = { [self] cb in+ guard let tqKV = turboQuantKV,+ let tqQuant = turboQuantQuant,+ let layerLayout = tqKV.turboQuantLayout(layer: L) else {+ return+ }++ let whtParams = TurboQuantWHTParams(numHeads: UInt32(numKVL),+ layer: UInt32(L),+ rotationSeed: Self.turboQuantRotationSeed,+ applyRotation: true)++ let keySlot = tqKV.quantizedKeySlot(layer: L, position: position)+ let keyWriteParams = TurboQuantKVWriteParams(+ d: UInt32(headDimL),+ numHeads: UInt32(numKVL),+ roleLayout: layerLayout.key,+ tokenBase: UInt32(position))+ tqQuant.encodeKVWriteWHT(commandBuffer: cb,+ x: kSlot.buffer,+ xOffset: kSlot.offset,+ cache: keySlot.buffer,+ cacheOffset: keySlot.offset,+ params: keyWriteParams,+ whtParams: whtParams,+ pairs: numKVL)++ let valueSlot = tqKV.quantizedValueSlot(layer: L, position: position)+ let valueWriteParams = TurboQuantKVWriteParams(+ d: UInt32(headDimL),+ numHeads: UInt32(numKVL),+ roleLayout: layerLayout.value,+ tokenBase: UInt32(position))+ tqQuant.encodeKVWriteWHT(commandBuffer: cb,+ x: vSlot.buffer,+ xOffset: vSlot.offset,+ cache: valueSlot.buffer,+ cacheOffset: valueSlot.offset,+ params: valueWriteParams,+ whtParams: whtParams,+ pairs: numKVL)+ }++ let gAttention: (MTLCommandBuffer) -> Void = { [self] cb in+ if useTurboQuantKV,+ let tqKV = turboQuantKV,+ let layerLayout = tqKV.turboQuantLayout(layer: L) {+ let keyBuffer = tqKV.quantizedKeyBuffer(+ layer: L,+ validTokenCount: Int(seqLen))+ let valueBuffer = tqKV.quantizedValueBuffer(+ layer: L,+ validTokenCount: Int(seqLen))+ let kvStart: UInt32 = isFull+ ? 0+ : (seqLen > UInt32(cfg.slidingWindow)+ ? seqLen - UInt32(cfg.slidingWindow)+ : 0)+ let params = AttentionTurboQuantKVParams(+ headDim: UInt32(headDimL),+ numQHeads: UInt32(cfg.numHeads),+ numKVHeads: UInt32(numKVL),+ seqLen: seqLen,+ kvStart: kvStart,+ scale: 1.0,+ layer: UInt32(L),+ rotationSeed: Self.turboQuantRotationSeed,+ keyLayout: layerLayout.key,+ valueLayout: layerLayout.value)+ attention.encodeTurboQuantSplit(+ commandBuffer: cb,+ q: qScratch,+ keyCache: keyBuffer,+ valueCache: valueBuffer,+ out: attnOut,+ params: params)+ return+ }++ guard kv != nil else {+ preconditionFailure("FP16 attention requires an FP16 KV cache")+ }+ if isFull {+ attention.encodeFull(commandBuffer: cb,+ q: qScratch,+ k: kSlot.buffer, kOffset: 0,+ v: vSlot.buffer, vOffset: 0,+ out: attnOut,+ headDim: UInt32(headDimL),+ numQHeads: UInt32(cfg.numHeads),+ numKVHeads: UInt32(numKVL),+ seqLen: seqLen,+ scale: 1.0)+ } else {+ let ringCapacity = kv?.ringCapacity(layer: L) ?? 0+ let activeRingCapacity = ringCapacity > 0 && Int(seqLen) > ringCapacity+ ? UInt32(ringCapacity)+ : 0+ attention.encodeSWA(commandBuffer: cb,+ q: qScratch,+ k: kSlot.buffer, kOffset: 0,+ v: vSlot.buffer, vOffset: 0,+ out: attnOut,+ headDim: UInt32(headDimL),+ numQHeads: UInt32(cfg.numHeads),+ numKVHeads: UInt32(numKVL),+ seqLen: seqLen,+ window: UInt32(cfg.slidingWindow),+ scale: 1.0,+ ringCapacity: activeRingCapacity)+ }+ }+ let gOProj: (MTLCommandBuffer) -> Void = { [self] cb in+ int4.encode(commandBuffer: cb,+ weights: o.buffer, weightsOffset: Int(o.offset),+ scales: o.buffer, scalesOffset: Int(o.scaleOffset),+ biases: o.buffer, biasesOffset: Int(o.biasOffset),+ x: attnOut, y: oOut, m: D, n: qDim)+ }++ let gPostAttnSetup: (MTLCommandBuffer) -> Void = { [self] cb in+ fusedPostAttentionSetup.encode(commandBuffer: cb,+ hidden: hidden,+ attn: oOut,+ denseX: denseX,+ routedX: routedX,+ routerX: routerInput,+ postAttentionWeight: postAttn.buffer,+ postAttentionWeightOffset: Int(postAttn.offset),+ preFFNWeight: preFFN.buffer,+ preFFNWeightOffset: Int(preFFN.offset),+ preFFN2Weight: preFFN2.buffer,+ preFFN2WeightOffset: Int(preFFN2.offset),+ d: D,+ eps: eps)+ }++ let gRouter: (MTLCommandBuffer) -> Void = { [self] cb in+ moe.encodeRouterGemma4(commandBuffer: cb,+ weights: routerW.buffer, weightsOffset: Int(routerW.offset),+ scales: routerW.buffer, scalesOffset: Int(routerW.scaleOffset),+ biases: routerW.buffer, biasesOffset: Int(routerW.biasOffset),+ hidden: routerInput,+ effectiveScale: effectiveScaleBuffers[L],+ perExpertScale: perExpertScale.buffer,+ perExpertScaleOffset: Int(perExpertScale.offset),+ outIndices: outIndices, outWeights: outWeights,+ numExperts: UInt32(cfg.numExperts), d: D, topK: UInt32(cfg.topKExperts))+ }++ let cb = ctx.queue.makeCommandBuffer()!+ gInputNorm(cb)+ gQKV(cb)+ gQKVEpilogue(cb)+ if useTurboQuantKV {+ gTurboQuantKVWrite(cb)+ }+ gAttention(cb)+ gOProj(cb)+ gPostAttnSetup(cb)+ gRouter(cb)+ cb.commit()+ let tWait = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ waitForCompletion(cb)+ let waitNanos = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tWait+ if let pending = pendingRoutedCommand {+ finishPendingRoutedCommand(pending, waitIfNeeded: false)+ pendingRoutedCommand = nil+ }+ totalCb1Nanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tCb1Start - waitNanos++ // CPU readback to fetch routed-expert blobs from disk.+ let idxPtr = outIndices.contents().bindMemory(to: UInt32.self,+ capacity: cfg.topKExperts)+ var experts = [Int](repeating: 0, count: cfg.topKExperts)+ for i in 0..<cfg.topKExperts {+ experts[i] = min(Int(idxPtr[i]), cfg.numExperts - 1)+ }++ let routedOffsets = model.routedExpertOffsets(layer: L)+ let topK = UInt32(cfg.topKExperts)+ let canPlanPhase1HitSplit =+ cfg.topKExperts <= MoE.maxStreamedExperts+ let plannedFetch = canPlanPhase1HitSplit+ ? try model.planRoutedExperts(layer: L, experts: experts)+ : nil+ var phase1HitCB: MTLCommandBuffer?+ var phase1HitSplitArgBuf: MTLBuffer?+ var phase1HitSplitRoutedBufs: [MTLBuffer] = []+ var phase1HitSlots: [UInt32] = []+ var phase1MissSlots: [UInt32] = []++ if let plan = plannedFetch {+ let missSet = Set(plan.misses)+ phase1HitSlots = (0..<cfg.topKExperts)+ .filter { !missSet.contains($0) }+ .map { UInt32($0) }+ phase1MissSlots = plan.misses.map { UInt32($0) }+ }+ func encodeRoutedPhase1Full(+ _ cb: MTLCommandBuffer,+ argBuf: MTLBuffer,+ routedBufs: [MTLBuffer]+ ) {+ moe.encodeRoutedPersistentPhase1U16Load(commandBuffer: cb,+ routedArgBuffer: argBuf,+ routedBlobs: routedBufs,+ routedOffsets: routedOffsets,+ x: routedX,+ acts: moeActs,+ d: D,+ f: FmoE,+ topK: topK)+ }++ func encodeRoutedPhase1Subset(+ _ cb: MTLCommandBuffer,+ argBuf: MTLBuffer,+ routedBufs: [MTLBuffer],+ activeSlots: MTLBuffer,+ activeSlotIndices: [UInt32],+ activeCount: UInt32+ ) {+ moe.encodeRoutedPersistentPhase1SubsetU16Load(+ commandBuffer: cb,+ routedArgBuffer: argBuf,+ routedBlobs: routedBufs,+ routedOffsets: routedOffsets,+ x: routedX,+ acts: moeActs,+ activeSlots: activeSlots,+ activeSlotIndices: activeSlotIndices,+ activeCount: activeCount,+ d: D,+ f: FmoE,+ topK: topK)+ }++ if let plan = plannedFetch,+ plan.hits > 0,+ !plan.misses.isEmpty {+ let plannedBlobs = try model.routedExpertBuffers(for: plan)+ phase1HitSplitRoutedBufs = plannedBlobs.map { $0.buffer }+ phase1HitSplitArgBuf = moe.makeRoutedArgumentBuffer(+ routedBlobs: phase1HitSplitRoutedBufs,+ topK: topK)+ if let argBuf = phase1HitSplitArgBuf, plan.hits > 0, !plan.misses.isEmpty {+ writeActiveSlots(phase1HitSlots, into: moeHitActiveSlots)+ let cb = ctx.queue.makeCommandBuffer()!+ encodeRoutedPhase1Subset(+ cb,+ argBuf: argBuf,+ routedBufs: phase1HitSplitRoutedBufs,+ activeSlots: moeHitActiveSlots,+ activeSlotIndices: phase1HitSlots,+ activeCount: UInt32(phase1HitSlots.count))+ phase1HitCB = cb+ }+ }++ // The shared dense MLP depends only on denseX, not on the routed+ // experts. Commit it without waiting so its GPU work overlaps the+ // routed-expert pread. The routed CB follows it on the same queue,+ // so the combine sees h1Buf.+ let gSharedFFN: (MTLCommandBuffer) -> Void = { [self] cb in+ try! shared.encode(commandBuffer: cb,+ x: denseX,+ gate: sharedProj.gate,+ up: sharedProj.up,+ down: sharedProj.down,+ y: h1Buf,+ scratchAct: denseScratchA)+ }+ let gSharedNorm: (MTLCommandBuffer) -> Void = { [self] cb in+ rms.encodeBF16W(commandBuffer: cb, x: h1Buf,+ weight: sharedProj.postF1.buffer,+ weightOffset: Int(sharedProj.postF1.offset),+ out: h1Buf, d: D, eps: eps)+ }+ let sharedCB = ctx.queue.makeCommandBuffer()!+ gSharedFFN(sharedCB)+ gSharedNorm(sharedCB)+ sharedCB.commit()+ if let cb = phase1HitCB {+ cb.commit()+ }+ if rdadviseEnabled && rdadvisePolicyMode != .off {+ let requestedMisses = plannedFetch?.misses.count ?? experts.count+ let estimatedAdviceBytes = try model.routedExpertAdviceByteEstimate(+ layer: L,+ missCount: requestedMisses)+ if let skipped = shouldSkipRDAdvice(position: position,+ requestedMisses: requestedMisses,+ estimatedBytes: estimatedAdviceBytes,+ canOverlapUsefulGPUWork: true) {+ recordRDAdvice(skipped, wallNanos: 0)+ } else {+ let tAdvice = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ let result: ExpertIOAdviceResult+ if let plannedFetch {+ result = try model.adviseRoutedExperts(plan: plannedFetch)+ } else {+ result = try model.adviseRoutedExperts(layer: L, experts: experts)+ }+ let wallNanos = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tAdvice+ recordRDAdvice(result, wallNanos: wallNanos)+ updateRDAdvicePolicy(after: result, position: position)+ }+ }++ // Routed-expert pread — overlaps the shared MLP GPU work above.+ let tIoStart = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ let blobs: [TensorView]+ if let plannedFetch {+ blobs = try await model.fetchRoutedExperts(plan: plannedFetch)+ } else {+ blobs = try await model.fetchRoutedExperts(layer: L, experts: experts)+ }+ let layerIo = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tIoStart+ totalIoNanos &+= layerIo+ let routedBufs = blobs.map { $0.buffer }+ let tCb2Start = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ let scalarPtr = layerScalarView.buffer.contents()+ .advanced(by: Int(layerScalarView.offset))+ .assumingMemoryBound(to: UInt16.self)+ let layerScalar = Quantization.bf16ToFloat(scalarPtr[0])++ let gTail: (MTLCommandBuffer) -> Void = { [self] cb in+ fusedTail.encode(commandBuffer: cb,+ h2: h2Buf,+ h1: h1Buf,+ hidden: hidden,+ postFFN2Weight: postF2.buffer,+ postFFN2WeightOffset: Int(postF2.offset),+ postFFNWeight: postF.buffer,+ postFFNWeightOffset: Int(postF.offset),+ d: D,+ eps: eps,+ layerScalar: layerScalar)+ }+ let routedCB = ctx.queue.makeCommandBuffer()!+ let splitArgBuf = phase1HitCB != nil && !phase1MissSlots.isEmpty+ ? phase1HitSplitArgBuf+ : nil+ let argBuf = splitArgBuf ?? moe.makeReusedRoutedArgumentBuffer(+ routedBlobs: routedBufs,+ topK: topK)+ if splitArgBuf != nil {+ writeActiveSlots(phase1MissSlots, into: moeMissActiveSlots)+ encodeRoutedPhase1Subset(+ routedCB,+ argBuf: argBuf,+ routedBufs: routedBufs,+ activeSlots: moeMissActiveSlots,+ activeSlotIndices: phase1MissSlots,+ activeCount: UInt32(phase1MissSlots.count))+ } else {+ encodeRoutedPhase1Full(routedCB,+ argBuf: argBuf,+ routedBufs: routedBufs)+ }+ moe.encodeRoutedPersistentPhase2Reduce(commandBuffer: routedCB,+ routedArgBuffer: argBuf,+ routedBlobs: routedBufs,+ routedOffsets: routedOffsets,+ acts: moeActs,+ routingWeights: outWeights,+ residual: zeroResidual,+ y: h2Buf,+ d: D,+ f: FmoE,+ topK: topK)+ gTail(routedCB)+ routedCB.commit()+ precondition(pendingRoutedCommand == nil,+ "routed command-buffer pipeline drained before queuing the next layer")+ pendingRoutedCommand = PendingRoutedCommand(+ cb: routedCB,+ sharedCB: sharedCB,+ phase1HitCB: phase1HitCB,+ encodeAndCommitNanos: clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tCb2Start)+ continue+ }+ if let pending = pendingRoutedCommand {+ finishPendingRoutedCommand(pending, waitIfNeeded: true)+ pendingRoutedCommand = nil+ }++ // The fused head skips the vocab buffer and leaves a greedy token in+ // greedyTokenBuf; the logits path writes the complete vector.+ let fNorm = model.finalNorm+ let lm = model.embedding+ let gFinalNorm: (MTLCommandBuffer) -> Void = { cb in+ self.rms.encodeBF16W(commandBuffer: cb, x: self.hidden,+ weight: fNorm.buffer, weightOffset: Int(fNorm.offset),+ out: self.normed, d: D, eps: eps)+ }+ let gLmHead: (MTLCommandBuffer) -> Void = { cb in+ self.int4.encode(commandBuffer: cb,+ weights: lm.buffer, weightsOffset: Int(lm.offset),+ scales: lm.buffer, scalesOffset: Int(lm.scaleOffset),+ biases: lm.buffer, biasesOffset: Int(lm.biasOffset),+ x: self.normed, y: logits, m: UInt32(self.cfg.vocabSize), n: D)+ }+ let gFusionHead: (MTLCommandBuffer) -> Void = { cb in+ self.fusionHead.encodeGreedyDecode(+ commandBuffer: cb,+ hidden: self.hidden,+ normWeight: fNorm.buffer, normOffset: Int(fNorm.offset),+ weights: lm.buffer, weightsOffset: Int(lm.offset),+ scales: lm.buffer, scalesOffset: Int(lm.scaleOffset),+ biases: lm.buffer, biasesOffset: Int(lm.biasOffset),+ outToken: self.greedyTokenBuf,+ d: D, vocab: UInt32(self.cfg.vocabSize),+ rmsEps: eps)+ }+ if emitHead {+ let useFusedHeadForThisToken = useFusedGreedyHead && outputMode == .greedyIfAvailable+ let tHead = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)+ if useFusedHeadForThisToken {+ runSync(gFusionHead)+ totalHeadFusedNanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tHead+ lastGreedyToken = greedyTokenBuf.contents().load(as: UInt32.self)+ } else {+ runSync { cb in+ gFinalNorm(cb)+ gLmHead(cb)+ }+ totalHeadNanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tHead+ }+ }++ kv?.advance()+ turboQuantKV?.advance()+ }++ private func runSync(_ body: (MTLCommandBuffer) -> Void) {+ let cb = ctx.queue.makeCommandBuffer()!+ body(cb)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ print("CB error: \(err)")+ }+ }++ private nonisolated func waitForCompletion(_ cb: MTLCommandBuffer) {+ cb.waitUntilCompleted()+ if let err = cb.error {+ print("CB error: \(err)")+ }+ }++}diff --git a/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swiftnew file mode 100644index 00000000..650b7daa--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift@@ -0,0 +1,305 @@+import Foundation+import Darwin+import Metal++/// Which attention variant a layer runs. Gemma 4 interleaves 25 sliding-window+/// layers with 5 full-attention layers. Sourced from+/// `ArchConfig.fullAttentionLayerMask`.+enum LayerKind: Sendable { case swa, full }++enum KVCacheStorageMode: Sendable, Equatable {+ case fp16+ case turboQuant(TurboQuantKVMode)+}++/// Per-layer FP16 K/V storage for the decode loop.+///+/// One K buffer and one V buffer per layer, allocated once in `init` — the+/// decode hot path never allocates. Linear storage sizes every layer for+/// `maxContext`; FP16 ring storage caps SWA layers to their physical capacity+/// while full-attention layers remain linear.+///+/// Full-attention layers share the raw `k_proj` output. K then runs scaled+/// per-head normalization plus RoPE, while V runs no-scale normalization and+/// skips RoPE. The cache buffers must therefore remain separate.+///+/// The K/V projection GEMV writes straight into the slot returned by+/// `kSlot`/`vSlot` (no separate `kv_write` kernel); the runner then norms ++/// optionally RoPE's each slot in place. `advance()` bumps the cursor once+/// both are written.+///+/// 8 GB rule: storage is bounded by per-layer physical capacity, allocated+/// once. `reset()` returns physical pages to the OS via `MADV_DONTNEED` so a+/// finished generation does not keep its KV resident into the next turn.+final class KVCacheManager {+ let config: ArchConfig+ let maxContext: Int+ let storageMode: KVCacheStorageMode+ let fp16RingEnabled: Bool++ private let kBuffers: [MTLBuffer]+ private let vBuffers: [MTLBuffer]+ private let quantizedKBuffers: [MTLBuffer]+ private let quantizedVBuffers: [MTLBuffer]+ private let turboQuantLayouts: [TurboQuantKVLayerLayout]+ private let strides: [Int] // bytes per token, per layer+ private let kinds: [LayerKind]+ private let capacityTokens: [Int]++ private(set) var position: Int = 0++ private static let fp16Size = 2++ init(device: MTLDevice,+ config: ArchConfig,+ maxContext: Int,+ storageMode: KVCacheStorageMode = .fp16,+ fp16RingEnabled: Bool = false,+ slidingWindow: Int? = nil,+ maxPrefillChunkTokens: Int = 128,+ fp16RingCapacityOverride: Int? = nil) throws {+ precondition(maxContext > 0, "maxContext must be positive")+ precondition(maxPrefillChunkTokens > 0, "maxPrefillChunkTokens must be positive")+ if case .turboQuant(.disabled) = storageMode {+ preconditionFailure("disabled TurboQuant mode cannot be used as a storage mode")+ }+ self.config = config+ self.maxContext = maxContext+ self.storageMode = storageMode+ let ringEnabled = storageMode == .fp16 && fp16RingEnabled+ self.fp16RingEnabled = ringEnabled++ let swaStride = config.numKVHeads * config.headDim * Self.fp16Size+ let fullStride = config.numFullKVHeads * config.fullHeadDim * Self.fp16Size+ let swaCapacity = min(maxContext,+ max(1, fp16RingCapacityOverride+ ?? ((slidingWindow ?? config.slidingWindow) + maxPrefillChunkTokens)))++ var ks: [MTLBuffer] = []+ var vs: [MTLBuffer] = []+ var qks: [MTLBuffer] = []+ var qvs: [MTLBuffer] = []+ var qls: [TurboQuantKVLayerLayout] = []+ var st: [Int] = []+ var kd: [LayerKind] = []+ var caps: [Int] = []+ ks.reserveCapacity(config.numLayers)+ vs.reserveCapacity(config.numLayers)+ qks.reserveCapacity(config.numLayers)+ qvs.reserveCapacity(config.numLayers)+ qls.reserveCapacity(config.numLayers)+ st.reserveCapacity(config.numLayers)+ kd.reserveCapacity(config.numLayers)+ caps.reserveCapacity(config.numLayers)++ for layer in 0..<config.numLayers {+ let isFull = config.fullAttentionLayerMask[layer] != 0+ let stride = isFull ? fullStride : swaStride+ let capacity = ringEnabled && !isFull ? swaCapacity : maxContext+ switch storageMode {+ case .fp16:+ let length = capacity * stride++ guard let kBuf = device.makeBuffer(length: length, options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ kBuf.label = "kv.K.layer\(layer)"+ ks.append(kBuf)++ guard let vBuf = device.makeBuffer(length: length, options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ vBuf.label = "kv.V.layer\(layer)"+ vs.append(vBuf)++ case .turboQuant(let mode):+ let layout = TurboQuantKVLayout.layer(mode: mode,+ config: config,+ layer: layer,+ capacity: maxContext)+ guard let kBuf = device.makeBuffer(length: maxContext * layout.key.bytesPerToken,+ options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ kBuf.label = "kv.tq.K.layer\(layer)"+ qks.append(kBuf)++ guard let vBuf = device.makeBuffer(length: maxContext * layout.value.bytesPerToken,+ options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ vBuf.label = "kv.tq.V.layer\(layer)"+ qvs.append(vBuf)+ qls.append(layout)+ }++ st.append(stride)+ kd.append(isFull ? .full : .swa)+ caps.append(capacity)+ }++ self.kBuffers = ks+ self.vBuffers = vs+ self.quantizedKBuffers = qks+ self.quantizedVBuffers = qvs+ self.turboQuantLayouts = qls+ self.strides = st+ self.kinds = kd+ self.capacityTokens = caps+ }++ /// Physical token capacity for `layer`. Ring-enabled SWA layers can be+ /// smaller than `maxContext`; full layers and ring-off storage stay linear.+ func capacity(layer: Int) -> Int { capacityTokens[layer] }++ func ringCapacity(layer: Int) -> Int {+ guard storageMode == .fp16, fp16RingEnabled, kinds[layer] == .swa else { return 0 }+ return capacityTokens[layer]+ }++ func turboQuantLayout(layer: Int) -> TurboQuantKVLayerLayout? {+ guard case .turboQuant = storageMode else { return nil }+ return turboQuantLayouts[layer]+ }++ /// Write target for this layer's K projection at `position`.+ func kSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {+ precondition(storageMode == .fp16, "FP16 K slots are unavailable for TurboQuant storage")+ validateRange(start: position, count: 1)+ return (kBuffers[layer], physicalSlot(layer: layer, position: position) * strides[layer])+ }++ /// Write target for this layer's V projection at `position`. It is distinct+ /// from `kSlot` because full layers normalize K and V differently and apply+ /// RoPE only to K.+ func vSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {+ precondition(storageMode == .fp16, "FP16 V slots are unavailable for TurboQuant storage")+ validateRange(start: position, count: 1)+ return (vBuffers[layer], physicalSlot(layer: layer, position: position) * strides[layer])+ }++ func kRange(layer: Int, start: Int, count: Int) -> (buffer: MTLBuffer, offset: Int, stride: Int) {+ precondition(storageMode == .fp16, "FP16 K ranges are unavailable for TurboQuant storage")+ validateRange(start: start, count: count)+ validateContiguousPhysicalRange(layer: layer, start: start, count: count)+ return (kBuffers[layer], physicalSlot(layer: layer, position: start) * strides[layer], strides[layer])+ }++ func vRange(layer: Int, start: Int, count: Int) -> (buffer: MTLBuffer, offset: Int, stride: Int) {+ precondition(storageMode == .fp16, "FP16 V ranges are unavailable for TurboQuant storage")+ validateRange(start: start, count: count)+ validateContiguousPhysicalRange(layer: layer, start: start, count: count)+ return (vBuffers[layer], physicalSlot(layer: layer, position: start) * strides[layer], strides[layer])+ }++ func keyBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {+ precondition(storageMode == .fp16, "FP16 K buffers are unavailable for TurboQuant storage")+ validateValidTokenCount(validTokenCount)+ return kBuffers[layer]+ }++ func valueBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {+ precondition(storageMode == .fp16, "FP16 V buffers are unavailable for TurboQuant storage")+ validateValidTokenCount(validTokenCount)+ return vBuffers[layer]+ }++ func quantizedKeySlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {+ let layout = requireTurboQuantLayout(layer: layer)+ validateRange(start: position, count: 1)+ return (quantizedKBuffers[layer], position * layout.key.bytesPerToken)+ }++ func quantizedValueSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {+ let layout = requireTurboQuantLayout(layer: layer)+ validateRange(start: position, count: 1)+ return (quantizedVBuffers[layer], position * layout.value.bytesPerToken)+ }++ func quantizedKeyBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {+ _ = requireTurboQuantLayout(layer: layer)+ validateValidTokenCount(validTokenCount)+ return quantizedKBuffers[layer]+ }++ func quantizedValueBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {+ _ = requireTurboQuantLayout(layer: layer)+ validateValidTokenCount(validTokenCount)+ return quantizedVBuffers[layer]+ }++ /// Advance the position cursor once the current token's K/V are written+ /// across all layers.+ func advance() { advance(by: 1) }++ func advance(by count: Int) {+ precondition(count >= 0, "advance count must be non-negative")+ precondition(position + count <= maxContext, "advance would exceed maxContext")+ position += count+ }++ /// Drop all cached positions and return physical pages to the OS.+ ///+ /// No buffer zeroing — the attention kernels read only `[0, validTokenCount]`,+ /// and `validTokenCount` is now 0. `MADV_DONTNEED` on the page-aligned span+ /// releases resident memory between turns; pages fault back in on next write.+ func reset() {+ position = 0+ let pageSize = Int(getpagesize())+ var advised = Set<ObjectIdentifier>()+ for layer in 0..<config.numLayers {+ switch storageMode {+ case .fp16:+ advise(kBuffers[layer], pageSize: pageSize, seen: &advised)+ advise(vBuffers[layer], pageSize: pageSize, seen: &advised)+ case .turboQuant:+ advise(quantizedKBuffers[layer], pageSize: pageSize, seen: &advised)+ advise(quantizedVBuffers[layer], pageSize: pageSize, seen: &advised)+ }+ }+ }++ private func requireTurboQuantLayout(layer: Int) -> TurboQuantKVLayerLayout {+ guard case .turboQuant = storageMode else {+ preconditionFailure("TurboQuant KV layout is unavailable for FP16 storage")+ }+ return turboQuantLayouts[layer]+ }++ private func validateRange(start: Int, count: Int) {+ precondition(count >= 0, "count must be non-negative")+ precondition(start >= 0, "start must be non-negative")+ precondition(start + count <= maxContext,+ "range \(start)..<\(start + count) exceeds maxContext \(maxContext)")+ }++ private func validateValidTokenCount(_ count: Int) {+ precondition(count >= 0, "validTokenCount must be non-negative")+ precondition(count <= maxContext,+ "validTokenCount \(count) exceeds maxContext \(maxContext)")+ }++ private func physicalSlot(layer: Int, position: Int) -> Int {+ position % capacityTokens[layer]+ }++ private func validateContiguousPhysicalRange(layer: Int, start: Int, count: Int) {+ guard count > 0, storageMode == .fp16, fp16RingEnabled, kinds[layer] == .swa else { return }+ let capacity = capacityTokens[layer]+ let physicalStart = start % capacity+ precondition(physicalStart + count <= capacity,+ "range \(start)..<\(start + count) wraps FP16 KV ring capacity \(capacity)")+ }++ private func advise(_ buffer: MTLBuffer, pageSize: Int, seen: inout Set<ObjectIdentifier>) {+ let id = ObjectIdentifier(buffer)+ if seen.contains(id) { return }+ seen.insert(id)+ // MTLBuffer allocations are page-aligned; round the length down to a+ // whole number of pages so we never hand madvise a partial tail page.+ let len = (buffer.length / pageSize) * pageSize+ if len > 0 {+ _ = posix_madvise(buffer.contents(), len, POSIX_MADV_DONTNEED)+ }+ }+}diff --git a/Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swift b/Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swiftnew file mode 100644index 00000000..6f5cd7bc--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swift@@ -0,0 +1,67 @@+import Foundation++enum TurboQuantKVMode: Sendable, Equatable {+ case disabled+ case k4v4NormCorrected+}++struct TurboQuantKVRoleLayout: Sendable, Equatable {+ let packedOffsetPerHead: Int+ let scaleOffsetPerHead: Int+ let bytesPerHead: Int+ let bytesPerToken: Int++}++struct TurboQuantKVLayerLayout: Sendable, Equatable {+ let key: TurboQuantKVRoleLayout+ let value: TurboQuantKVRoleLayout++}++enum TurboQuantKVLayout {+ static let fp16ScaleBytes = 2++ static func layer(mode: TurboQuantKVMode,+ config: ArchConfig,+ layer: Int,+ capacity: Int) -> TurboQuantKVLayerLayout {+ let isFull = config.fullAttentionLayerMask[layer] != 0+ let headDim = isFull ? config.fullHeadDim : config.headDim+ let numKVHeads = isFull ? config.numFullKVHeads : config.numKVHeads+ return self.layer(mode: mode,+ headDim: headDim,+ numKVHeads: numKVHeads,+ capacity: capacity)+ }++ static func layer(mode: TurboQuantKVMode,+ headDim: Int,+ numKVHeads: Int,+ capacity: Int) -> TurboQuantKVLayerLayout {+ precondition(mode != .disabled, "disabled mode has no TurboQuant layout")+ precondition(headDim > 0 && headDim % 8 == 0,+ "headDim must be positive and byte-packable")+ precondition(numKVHeads > 0)+ precondition(capacity > 0)+ let roleLayout = role(mode: mode,+ headDim: headDim,+ numKVHeads: numKVHeads)+ return TurboQuantKVLayerLayout(key: roleLayout,+ value: roleLayout)+ }++ static func role(mode: TurboQuantKVMode,+ headDim: Int,+ numKVHeads: Int) -> TurboQuantKVRoleLayout {+ precondition(mode == .k4v4NormCorrected)+ let packed = (headDim * 4 + 7) / 8+ let packedOffset = 0+ let scaleOffset = packedOffset + packed+ let perHead = scaleOffset + fp16ScaleBytes+ return TurboQuantKVRoleLayout(packedOffsetPerHead: packedOffset,+ scaleOffsetPerHead: scaleOffset,+ bytesPerHead: perHead,+ bytesPerToken: perHead * numKVHeads)+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swiftnew file mode 100644index 00000000..e8825142--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift@@ -0,0 +1,148 @@+import Metal++struct PrefillChunkScratchLayout: Sendable, Equatable {+ let chunkTokens: Int+ let hiddenSize: Int+ let maxQElementsPerToken: Int+ let maxKVElementsPerToken: Int+ let sharedIntermediate: Int+ let routedIntermediate: Int+ let topK: Int+ let routedPairMicrobatchRows: Int++ init(config: ArchConfig,+ chunkTokens: Int,+ routedPairMicrobatchRows: Int = 32) {+ self.chunkTokens = max(1, min(chunkTokens, 128))+ self.hiddenSize = config.hiddenSize+ self.maxQElementsPerToken = config.numHeads * max(config.headDim, config.fullHeadDim)+ self.maxKVElementsPerToken = max(config.numKVHeads * config.headDim,+ config.numFullKVHeads * config.fullHeadDim)+ self.sharedIntermediate = config.intermediateSize+ self.routedIntermediate = config.moeIntermediateSize+ self.topK = config.topKExperts+ self.routedPairMicrobatchRows = max(1, min(routedPairMicrobatchRows, 128))+ }++ init(config: ArchConfig, runtime: PrefillRuntimeConfig) {+ self.init(config: config,+ chunkTokens: runtime.chunkTokens)+ }++ var hiddenElements: Int { chunkTokens * hiddenSize }+ var normedElements: Int { hiddenElements }+ var qElements: Int { chunkTokens * maxQElementsPerToken }+ var kStageElements: Int { chunkTokens * maxKVElementsPerToken }+ var vStageElements: Int { kStageElements }+ var attentionOutputElements: Int { qElements }+ var denseXElements: Int { hiddenElements }+ var routedXElements: Int { hiddenElements }+ var routerXElements: Int { hiddenElements }+ var h1Elements: Int { hiddenElements }+ var h2Elements: Int { hiddenElements }+ var routePartialElements: Int { chunkTokens * topK * hiddenSize }+ var routeIDElements: Int { chunkTokens * topK }+ var routeWeightElements: Int { routeIDElements }+ var sharedExpertActScratchElements: Int {+ sharedIntermediate+ }+ var routedGateUpActElements: Int { 3 * routedPairMicrobatchRows * routedIntermediate }+ var routedDownOutputElements: Int { routedPairMicrobatchRows * hiddenSize }++ var devicePrivateBytes: Int {+ let fp16Elements = hiddenElements+ + normedElements+ + qElements+ + kStageElements+ + vStageElements+ + attentionOutputElements+ + denseXElements+ + routedXElements+ + routerXElements+ + h1Elements+ + h2Elements+ + routePartialElements+ + sharedExpertActScratchElements+ + routedGateUpActElements+ + routedDownOutputElements+ return fp16Elements * MemoryLayout<Float16>.stride+ }++ var sharedMetadataBytes: Int {+ routeIDElements * MemoryLayout<UInt32>.stride+ + routeWeightElements * MemoryLayout<Float16>.stride+ }++ var totalPersistentBytes: Int {+ devicePrivateBytes + sharedMetadataBytes+ }+}++struct PrefillChunkScratchBuffers {+ let layout: PrefillChunkScratchLayout+ let hidden: MTLBuffer+ let normed: MTLBuffer+ let q: MTLBuffer+ let kStage: MTLBuffer+ let vStage: MTLBuffer+ let attentionOutput: MTLBuffer+ let denseX: MTLBuffer+ let routedX: MTLBuffer+ let routerX: MTLBuffer+ let h1: MTLBuffer+ let h2: MTLBuffer+ let routePartials: MTLBuffer+ let routeIDs: MTLBuffer+ let routeWeights: MTLBuffer+ let sharedActScratch: MTLBuffer+ let routedGateUpActScratch: MTLBuffer+ let routedDownScratch: MTLBuffer++ static func allocate(device: MTLDevice,+ layout: PrefillChunkScratchLayout) throws -> PrefillChunkScratchBuffers {+ func privateBuffer(_ elements: Int, label: String) throws -> MTLBuffer {+ guard let buffer = device.makeBuffer(+ length: max(elements, 1) * MemoryLayout<Float16>.stride,+ options: .storageModePrivate)+ else {+ throw ModelError.residentBufferWrapFailed+ }+ buffer.label = label+ return buffer+ }++ func sharedBuffer(_ bytes: Int, label: String) throws -> MTLBuffer {+ guard let buffer = device.makeBuffer(length: max(bytes, 1),+ options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ buffer.label = label+ return buffer+ }++ return PrefillChunkScratchBuffers(+ layout: layout,+ hidden: try privateBuffer(layout.hiddenElements, label: "prefill.hidden"),+ normed: try privateBuffer(layout.normedElements, label: "prefill.normed"),+ q: try privateBuffer(layout.qElements, label: "prefill.q"),+ kStage: try privateBuffer(layout.kStageElements, label: "prefill.kStage"),+ vStage: try privateBuffer(layout.vStageElements, label: "prefill.vStage"),+ attentionOutput: try privateBuffer(layout.attentionOutputElements, label: "prefill.attnOut"),+ denseX: try privateBuffer(layout.denseXElements, label: "prefill.denseX"),+ routedX: try privateBuffer(layout.routedXElements, label: "prefill.routedX"),+ routerX: try privateBuffer(layout.routerXElements, label: "prefill.routerX"),+ h1: try privateBuffer(layout.h1Elements, label: "prefill.h1"),+ h2: try privateBuffer(layout.h2Elements, label: "prefill.h2"),+ routePartials: try privateBuffer(layout.routePartialElements, label: "prefill.routePartials"),+ routeIDs: try sharedBuffer(layout.routeIDElements * MemoryLayout<UInt32>.stride,+ label: "prefill.routeIDs"),+ routeWeights: try sharedBuffer(layout.routeWeightElements * MemoryLayout<Float16>.stride,+ label: "prefill.routeWeights"),+ sharedActScratch: try privateBuffer(layout.sharedExpertActScratchElements,+ label: "prefill.sharedActScratch"),+ routedGateUpActScratch: try privateBuffer(layout.routedGateUpActElements,+ label: "prefill.routedGateUpActScratch"),+ routedDownScratch: try privateBuffer(layout.routedDownOutputElements,+ label: "prefill.routedDownScratch"))+ }+}diff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swiftnew file mode 100644index 00000000..f82c4f22--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift@@ -0,0 +1,197 @@+import Foundation++public enum PrefillError: Error, CustomStringConvertible, Equatable {+ public static let chunkedRequiresChunkedRunnerReason =+ "chunked prefill requires a ChunkedPrefillRunner-backed runtime"++ case chunkedUnsupported(String)+ case chunkedRunnerDirty(String)+ case prefillCursorMismatch(String)+ case unsupportedPrefillSeed(String)++ public var description: String {+ switch self {+ case .chunkedUnsupported(let reason),+ .chunkedRunnerDirty(let reason),+ .prefillCursorMismatch(let reason),+ .unsupportedPrefillSeed(let reason):+ return reason+ }+ }+}++struct PrefillChunkCommitState: Sendable, Equatable {+ private(set) var isDirty = false+ private(set) var inFlightStartPosition: Int?+ private(set) var inFlightTokenCount: Int?++ var inFlightEndPosition: Int? {+ guard let start = inFlightStartPosition,+ let count = inFlightTokenCount else { return nil }+ return start + count+ }++ init() {}++ mutating func markDirty(startPosition: Int, tokenCount: Int) {+ precondition(startPosition >= 0, "prefill dirty startPosition must be non-negative")+ precondition(tokenCount > 0, "prefill dirty tokenCount must be positive")+ isDirty = true+ inFlightStartPosition = startPosition+ inFlightTokenCount = tokenCount+ }++ mutating func markCommitted() {+ isDirty = false+ inFlightStartPosition = nil+ inFlightTokenCount = nil+ }++ mutating func reset() {+ markCommitted()+ }++ func requireClean(operation: String) throws {+ guard !isDirty else {+ let range: String+ if let start = inFlightStartPosition, let end = inFlightEndPosition {+ range = " for in-flight chunk [\(start), \(end))"+ } else {+ range = ""+ }+ throw PrefillError.chunkedRunnerDirty(+ "\(operation) rejected because a previous chunked prefill wrote KV rows\(range) but did not commit; call reset() before reusing the runner")+ }+ }+}++struct PrefillChunkSpan: Sendable, Equatable {+ let tokenOffset: Int+ let tokenCount: Int+ let startPosition: Int+ let completedCount: Int++ init(tokenOffset: Int,+ tokenCount: Int,+ startPosition: Int,+ completedCount: Int) {+ self.tokenOffset = tokenOffset+ self.tokenCount = tokenCount+ self.startPosition = startPosition+ self.completedCount = completedCount+ }++}++enum PrefillChunkPlanner {+ static func spans(tokenCount: Int,+ startPosition: Int,+ config: PrefillRuntimeConfig) -> [PrefillChunkSpan] {+ spans(tokenCount: tokenCount,+ startPosition: startPosition,+ chunkTokens: config.chunkTokens)+ }++ static func spans(tokenCount: Int,+ startPosition: Int,+ chunkTokens: Int) -> [PrefillChunkSpan] {+ precondition(tokenCount >= 0, "prefill tokenCount must be non-negative")+ precondition(startPosition >= 0, "prefill startPosition must be non-negative")+ let chunk = max(1, min(chunkTokens, PrefillRuntimeConfig.maxChunkTokens))+ guard tokenCount > 0 else { return [] }++ var spans: [PrefillChunkSpan] = []+ spans.reserveCapacity((tokenCount + chunk - 1) / chunk)+ var offset = 0+ while offset < tokenCount {+ let count = min(chunk, tokenCount - offset)+ let completed = offset + count+ spans.append(PrefillChunkSpan(tokenOffset: offset,+ tokenCount: count,+ startPosition: startPosition + offset,+ completedCount: completed))+ offset = completed+ }+ return spans+ }+}++public enum PrefillKVStorageMode: String, Sendable, Equatable {+ case fp16+ case packedOnly = "packed-only"+}++public enum PrefillExecutedMode: String, Sendable, Equatable {+ case off+ case chunked+ case unsupported+}++public enum PrefillChunkCompleteness: String, Sendable, Equatable {+ case complete+ case unsupported+}++public struct PrefillExecutionDiagnostics: Sendable, Equatable {+ public let requestedMode: PrefillRuntimeConfig.Mode+ public let executedMode: PrefillExecutedMode+ public let kvStorageMode: PrefillKVStorageMode?+ public let chunkCompleteness: PrefillChunkCompleteness+ public let unsupportedReason: String?++ public init(config: PrefillRuntimeConfig,+ executedMode: PrefillExecutedMode,+ kvStorageMode: PrefillKVStorageMode? = nil,+ chunkCompleteness: PrefillChunkCompleteness? = nil,+ unsupportedReason: String? = nil) {+ self.requestedMode = config.mode+ self.executedMode = executedMode+ self.kvStorageMode = kvStorageMode+ self.chunkCompleteness = chunkCompleteness+ ?? (executedMode == .unsupported ? .unsupported : .complete)+ self.unsupportedReason = unsupportedReason+ }++ public static func unsupported(config: PrefillRuntimeConfig,+ kvStorageMode: PrefillKVStorageMode? = nil,+ reason: String) -> PrefillExecutionDiagnostics {+ PrefillExecutionDiagnostics(config: config,+ executedMode: .unsupported,+ kvStorageMode: kvStorageMode,+ chunkCompleteness: .unsupported,+ unsupportedReason: reason)+ }+}++public struct PrefillRuntimeConfig: Sendable, Equatable {+ public enum Mode: String, Sendable, Equatable {+ case off+ case chunked+ }++ public static let maxChunkTokens = 128++ public let mode: Mode+ public let chunkTokens: Int++ private init(mode: Mode, chunkTokens: Int) {+ self.mode = mode+ self.chunkTokens = chunkTokens+ }++ public var enabled: Bool { mode == .chunked }++ public static var off: PrefillRuntimeConfig {+ PrefillRuntimeConfig(mode: .off, chunkTokens: 128)+ }++ public static var defaultChunked: PrefillRuntimeConfig {+ production(chunkTokens: 128)+ }++ public static func production(chunkTokens: Int) -> PrefillRuntimeConfig {+ precondition(RuntimeConfiguration.allowedPrefillChunkTokens.contains(chunkTokens),+ "unsupported prefill chunk size")+ return PrefillRuntimeConfig(mode: .chunked, chunkTokens: chunkTokens)+ }+}diff --git a/Sources/TurboFieldfare/Tokenization/Detokenizer.swift b/Sources/TurboFieldfare/Tokenization/Detokenizer.swiftnew file mode 100644index 00000000..dac93db8--- /dev/null+++ b/Sources/TurboFieldfare/Tokenization/Detokenizer.swift@@ -0,0 +1,95 @@+import Foundation+import Tokenizers++/// Streaming detokenizer for generation loops.+///+/// Two challenges drive the design:+///+/// 1. BPE byte-fallback splits multi-byte codepoints (e.g. emoji) across several+/// tokens. Naively decoding each token in isolation yields broken UTF-8.+/// 2. swift-transformers' decoder silently drops byte-fallback tokens that sit+/// at the **end** of the decoded sequence (the bytes are committed only once+/// a non-byte-fallback token follows). For us this matters at `flush()`.+///+/// Strategy:+/// - During `push(_:)` we decode the longest prefix of accumulated IDs that+/// does NOT end with byte-fallback tokens, then emit the delta vs. previously+/// emitted text. Any trailing byte-fallback IDs are held back.+/// - During `flush()` we decode the stable prefix as above AND manually+/// assemble the trailing byte-fallback bytes into a UTF-8 string. This+/// recovers text the library would otherwise drop on a sequence-ending+/// codepoint.+struct GFDetokenizer {+ @usableFromInline let tokenizer: any Tokenizer+ @usableFromInline var stableIDs: [Int] = []+ @usableFromInline var trailingByteIDs: [Int] = []+ @usableFromInline var emitted: String = ""++ init(tokenizer: GFTokenizer) {+ self.tokenizer = tokenizer.tokenizer+ }++ mutating func push(_ id: Int32) -> String {+ let tokenID = Int(id)+ let token = tokenizer.convertIdToToken(tokenID) ?? ""+ if Self.isByteFallback(token) {+ trailingByteIDs.append(tokenID)+ return ""+ }++ if !trailingByteIDs.isEmpty {+ stableIDs.append(contentsOf: trailingByteIDs)+ trailingByteIDs.removeAll(keepingCapacity: true)+ }+ stableIDs.append(tokenID)++ let current = tokenizer.decode(tokens: stableIDs, skipSpecialTokens: true)+ return commitDelta(current)+ }++ mutating func flush() -> String {+ let stableText = stableIDs.isEmpty+ ? ""+ : tokenizer.decode(tokens: stableIDs, skipSpecialTokens: true)++ let trailingText = assembleByteFallback(trailingByteIDs)+ let fullText = stableText + trailingText+ return commitDelta(fullText)+ }++ @usableFromInline+ mutating func commitDelta(_ current: String) -> String {+ guard current.hasPrefix(emitted) else {+ // Decoder altered the prefix — extremely rare in append-only streams.+ // Resync rather than emit garbage; the user-visible loss is bounded+ // to whatever was retokenized.+ emitted = current+ return ""+ }+ let delta = String(current.dropFirst(emitted.count))+ emitted = current+ return delta+ }++ @usableFromInline+ func assembleByteFallback(_ ids: [Int]) -> String {+ var bytes: [UInt8] = []+ bytes.reserveCapacity(ids.count)+ for id in ids {+ guard let tok = tokenizer.convertIdToToken(id) else { continue }+ guard Self.isByteFallback(tok),+ let byte = UInt8(tok.dropFirst(3).dropLast(), radix: 16)+ else { continue }+ bytes.append(byte)+ }+ return String(bytes: bytes, encoding: .utf8) ?? ""+ }++ @usableFromInline+ static func isByteFallback(_ token: String) -> Bool {+ token.count == 6+ && token.hasPrefix("<0x")+ && token.hasSuffix(">")+ && token.dropFirst(3).dropLast().allSatisfy { $0.isHexDigit }+ }+}diff --git a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift b/Sources/TurboFieldfare/Tokenization/Tokenizer.swiftnew file mode 100644index 00000000..ac030cbd--- /dev/null+++ b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift@@ -0,0 +1,146 @@+import Foundation+import Tokenizers++enum GFTokenizerError: Error, CustomStringConvertible {+ case missingSpecialToken(String)++ public var description: String {+ switch self {+ case .missingSpecialToken(let t): return "tokenizer missing required special token: \(t)"+ }+ }+}++/// Gemma 4 tokenizer wrapper. It prefers the tokenizer included in a completed+/// `.gturbo` directory and adapts token IDs to the Int32 runtime boundary.+public struct GFTokenizer: @unchecked Sendable {+ public static let modelID = "google/gemma-4-26B-A4B-it"++ public let bosID: Int32+ public let eosID: Int32+ public let padID: Int32+ public let endOfTurnID: Int32+ public let stopTokenIDs: Set<Int32>+ public let vocabSize: Int++ @usableFromInline+ let tokenizer: any Tokenizer++ public static func load() async throws -> GFTokenizer {+ try await GFTokenizerLoadCoordinator.shared.load(.pretrained(modelID))+ }++ public static func load(from folder: URL) async throws -> GFTokenizer {+ try await GFTokenizerLoadCoordinator.shared.load(.local(folder.standardizedFileURL.path))+ }++ public static func load(forModelDirectory modelDirectory: URL) async throws -> GFTokenizer {+ if let folder = tokenizerFolder(forModelDirectory: modelDirectory) {+ return try await load(from: folder)+ }+ return try await load()+ }++ public static func tokenizerFolder(forModelDirectory modelDirectory: URL,+ fileManager: FileManager = .default) -> URL? {+ let sidecar = modelDirectory+ .standardizedFileURL+ .appendingPathComponent("tokenizer", isDirectory: true)+ if hasTokenizerJSON(in: sidecar, fileManager: fileManager) {+ return sidecar+ }++ return nil+ }++ static func loadUncached(pretrained modelID: String = Self.modelID) async throws -> GFTokenizer {+ let underlying = try await AutoTokenizer.from(pretrained: modelID)+ return try GFTokenizer(tokenizer: underlying)+ }++ static func loadUncached(from folder: URL) async throws -> GFTokenizer {+ let underlying = try await AutoTokenizer.from(modelFolder: folder)+ return try GFTokenizer(tokenizer: underlying)+ }++ private static func hasTokenizerJSON(in folder: URL, fileManager: FileManager) -> Bool {+ fileManager.fileExists(atPath: folder.appendingPathComponent("tokenizer.json").path)+ }++ public init(tokenizer: any Tokenizer) throws {+ self.tokenizer = tokenizer++ guard let bos = tokenizer.bosTokenId else {+ throw GFTokenizerError.missingSpecialToken("<bos>")+ }+ guard let eos = tokenizer.eosTokenId else {+ throw GFTokenizerError.missingSpecialToken("<eos>")+ }+ guard let pad = tokenizer.convertTokenToId("<pad>") else {+ throw GFTokenizerError.missingSpecialToken("<pad>")+ }+ guard let eot = tokenizer.convertTokenToId("<turn|>") else {+ throw GFTokenizerError.missingSpecialToken("<turn|>")+ }++ self.bosID = Int32(bos)+ self.eosID = Int32(eos)+ self.padID = Int32(pad)+ self.endOfTurnID = Int32(eot)+ self.stopTokenIDs = [self.eosID, self.endOfTurnID]+ self.vocabSize = 262_144+ }++ /// Encode UTF-8 text to token IDs. `addBOS = true` prepends `<bos>`.+ ///+ /// The library's `addSpecialTokens: true` flag is a no-op for the Gemma 4 IT+ /// tokenizer (its config has `add_bos_token = false`; BOS is expected to come+ /// from the chat template). We prepend manually so the kernel-facing API stays+ /// the same regardless of upstream defaults.+ public func encode(_ text: String, addBOS: Bool = true) -> [Int32] {+ let base = tokenizer.encode(text: text, addSpecialTokens: false).map(Int32.init)+ return addBOS ? [bosID] + base : base+ }++ /// Decode token IDs to text. `skipSpecialTokens` strips BOS/EOS/turn markers from the output.+ public func decode(_ ids: [Int32], skipSpecialTokens: Bool = true) -> String {+ tokenizer.decode(tokens: ids.map(Int.init), skipSpecialTokens: skipSpecialTokens)+ }++}++private enum GFTokenizerLoadSource: Hashable {+ case pretrained(String)+ case local(String)+}++private actor GFTokenizerLoadCoordinator {+ static let shared = GFTokenizerLoadCoordinator()++ private var tasks: [GFTokenizerLoadSource: Task<GFTokenizer, Error>] = [:]++ func load(_ source: GFTokenizerLoadSource) async throws -> GFTokenizer {+ if let task = tasks[source] {+ return try await task.value+ }++ // Keep the CPU-heavy tokenizer build off the coordinator actor; callers+ // share the task result instead of owning its cancellation.+ let task = Task.detached(priority: .userInitiated) { () throws -> GFTokenizer in+ switch source {+ case .pretrained(let modelID):+ return try await GFTokenizer.loadUncached(pretrained: modelID)+ case .local(let path):+ return try await GFTokenizer.loadUncached(from: URL(fileURLWithPath: path))+ }+ }+ tasks[source] = task++ do {+ return try await task.value+ } catch {+ tasks[source] = nil+ throw error+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppPromptPreset.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppPromptPreset.swiftnew file mode 100644index 00000000..8b62aa5a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppPromptPreset.swift@@ -0,0 +1,81 @@+public struct AppPromptPreset: Identifiable, Sendable, Equatable {+ public let id: String+ public let title: String+ public let prefix: String+ public let isPrimary: Bool++ public init(id: String, title: String, prefix: String, isPrimary: Bool) {+ self.id = id+ self.title = title+ self.prefix = prefix+ self.isPrimary = isPrimary+ }++ public static let all: [AppPromptPreset] = [+ AppPromptPreset(+ id: "paris",+ title: "Paris",+ prefix: "Paris is the capital and largest city of France. Situated on the River Seine, the city is known for",+ isPrimary: true),+ AppPromptPreset(+ id: "fibonacci",+ title: "Python Fibonacci",+ prefix: """+ An iterative Python function can return the first n Fibonacci numbers without recursion. It returns an empty list when n is zero, uses O(n) time, and includes a small correctness check:++ ```python+ def fibonacci(n: int) -> list[int]:+ """,+ isPrimary: true),+ AppPromptPreset(+ id: "fieldfare",+ title: "Meet the fieldfare",+ prefix: "The fieldfare (Turdus pilaris) is a grey-headed, chestnut-backed thrush that reaches Britain and Ireland from northern Europe each autumn. Its noisy winter flocks roam the countryside in search of berries, and",+ isPrimary: true),+ AppPromptPreset(+ id: "cosine-similarity",+ title: "Dot product and cosine similarity",+ prefix: """+ The unit vectors u = [1, 0] and v = [0, 1] are orthogonal. Their dot product is 0, both lengths are 1, and their cosine similarity is exactly 0. A compact check is:++ ```python+ assert dot([1, 0], [0, 1]) == 0+ assert cosine_similarity([1, 0], [0, 1]) ==+ """,+ isPrimary: false),+ AppPromptPreset(+ id: "recommendation-systems",+ title: "How recommendations learn",+ prefix: """+ # How Collaborative Filtering Learns Film Recommendations++ A film-streaming service records a sparse user–item matrix: rows represent viewers, columns represent films, and observed entries represent ratings or interactions. Most entries are missing because each viewer has seen only a small fraction of the catalog. Matrix factorization learns a low-dimensional vector for every viewer and every film. Their dot product estimates a missing preference score, so films with the largest estimated scores can be ranked for that viewer.++ The explanation has exactly four sections: the sparse interaction matrix; latent viewer and film vectors; training and prediction; and limitations and evaluation. A missing interaction is unknown, not a negative rating. Training adjusts the vectors to reduce error on observed interactions with regularization. Evaluation uses held-out interactions and ranking measures. The limitations are cold start and popularity bias. The fourth section ends the article without a summary, repeated title, or repeated instructions.++ ## The sparse interaction matrix+ """,+ isPrimary: false),+ AppPromptPreset(+ id: "matrix-multiplication",+ title: "Matrix multiplication",+ prefix: """+ # Matrix Multiplication: Why Rows Meet Columns++ For A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]], the complete verified calculation is:++ C[1,1] = 1 x 5 + 2 x 7 = 19+ C[1,2] = 1 x 6 + 2 x 8 = 22+ C[2,1] = 3 x 5 + 4 x 7 = 43+ C[2,2] = 3 x 6 + 4 x 8 = 50++ Thus C = AB = [[19, 22], [43, 50]]. The explanation below does not repeat or recompute those numeric equations. It has exactly three sections: why the inner dimensions match; how each output cell is a row-column dot product; and the general m x n by n x p rule. The final section states C[i,j] = sum over k of A[i,k]B[k,j] and then ends, without another example, code, references, or a summary.++ ## Why the inner dimensions match+ """,+ isPrimary: false),+ ]++ public static var primary: [AppPromptPreset] { all.filter(\.isPrimary) }+ public static var secondary: [AppPromptPreset] { all.filter { !$0.isPrimary } }+}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swiftnew file mode 100644index 00000000..c1270095--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift@@ -0,0 +1,134 @@+import Foundation+import TurboFieldfare++public enum AppExpertCachePolicy: String, CaseIterable, Sendable, Identifiable {+ case lfu+ case lru++ public var id: String { rawValue }+ public var label: String { rawValue.uppercased() }+}++public enum AppRDAdvicePolicy: String, CaseIterable, Sendable, Identifiable {+ case off+ case `default`+ case bounded+ case adaptive++ public var id: String { rawValue }+ public var label: String { rawValue.capitalized }++ var runtimeValue: RDAdvicePolicyMode {+ switch self {+ case .off: return .off+ case .default: return .default+ case .bounded: return .bounded+ case .adaptive: return .adaptive+ }+ }+}++public enum AppModelVerification: String, CaseIterable, Sendable, Identifiable {+ case fullSha256 = "full-sha256"+ case trustedInstall = "trusted-install"++ public var id: String { rawValue }++ public var label: String {+ switch self {+ case .fullSha256: return "Full SHA-256"+ case .trustedInstall: return "Trust verified install"+ }+ }++ var runtimeValue: ModelIntegrityPolicy {+ switch self {+ case .fullSha256: return .fullSha256+ case .trustedInstall: return .sizeCheckTrustedReceipt+ }+ }+}++public struct AppRuntimeOptions: Equatable, Sendable {+ public static let allowedSlotCounts = RuntimeConfiguration.allowedExpertCacheSlots+ public static let allowedPrefillChunkTokens = RuntimeConfiguration.allowedPrefillChunkTokens++ public var expertCacheSlots: Int+ public var expertCachePolicy: AppExpertCachePolicy+ public var prefillEnabled: Bool+ public var prefillChunkTokens: Int+ public var turboQuantKVEnabled: Bool+ public var rdadvisePolicy: AppRDAdvicePolicy+ public var modelVerification: AppModelVerification++ public init(expertCacheSlots: Int = 16,+ expertCachePolicy: AppExpertCachePolicy = .lfu,+ prefillEnabled: Bool = true,+ prefillChunkTokens: Int = 128,+ turboQuantKVEnabled: Bool = false,+ rdadvisePolicy: AppRDAdvicePolicy = .off,+ modelVerification: AppModelVerification = .fullSha256) {+ self.expertCacheSlots = expertCacheSlots+ self.expertCachePolicy = expertCachePolicy+ self.prefillEnabled = prefillEnabled+ self.prefillChunkTokens = prefillChunkTokens+ self.turboQuantKVEnabled = turboQuantKVEnabled+ self.rdadvisePolicy = rdadvisePolicy+ self.modelVerification = modelVerification+ }++ public func validate() throws {+ guard Self.allowedSlotCounts.contains(expertCacheSlots) else {+ throw AppInferenceError.invalidRequest(+ "expert cache slots must be one of \(Self.allowedSlotCounts)")+ }+ guard Self.allowedPrefillChunkTokens.contains(prefillChunkTokens) else {+ throw AppInferenceError.invalidRequest(+ "prefill chunk size must be one of \(Self.allowedPrefillChunkTokens)")+ }+ }++ public var prefillConfig: PrefillRuntimeConfig {+ prefillEnabled ? .production(chunkTokens: prefillChunkTokens) : .off+ }++ public var resultSummary: String {+ let prefill = prefillEnabled ? "prefill \(prefillChunkTokens)" : "prefill off"+ let kv = turboQuantKVEnabled ? "K4/V4 KV" : "FP16 KV"+ let verification = modelVerification == .fullSha256 ? "full SHA-256" : "trusted receipt"+ return "Cache \(expertCacheSlots) \(expertCachePolicy.label), \(prefill), \(kv), RDADVISE \(rdadvisePolicy.label.lowercased()), \(verification)"+ }++ public static func slotsLabel(for slots: Int) -> String {+ slots > 16 ? "\(slots) +RAM" : "\(slots)"+ }++ public func resolvedRuntimeConfiguration(forceLogitsHead: Bool) throws -> RuntimeConfiguration {+ try validate()+ return RuntimeConfiguration(+ expertCacheSlots: expertCacheSlots,+ expertCachePolicy: expertCachePolicy == .lru ? .lru : .lfu,+ rdadvisePolicy: rdadvisePolicy.runtimeValue,+ prefillEnabled: prefillEnabled,+ prefillChunkTokens: prefillChunkTokens,+ turboQuantKVEnabled: turboQuantKVEnabled,+ forceLogitsHead: forceLogitsHead)+ }+}++public struct AppLoadedRuntimeKey: Equatable, Sendable {+ public var modelDirectory: URL+ public var maxContextTokens: Int+ public var runtimeOptions: AppRuntimeOptions+ public var forceLogitsHead: Bool++ public init(modelDirectory: URL,+ maxContextTokens: Int,+ options: AppRuntimeOptions,+ forceLogitsHead: Bool = false) {+ self.modelDirectory = modelDirectory.standardizedFileURL+ self.maxContextTokens = maxContextTokens+ self.runtimeOptions = options+ self.forceLogitsHead = forceLogitsHead+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swiftnew file mode 100644index 00000000..302b68eb--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift@@ -0,0 +1,100 @@+import Foundation+import TurboFieldfare++public enum AppStopReason: String, Equatable, Sendable {+ case maxTokens+ case cancelled+ case failed+ case eos+ case endOfTurn+ case stopString+}++public struct AppRunnerDiagnostics: Equatable, Sendable {+ public var cb1MillisecondsPerToken: Double+ public var ioMillisecondsPerToken: Double+ public var cb2MillisecondsPerToken: Double+ public var headMillisecondsPerToken: Double+ public var rdadviseMillisecondsPerToken: Double+ public var rdadviseCallsPerToken: Double+ public var rdadviseMegabytesPerToken: Double+ public var rdadviseSkippedPerToken: Double+ public var rdadviseFailures: UInt64++ public init(cb1MillisecondsPerToken: Double = 0,+ ioMillisecondsPerToken: Double = 0,+ cb2MillisecondsPerToken: Double = 0,+ headMillisecondsPerToken: Double = 0,+ rdadviseMillisecondsPerToken: Double = 0,+ rdadviseCallsPerToken: Double = 0,+ rdadviseMegabytesPerToken: Double = 0,+ rdadviseSkippedPerToken: Double = 0,+ rdadviseFailures: UInt64 = 0) {+ self.cb1MillisecondsPerToken = cb1MillisecondsPerToken+ self.ioMillisecondsPerToken = ioMillisecondsPerToken+ self.cb2MillisecondsPerToken = cb2MillisecondsPerToken+ self.headMillisecondsPerToken = headMillisecondsPerToken+ self.rdadviseMillisecondsPerToken = rdadviseMillisecondsPerToken+ self.rdadviseCallsPerToken = rdadviseCallsPerToken+ self.rdadviseMegabytesPerToken = rdadviseMegabytesPerToken+ self.rdadviseSkippedPerToken = rdadviseSkippedPerToken+ self.rdadviseFailures = rdadviseFailures+ }+}++public struct AppDiagnostics: Equatable, Sendable {+ public var generatedTokens: Int+ public var stopReason: AppStopReason+ public var promptTokenCount: Int?+ public var prefillSeconds: Double?+ public var timeToFirstTokenSeconds: Double?+ public var decodeSeconds: Double+ public var tokensPerSecond: Double+ public var peakMemoryBytes: UInt64?+ public var runtimeOptions: AppRuntimeOptions+ public var prefill: PrefillExecutionDiagnostics?+ public var runner: AppRunnerDiagnostics?++ public var requestStartTimeToFirstTokenSeconds: Double? {+ guard let prefillSeconds, let timeToFirstTokenSeconds else { return nil }+ return prefillSeconds + timeToFirstTokenSeconds+ }++ public init(generatedTokens: Int,+ stopReason: AppStopReason,+ promptTokenCount: Int? = nil,+ prefillSeconds: Double? = nil,+ timeToFirstTokenSeconds: Double?,+ decodeSeconds: Double,+ tokensPerSecond: Double,+ peakMemoryBytes: UInt64?,+ runtimeOptions: AppRuntimeOptions,+ prefill: PrefillExecutionDiagnostics? = nil,+ runner: AppRunnerDiagnostics? = nil) {+ self.generatedTokens = generatedTokens+ self.stopReason = stopReason+ self.promptTokenCount = promptTokenCount+ self.prefillSeconds = prefillSeconds+ self.timeToFirstTokenSeconds = timeToFirstTokenSeconds+ self.decodeSeconds = decodeSeconds+ self.tokensPerSecond = tokensPerSecond+ self.peakMemoryBytes = peakMemoryBytes+ self.runtimeOptions = runtimeOptions+ self.prefill = prefill+ self.runner = runner+ }+}++public struct AppTokenEvent: Equatable, Sendable {+ public var index: Int+ public var textDelta: String+ public var elapsedDecodeSeconds: Double+}++public enum AppInferenceEvent: Equatable, Sendable {+ case prefillProgress(done: Int, total: Int)+ case token(AppTokenEvent)+ case finished(AppDiagnostics)+ case cancelled(AppDiagnostics)+ case failed(AppInferenceError, partial: AppDiagnostics?)+}diff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppMemorySampler.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppMemorySampler.swiftnew file mode 100644index 00000000..26230ea1--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppMemorySampler.swift@@ -0,0 +1,50 @@+import Darwin+import Darwin.Mach+import Foundation++public final class AppMemorySampler: @unchecked Sendable {+ private let lock = NSLock()+ private var peak: UInt64 = 0+ private let processFootprint: @Sendable () -> UInt64?++ public init() {+ self.processFootprint = { Self.readProcessFootprint() }+ }++ init(processFootprint: @escaping @Sendable () -> UInt64?) {+ self.processFootprint = processFootprint+ }++ public func resetPeak() {+ lock.lock()+ peak = 0+ lock.unlock()+ }++ public func sample() -> UInt64? {+ guard let current = processFootprint() else { return nil }+ lock.lock()+ if current > peak { peak = current }+ lock.unlock()+ return current+ }++ private static func readProcessFootprint() -> UInt64? {+ var info = task_vm_info_data_t()+ var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)+ let kr = withUnsafeMutablePointer(to: &info) {+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {+ task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)+ }+ }+ guard kr == KERN_SUCCESS else { return nil }+ return UInt64(info.phys_footprint)+ }++ public var peakBytes: UInt64? {+ lock.lock()+ let value = peak+ lock.unlock()+ return value == 0 ? nil : value+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swiftnew file mode 100644index 00000000..881d2a74--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift@@ -0,0 +1,79 @@+import Foundation++public struct AppGenerationRequest: Equatable, Sendable {+ public var modelDirectory: URL+ public var prompt: String+ public var maxNewTokens: Int+ public var maxContextTokens: Int+ public var temperature: Float+ public var topK: Int?+ public var topP: Float?+ public var repetitionPenalty: Float+ public var runtimeOptions: AppRuntimeOptions++ public init(modelDirectory: URL,+ prompt: String,+ maxNewTokens: Int = 1_024,+ maxContextTokens: Int = 4096,+ temperature: Float = 0.1,+ topK: Int? = 64,+ topP: Float? = 0.95,+ repetitionPenalty: Float = 1.0,+ runtimeOptions: AppRuntimeOptions = AppRuntimeOptions()) {+ self.modelDirectory = modelDirectory+ self.prompt = prompt+ self.maxNewTokens = maxNewTokens+ self.maxContextTokens = maxContextTokens+ self.temperature = temperature+ self.topK = topK+ self.topP = topP+ self.repetitionPenalty = repetitionPenalty+ self.runtimeOptions = runtimeOptions+ }++ public var isPureGreedy: Bool {+ temperature == 0 && repetitionPenalty == 1+ }++ public func validate(fileManager: FileManager = .default,+ requireModelDirectory: Bool = true) throws {+ guard !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ throw AppInferenceError.invalidRequest("Prompt cannot be empty.")+ }+ guard maxNewTokens > 0 else {+ throw AppInferenceError.invalidRequest("Max response length must be greater than zero.")+ }+ guard maxContextTokens > 0 else {+ throw AppInferenceError.invalidRequest("Max context must be greater than zero.")+ }+ guard temperature >= 0 else {+ throw AppInferenceError.invalidRequest("Temperature cannot be negative.")+ }+ if let topK {+ guard (1...256).contains(topK) else {+ throw AppInferenceError.invalidRequest("Top-K must be between 1 and 256.")+ }+ }+ if let topP {+ guard topP > 0, topP <= 1 else {+ throw AppInferenceError.invalidRequest("Top-P must be greater than 0 and at most 1.")+ }+ if temperature > 0, topP < 1, topK == nil {+ throw AppInferenceError.invalidRequest(+ "Top-P below 1 requires Top-K to be enabled.")+ }+ }+ guard repetitionPenalty >= 1 else {+ throw AppInferenceError.invalidRequest("Repetition penalty must be at least 1.")+ }+ try runtimeOptions.validate()++ if requireModelDirectory {+ var isDirectory = ObjCBool(false)+ guard fileManager.fileExists(atPath: modelDirectory.path, isDirectory: &isDirectory),+ isDirectory.boolValue else {+ throw AppInferenceError.modelNotFound(modelDirectory.path)+ }+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swiftnew file mode 100644index 00000000..5b1b856a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift@@ -0,0 +1,24 @@+import Foundation++public protocol AppInferenceClient: Sendable {+ func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error>+ func cancel()+}++/// A client that owns a loadable model session. Loading is split from+/// generation so the UI can pre-load the ~1.6 GB resident weights once and+/// keep them warm across runs. Generation never loads or replaces a session.+public protocol AppModelLifecycleClient: AnyObject, AppInferenceClient {+ func ensureLoaded(modelDirectory: URL, maxContextTokens: Int,+ options: AppRuntimeOptions, forceLogitsHead: Bool,+ onState: @escaping @Sendable (AppModelLoadState) -> Void) async throws+ func unload() async+}++public protocol AppInferenceMemoryReporting: AnyObject {+ var currentInferenceMemoryBytes: UInt64? { get }+}++public protocol AppInferenceTranscriptReporting: AnyObject {+ var generationTranscriptMailbox: GenerationTranscriptMailbox { get }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swiftnew file mode 100644index 00000000..061c7faa--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceError.swift@@ -0,0 +1,50 @@+import Foundation++public enum AppInferenceError: Error, Equatable, Sendable, CustomStringConvertible {+ case invalidRequest(String)+ case modelNotFound(String)+ case modelLoadFailed(String)+ case tokenizerUnavailable(String)+ case contextOverflow(prompt: Int, maxNew: Int, maxContext: Int)+ case generationInFlight+ case modelNotLoaded+ case reloadRequired+ case cancelled+ case unknown(String)++ public var description: String { userMessage }++ public var userMessage: String {+ switch self {+ case .invalidRequest(let message):+ return message+ case .modelNotFound(let path):+ return "Model directory is not loadable: \(path)"+ case .modelLoadFailed(let message):+ return "Model load failed: \(message)"+ case .tokenizerUnavailable(let message):+ return "Tokenizer unavailable: \(message)"+ case .contextOverflow(let prompt, let maxNew, let maxContext):+ return "Prompt (\(prompt) tokens) plus max response (\(maxNew)) exceeds the \(maxContext)-token context."+ case .generationInFlight:+ return "A generation is already running."+ case .modelNotLoaded:+ return "Load the model before generating."+ case .reloadRequired:+ return "Model settings changed. Reload the model before generating."+ case .cancelled:+ return "Generation cancelled."+ case .unknown(let message):+ return message+ }+ }++ public var technicalDetail: String {+ switch self {+ case .tokenizerUnavailable:+ return "The installed tokenizer sidecar is missing or invalid. A Hugging Face fallback may require network access when no local sidecar is available."+ default:+ return userMessage+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swiftnew file mode 100644index 00000000..39528465--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift@@ -0,0 +1,334 @@+import Darwin+import Foundation+import Synchronization+import TurboFieldfare+import TurboFieldfareDecodeProtocol++public final class DecodeServiceInferenceClient: AppModelLifecycleClient,+ AppInferenceMemoryReporting, AppInferenceTranscriptReporting, @unchecked Sendable {+ private struct Connection {+ var input: FileHandle?+ var output: FileHandle?+ var loadedDirectory: URL?+ var launchLabel: String?+ var socketPath: String?+ }++ private let connection = Mutex(Connection())+ private let serviceURL: URL+ private let inferenceMemory = Mutex<UInt64?>(nil)+ public let generationTranscriptMailbox = GenerationTranscriptMailbox()++ public var currentInferenceMemoryBytes: UInt64? {+ inferenceMemory.withLock { $0 }+ }++ public init(serviceURL: URL? = nil) {+ self.serviceURL = serviceURL ?? Self.defaultServiceURL()+ }++ public func ensureLoaded(modelDirectory: URL, maxContextTokens: Int,+ options: AppRuntimeOptions, forceLogitsHead: Bool,+ onState: @escaping @Sendable (AppModelLoadState) -> Void) async throws {+ onState(.loading(.validatingDirectory))+ let handles = try await Task.detached(priority: .userInitiated) { [self] in+ try ensureProcess()+ }.value+ let request = DecodeLoadRequest(+ modelPath: modelDirectory.path, maxContextTokens: maxContextTokens,+ runtimeOptions: Self.decodeRuntimeOptions(options),+ forceLogitsHead: forceLogitsHead)+ try handles.input.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceCommand.load(request)))+ let event = try await readEvent(from: handles.output)+ guard event.generationID == request.requestID, event.kind == .ready else {+ throw AppInferenceError.modelLoadFailed(+ event.error ?? "decode service load failed")+ }+ inferenceMemory.withLock { $0 = event.currentMemoryBytes }+ connection.withLock { $0.loadedDirectory = modelDirectory.standardizedFileURL }+ onState(.ready(modelDirectory: modelDirectory, loadSeconds: 0))+ }++ public func unload() async {+ guard let handles = currentHandles() else { return }+ let requestID = UUID()+ try? handles.input.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceCommand.unload(requestID)))+ _ = try? await readEvent(from: handles.output)+ connection.withLock { $0.loadedDirectory = nil }+ inferenceMemory.withLock { $0 = nil }+ }++ public func generate(_ request: AppGenerationRequest)+ -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream { continuation in+ let task = Task.detached(priority: .userInitiated) { [self] in+ do {+ try request.validate()+ guard let handles = currentHandles() else {+ throw AppInferenceError.modelNotLoaded+ }+ let generationID = UUID()+ generationTranscriptMailbox.reset()+ let command = DecodeGenerationRequest(+ prompt: request.prompt, maxNewTokens: request.maxNewTokens,+ maxContextTokens: request.maxContextTokens,+ temperature: request.temperature,+ repetitionPenalty: request.repetitionPenalty,+ runtimeOptions: Self.decodeRuntimeOptions(request.runtimeOptions),+ generationID: generationID)+ try handles.input.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceCommand.generate(command)))++ var expectedSequence: UInt64 = 1+ var lastMetricYield = Date.distantPast+ while true {+ let event = try DecodeFrameCodec.read(+ DecodeServiceEvent.self, from: handles.output)+ inferenceMemory.withLock { $0 = event.currentMemoryBytes }+ guard event.generationID == generationID else { continue }++ if event.kind == .prefill || event.kind == .snapshot {+ guard event.sequence == expectedSequence else {+ throw AppInferenceError.unknown(+ "decode service event sequence changed from \(expectedSequence) to \(event.sequence)")+ }+ expectedSequence &+= 1+ }+ if event.kind == .prefill,+ let done = event.prefillDone,+ let total = event.prefillTotal {+ continuation.yield(.prefillProgress(done: done, total: total))+ continue+ }+ if event.kind == .snapshot {+ generationTranscriptMailbox.append(event.textDelta)+ let now = Date()+ if now.timeIntervalSince(lastMetricYield) >= 0.5 {+ lastMetricYield = now+ continuation.yield(.token(AppTokenEvent(+ index: max(0, event.tokenCount - 1),+ textDelta: "",+ elapsedDecodeSeconds: event.decodeSeconds)))+ }+ continue+ }++ let diagnostics = Self.diagnostics(+ event, options: request.runtimeOptions)+ switch event.kind {+ case .finished:+ continuation.yield(.finished(diagnostics))+ continuation.finish()+ case .cancelled:+ continuation.yield(.cancelled(diagnostics))+ continuation.finish()+ case .failed:+ let error = AppInferenceError.unknown(+ event.error ?? "decode service failed")+ continuation.yield(.failed(error, partial: diagnostics))+ continuation.finish(throwing: error)+ default:+ continue+ }+ return+ }+ } catch {+ continuation.finish(throwing: error)+ }+ }+ continuation.onTermination = { [weak self] _ in+ task.cancel()+ self?.cancel()+ }+ }+ }++ public func cancel() {+ guard let input = currentHandles()?.input else { return }+ try? input.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceCommand.cancel))+ }++ deinit {+ let state = connection.withLock { value -> Connection in+ defer { value = Connection() }+ return value+ }+ if let input = state.input {+ try? input.write(contentsOf: DecodeFrameCodec.encode(+ DecodeServiceCommand.shutdown))+ try? input.close()+ }+ if let label = state.launchLabel { Self.removeLaunchJob(label: label) }+ if let socketPath = state.socketPath { unlink(socketPath) }+ }++ private func ensureProcess() throws -> (input: FileHandle, output: FileHandle) {+ if let handles = currentHandles() { return handles }+ return try launchIndependentService()+ }++ private func launchIndependentService() throws+ -> (input: FileHandle, output: FileHandle) {+ guard FileManager.default.isExecutableFile(atPath: serviceURL.path) else {+ throw AppInferenceError.modelLoadFailed(+ "decode service executable is missing at \(serviceURL.path); run swift build -c release before launching the app")+ }+ let identifier = "\(getuid()).\(getpid()).\(UUID().uuidString.lowercased())"+ let label = "com.turbofieldfare.decode.\(identifier)"+ let socketPath = "/private/tmp/turbofieldfare-decode-\(identifier).sock"+ let propertyListURL = URL(+ fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)+ .appendingPathComponent("\(label).plist")+ let propertyList: [String: Any] = [+ "Label": label,+ "ProgramArguments": [+ serviceURL.path,+ "--socket", socketPath,+ "--launch-label", label,+ ],+ "RunAtLoad": true,+ "KeepAlive": false,+ "ProcessType": "Interactive",+ ]+ let propertyListData = try PropertyListSerialization.data(+ fromPropertyList: propertyList, format: .xml, options: 0)+ try propertyListData.write(to: propertyListURL, options: .atomic)+ defer { try? FileManager.default.removeItem(at: propertyListURL) }++ let launcher = Process()+ let errors = Pipe()+ launcher.executableURL = URL(fileURLWithPath: "/bin/launchctl")+ launcher.arguments = [+ "bootstrap", "gui/\(getuid())", propertyListURL.path,+ ]+ launcher.standardOutput = FileHandle.nullDevice+ launcher.standardError = errors+ try launcher.run()+ launcher.waitUntilExit()+ guard launcher.terminationStatus == 0 else {+ let data = try? errors.fileHandleForReading.readToEnd()+ let detail = data.flatMap { String(data: $0, encoding: .utf8) }?+ .trimmingCharacters(in: .whitespacesAndNewlines)+ let message = detail.flatMap { $0.isEmpty ? nil : $0 }+ ?? "launchd could not start the decode service"+ throw AppInferenceError.modelLoadFailed(message)+ }++ var lastError: Error?+ for _ in 0..<200 {+ do {+ let handles = try DecodeUnixSocket.connect(path: socketPath)+ connection.withLock {+ $0.input = handles.input+ $0.output = handles.output+ $0.launchLabel = label+ $0.socketPath = socketPath+ }+ return handles+ } catch {+ lastError = error+ usleep(10_000)+ }+ }+ Self.removeLaunchJob(label: label)+ throw AppInferenceError.modelLoadFailed(+ "decode service socket did not become ready: \(lastError.map(String.init(describing:)) ?? "unknown error")")+ }++ private func currentHandles() -> (input: FileHandle, output: FileHandle)? {+ connection.withLock { state in+ guard let input = state.input, let output = state.output else {+ return nil+ }+ return (input, output)+ }+ }++ private func readEvent(from output: FileHandle) async throws+ -> DecodeServiceEvent {+ try await Task.detached(priority: .userInitiated) {+ try DecodeFrameCodec.read(DecodeServiceEvent.self, from: output)+ }.value+ }++ private static func diagnostics(_ event: DecodeServiceEvent,+ options: AppRuntimeOptions) -> AppDiagnostics {+ let stop = AppStopReason(rawValue: event.stopReason ?? "")+ ?? (event.kind == .cancelled+ ? .cancelled+ : event.kind == .failed ? .failed : .maxTokens)+ return AppDiagnostics(+ generatedTokens: event.tokenCount,+ stopReason: stop,+ promptTokenCount: event.promptTokenCount,+ prefillSeconds: event.prefillSeconds,+ timeToFirstTokenSeconds: event.timeToFirstTokenSeconds,+ decodeSeconds: event.decodeSeconds,+ tokensPerSecond: event.tokensPerSecond,+ peakMemoryBytes: event.peakMemoryBytes,+ runtimeOptions: options,+ prefill: prefillDiagnostics(event.prefill, options: options),+ runner: event.runner.map(runnerDiagnostics))+ }++ private static func prefillDiagnostics(+ _ value: DecodePrefillDiagnostics?, options: AppRuntimeOptions+ ) -> PrefillExecutionDiagnostics? {+ guard let value,+ let executedMode = PrefillExecutedMode(rawValue: value.executedMode),+ let completeness = PrefillChunkCompleteness(+ rawValue: value.chunkCompleteness) else { return nil }+ let kvStorage = value.kvStorageMode.flatMap(PrefillKVStorageMode.init(rawValue:))+ return PrefillExecutionDiagnostics(+ config: options.prefillConfig,+ executedMode: executedMode,+ kvStorageMode: kvStorage,+ chunkCompleteness: completeness,+ unsupportedReason: value.unsupportedReason)+ }++ private static func runnerDiagnostics(_ value: DecodeRunnerDiagnostics)+ -> AppRunnerDiagnostics {+ AppRunnerDiagnostics(+ cb1MillisecondsPerToken: value.cb1MillisecondsPerToken,+ ioMillisecondsPerToken: value.ioMillisecondsPerToken,+ cb2MillisecondsPerToken: value.cb2MillisecondsPerToken,+ headMillisecondsPerToken: value.headMillisecondsPerToken,+ rdadviseMillisecondsPerToken: value.rdadviseMillisecondsPerToken,+ rdadviseCallsPerToken: value.rdadviseCallsPerToken,+ rdadviseMegabytesPerToken: value.rdadviseMegabytesPerToken,+ rdadviseSkippedPerToken: value.rdadviseSkippedPerToken,+ rdadviseFailures: value.rdadviseFailures)+ }++ private static func decodeRuntimeOptions(_ options: AppRuntimeOptions)+ -> DecodeRuntimeOptions {+ DecodeRuntimeOptions(+ expertCacheSlots: options.expertCacheSlots,+ expertCachePolicy: options.expertCachePolicy.rawValue,+ prefillEnabled: options.prefillEnabled,+ prefillChunkTokens: options.prefillChunkTokens,+ turboQuantKVEnabled: options.turboQuantKVEnabled,+ rdadvisePolicy: options.rdadvisePolicy.rawValue,+ modelVerification: options.modelVerification.rawValue)+ }++ private static func removeLaunchJob(label: String) {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/bin/launchctl")+ process.arguments = ["bootout", "gui/\(getuid())/\(label)"]+ process.standardOutput = FileHandle.nullDevice+ process.standardError = FileHandle.nullDevice+ try? process.run()+ process.waitUntilExit()+ }++ private static func defaultServiceURL() -> URL {+ return Bundle.main.executableURL!+ .deletingLastPathComponent()+ .appendingPathComponent("TurboFieldfareDecodeService")+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/GenerationTranscriptMailbox.swift b/Sources/TurboFieldfareApp/Core/Inference/GenerationTranscriptMailbox.swiftnew file mode 100644index 00000000..2f68fe90--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/GenerationTranscriptMailbox.swift@@ -0,0 +1,42 @@+import Foundation+import Synchronization++public final class GenerationTranscriptMailbox: Sendable {+ public struct Snapshot: Sendable {+ public let pendingText: String+ public let completeText: String+ }++ private struct State: Sendable {+ var pending = ""+ var complete = ""+ }++ private let state = Mutex(State())++ public init() {}++ public func append(_ text: String) {+ guard !text.isEmpty else { return }+ state.withLock {+ $0.pending += text+ $0.complete += text+ }+ }++ public func drain() -> Snapshot {+ state.withLock {+ let snapshot = Snapshot(pendingText: $0.pending, completeText: $0.complete)+ $0.pending = ""+ return snapshot+ }+ }++ public var completeText: String {+ state.withLock { $0.complete }+ }++ public func reset() {+ state.withLock { $0 = State() }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swiftnew file mode 100644index 00000000..06d96df0--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift@@ -0,0 +1,501 @@+import Foundation+import Metal+import TurboFieldfare+import Synchronization++final class GenerationTaskRegistry: Sendable {+ private struct Entry: Sendable {+ let id: UUID+ var task: Task<Void, Never>?+ }++ private let state = Mutex<Entry?>(nil)++ func reserve(_ id: UUID) -> Bool {+ state.withLock { entry in+ guard entry == nil else { return false }+ entry = Entry(id: id, task: nil)+ return true+ }+ }++ func attach(_ task: Task<Void, Never>, to id: UUID) {+ let shouldCancel = state.withLock { entry -> Bool in+ guard entry?.id == id else { return true }+ entry?.task = task+ return false+ }+ if shouldCancel { task.cancel() }+ }++ func take(_ id: UUID) -> Task<Void, Never>? {+ state.withLock { entry in+ guard entry?.id == id else { return nil }+ defer { entry = nil }+ return entry?.task+ }+ }++ func takeCurrent() -> Task<Void, Never>? {+ state.withLock { entry in+ defer { entry = nil }+ return entry?.task+ }+ }++ func clear(_ id: UUID) {+ state.withLock { entry in+ if entry?.id == id { entry = nil }+ }+ }++}++/// Real-model inference client for the Mac app. Wraps the same raw-completion+/// loop the CLI uses (`runRawCompletion`, BOS + verbatim encode, no chat+/// template) behind the `AppInferenceClient` event stream, with an explicit+/// load lifecycle so the resident weights stay warm across generations.+public final class RealInferenceClient: AppModelLifecycleClient, @unchecked Sendable {+ private let session: RealInferenceSession+ private let memorySampler: AppMemorySampler+ private let generationTasks = GenerationTaskRegistry()++ public init(memorySampler: AppMemorySampler = AppMemorySampler()) {+ self.memorySampler = memorySampler+ self.session = RealInferenceSession()+ }++ public func ensureLoaded(modelDirectory: URL,+ maxContextTokens: Int,+ options: AppRuntimeOptions,+ forceLogitsHead: Bool,+ onState: @escaping @Sendable (AppModelLoadState) -> Void) async throws {+ try await session.ensureLoaded(+ key: SessionLoadKey(directory: modelDirectory.standardizedFileURL,+ maxContext: maxContextTokens,+ options: options,+ forceLogitsHead: forceLogitsHead),+ onState: onState)+ }++ public func unload() async {+ await session.unload()+ }++ public func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream { continuation in+ let generationID = UUID()+ guard generationTasks.reserve(generationID) else {+ continuation.yield(.failed(.generationInFlight, partial: nil))+ continuation.finish(throwing: AppInferenceError.generationInFlight)+ return+ }+ let task = Task { [self] in+ await session.run(request: request,+ memorySampler: memorySampler,+ continuation: continuation)+ generationTasks.clear(generationID)+ }+ generationTasks.attach(task, to: generationID)++ continuation.onTermination = { [generationTasks] _ in+ generationTasks.take(generationID)?.cancel()+ }+ }+ }++ public func cancel() {+ generationTasks.takeCurrent()?.cancel()+ }++}++struct SessionLoadKey: Equatable, Sendable {+ var directory: URL+ var maxContext: Int+ var options: AppRuntimeOptions+ var forceLogitsHead: Bool++ init(directory: URL,+ maxContext: Int,+ options: AppRuntimeOptions,+ forceLogitsHead: Bool = false) {+ self.directory = directory.standardizedFileURL+ self.maxContext = maxContext+ self.options = options+ self.forceLogitsHead = forceLogitsHead+ }+}++struct TokenizerDirectoryCache: Equatable, Sendable {+ private(set) var directory: URL?++ func shouldReload(for modelDirectory: URL) -> Bool {+ directory != modelDirectory.standardizedFileURL+ }++ mutating func markLoaded(for modelDirectory: URL) {+ directory = modelDirectory.standardizedFileURL+ }++ mutating func clear() {+ directory = nil+ }+}++/// Owns the loaded model and serializes load / unload / generate. All Metal+/// command-buffer waits happen inside this actor, off the main actor; one+/// cooperative-pool thread is occupied for the duration of a generation,+/// which is acceptable for the app's single session. The 8 GB rule lives+/// here: a reload releases the loaded model, runner, and scratch before constructing+/// replacements, so two models are never alive at once.+actor RealInferenceSession {+ private var loadedKey: SessionLoadKey?+ private var ctx: MetalContext?+ private var tokenizer: GFTokenizer?+ private var tokenizerDirectoryCache = TokenizerDirectoryCache()+ private var runner: RealForwardRunner?+ private var scratch: RawCompletionScratch?++ func ensureLoaded(key: SessionLoadKey,+ onState: @Sendable (AppModelLoadState) -> Void) async throws {+ if loadedKey == key, runner != nil { return }++ runner = nil+ scratch = nil+ loadedKey = nil++ let start = Date()+ do {+ onState(.loading(.validatingDirectory))+ let manifest = key.directory.appendingPathComponent("manifest.json")+ guard FileManager.default.fileExists(atPath: manifest.path) else {+ throw AppInferenceError.modelNotFound(key.directory.path)+ }++ onState(.loading(.tokenizer))+ if tokenizer == nil || tokenizerDirectoryCache.shouldReload(for: key.directory) {+ do {+ tokenizer = try await Self.loadTokenizer(for: key.directory)+ tokenizerDirectoryCache.markLoaded(for: key.directory)+ } catch {+ throw AppInferenceError.tokenizerUnavailable("\(error)")+ }+ }+ try Task.checkCancellation()++ onState(.loading(.verifyingWeights))+ let runtimeConfiguration = try key.options.resolvedRuntimeConfiguration(+ forceLogitsHead: key.forceLogitsHead)+ let context: MetalContext+ if let ctx {+ context = ctx+ } else {+ context = try MetalContext()+ ctx = context+ }+ let loadedModel = try Model.load(+ directoryURL: key.directory,+ device: context.device,+ streamingMode: .pread(slotCount: runtimeConfiguration.expertCacheSlots),+ expertCachePolicy: runtimeConfiguration.modelExpertCachePolicy,+ integrityPolicy: key.options.modelVerification.runtimeValue)+ try Task.checkCancellation()++ onState(.loading(.preparingRunner))+ let loadedRunner = try RealForwardRunner(+ model: loadedModel,+ context: context,+ maxContext: key.maxContext,+ runtimeConfiguration: runtimeConfiguration)+ let loadedScratch = try RawCompletionScratch(context: context,+ vocab: loadedModel.config.vocabSize)+ try Task.checkCancellation()++ runner = loadedRunner+ scratch = loadedScratch+ loadedKey = key+ onState(.ready(modelDirectory: key.directory,+ loadSeconds: Date().timeIntervalSince(start)))+ } catch is CancellationError {+ throw CancellationError()+ } catch let appError as AppInferenceError {+ onState(.failed(appError))+ throw appError+ } catch {+ let appError = AppInferenceError.modelLoadFailed("\(error)")+ onState(.failed(appError))+ throw appError+ }+ }++ private static func loadTokenizer(for modelDirectory: URL) async throws -> GFTokenizer {+ try await GFTokenizer.load(forModelDirectory: modelDirectory)+ }++ static func forceLogitsHead(for request: AppGenerationRequest) -> Bool {+ !request.isPureGreedy+ }++ static func generationConfig(for request: AppGenerationRequest) -> GenerationConfig {+ GenerationConfig(maxNewTokens: request.maxNewTokens,+ temperature: request.temperature,+ topK: request.topK,+ topP: request.topP,+ repetitionPenalty: request.repetitionPenalty)+ }++ func unload() {+ runner = nil+ scratch = nil+ tokenizer = nil+ tokenizerDirectoryCache.clear()+ loadedKey = nil+ }++ func run(request: AppGenerationRequest,+ memorySampler: AppMemorySampler,+ continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation) async {+ let prefillConfig = request.runtimeOptions.prefillConfig+ let progress = ProgressState()+ do {+ try request.validate()+ let kvStorageMode: PrefillKVStorageMode =+ request.runtimeOptions.turboQuantKVEnabled ? .packedOnly : .fp16+ let executedPrefillMode: PrefillExecutedMode =+ prefillConfig.mode == .chunked ? .chunked : .off+ let prefillDiagnostics = PrefillExecutionDiagnostics(config: prefillConfig,+ executedMode: executedPrefillMode,+ kvStorageMode: kvStorageMode)+ let requestKey = SessionLoadKey(+ directory: request.modelDirectory.standardizedFileURL,+ maxContext: request.maxContextTokens,+ options: request.runtimeOptions,+ forceLogitsHead: Self.forceLogitsHead(for: request))+ guard let loadedKey else { throw AppInferenceError.modelNotLoaded }+ guard loadedKey == requestKey else { throw AppInferenceError.reloadRequired }+ guard let runner, let tokenizer, let ctx, let scratch else {+ throw AppInferenceError.modelLoadFailed("session lost its loaded state")+ }++ let promptIds = tokenizer.encode(request.prompt, addBOS: true)+ progress.promptTokenCount = promptIds.count+ guard promptIds.count + request.maxNewTokens <= runner.maxContext else {+ throw AppInferenceError.contextOverflow(prompt: promptIds.count,+ maxNew: request.maxNewTokens,+ maxContext: runner.maxContext)+ }+ memorySampler.resetPeak()+ _ = memorySampler.sample()+ let config = Self.generationConfig(for: request)+ runner.reset()+ progress.prefillStart = Date()++ let result = try await runRawCompletion(+ producer: runner, tokenizer: tokenizer, promptIds: promptIds,+ config: config, context: ctx, scratch: scratch,+ prefillConfig: prefillConfig) { event in+ switch event {+ case .prefill(let done, let total):+ if done == total {+ progress.decodeStart = Date()+ progress.countersAtDecodeStart = RunnerCounterSnapshot(runner)+ }+ continuation.yield(.prefillProgress(done: done, total: total))+ case .token(let index, _, let delta):+ if progress.firstTokenDate == nil { progress.firstTokenDate = Date() }+ progress.generated = index + 1+ if index % 8 == 0 { _ = memorySampler.sample() }+ continuation.yield(.token(AppTokenEvent(+ index: index,+ textDelta: delta,+ elapsedDecodeSeconds: progress.elapsedDecodeSeconds)))+ case .tail(let text):+ continuation.yield(.token(AppTokenEvent(+ index: max(progress.generated - 1, 0),+ textDelta: text,+ elapsedDecodeSeconds: progress.elapsedDecodeSeconds)))+ }+ }++ let diagnostics = makeDiagnostics(request: request,+ memorySampler: memorySampler,+ progress: progress,+ stopReason: Self.stopReason(result.reason),+ prefillSeconds: result.prefillSeconds,+ decodeSeconds: result.decodeSeconds,+ generated: result.newTokens,+ prefill: prefillDiagnostics)+ continuation.yield(.finished(diagnostics))+ continuation.finish()+ } catch is CancellationError {+ let diagnostics = makeDiagnostics(request: request,+ memorySampler: memorySampler,+ progress: progress,+ stopReason: .cancelled,+ prefillSeconds: progress.elapsedPrefillSeconds,+ decodeSeconds: progress.elapsedDecodeSeconds,+ generated: progress.generated,+ prefill: PrefillExecutionDiagnostics(+ config: prefillConfig,+ executedMode: prefillConfig.mode == .chunked ? .chunked : .off,+ kvStorageMode: request.runtimeOptions.turboQuantKVEnabled ? .packedOnly : .fp16))+ continuation.yield(.cancelled(diagnostics))+ continuation.finish(throwing: AppInferenceError.cancelled)+ } catch let prefillError as PrefillError {+ let kvStorageMode: PrefillKVStorageMode =+ request.runtimeOptions.turboQuantKVEnabled ? .packedOnly : .fp16+ let diagnostics = Self.prefillFailureDiagnostics(config: prefillConfig,+ kvStorageMode: kvStorageMode,+ reason: prefillError.description)+ failGeneration(.unknown(prefillError.description),+ request: request,+ memorySampler: memorySampler,+ progress: progress,+ continuation: continuation,+ prefill: diagnostics,+ forcePartialDiagnostics: true)+ } catch let appError as AppInferenceError {+ failGeneration(appError, request: request, memorySampler: memorySampler,+ progress: progress, continuation: continuation)+ } catch {+ failGeneration(.unknown("\(error)"), request: request, memorySampler: memorySampler,+ progress: progress, continuation: continuation)+ }+ }++ private func failGeneration(_ error: AppInferenceError,+ request: AppGenerationRequest,+ memorySampler: AppMemorySampler,+ progress: ProgressState,+ continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation,+ prefill: PrefillExecutionDiagnostics? = nil,+ forcePartialDiagnostics: Bool = false) {+ let partial = progress.generated > 0 || forcePartialDiagnostics+ ? makeDiagnostics(request: request, memorySampler: memorySampler,+ progress: progress, stopReason: .failed,+ prefillSeconds: progress.elapsedPrefillSeconds,+ decodeSeconds: progress.elapsedDecodeSeconds,+ generated: progress.generated,+ prefill: prefill)+ : nil+ continuation.yield(.failed(error, partial: partial))+ continuation.finish(throwing: error)+ }++ private func makeDiagnostics(request: AppGenerationRequest,+ memorySampler: AppMemorySampler,+ progress: ProgressState,+ stopReason: AppStopReason,+ prefillSeconds: Double? = nil,+ decodeSeconds: Double,+ generated: Int,+ prefill: PrefillExecutionDiagnostics? = nil) -> AppDiagnostics {+ _ = memorySampler.sample()+ let ttft: Double?+ if let first = progress.firstTokenDate, let start = progress.decodeStart {+ ttft = first.timeIntervalSince(start)+ } else {+ ttft = nil+ }+ return AppDiagnostics(+ generatedTokens: generated,+ stopReason: stopReason,+ promptTokenCount: progress.promptTokenCount,+ prefillSeconds: prefillSeconds,+ timeToFirstTokenSeconds: ttft,+ decodeSeconds: decodeSeconds,+ tokensPerSecond: decodeSeconds > 0 ? Double(generated) / decodeSeconds : 0,+ peakMemoryBytes: memorySampler.peakBytes,+ runtimeOptions: request.runtimeOptions,+ prefill: prefill,+ runner: runnerDiagnostics(progress: progress, generated: generated))+ }++ /// Per-token buckets as diffs of the runner's cumulative counters from the+ /// decode start (excludes prefill), divided by the decode forward count.+ /// The forward count is `generated - 1`: each loop iteration that continues+ /// ends with one `produce`; the final sampled token never runs a forward.+ private func runnerDiagnostics(progress: ProgressState, generated: Int) -> AppRunnerDiagnostics? {+ guard let runner, let base = progress.countersAtDecodeStart, generated > 1 else { return nil }+ let now = RunnerCounterSnapshot(runner)+ let forwards = Double(generated - 1)+ func ms(_ end: UInt64, _ start: UInt64) -> Double {+ Double(end &- start) / 1_000_000 / forwards+ }+ return AppRunnerDiagnostics(+ cb1MillisecondsPerToken: ms(now.cb1, base.cb1),+ ioMillisecondsPerToken: ms(now.io, base.io),+ cb2MillisecondsPerToken: ms(now.cb2, base.cb2),+ headMillisecondsPerToken: ms(now.head, base.head),+ rdadviseMillisecondsPerToken: ms(now.rdadvise, base.rdadvise),+ rdadviseCallsPerToken: Double(now.rdadviseCalls &- base.rdadviseCalls) / forwards,+ rdadviseMegabytesPerToken: Double(now.rdadviseBytes &- base.rdadviseBytes) / 1_048_576.0 / forwards,+ rdadviseSkippedPerToken: Double(now.rdadviseSkipped &- base.rdadviseSkipped) / forwards,+ rdadviseFailures: now.rdadviseFailures &- base.rdadviseFailures)+ }++ private static func stopReason(_ reason: StopReason) -> AppStopReason {+ switch reason {+ case .eos: return .eos+ case .endOfTurn: return .endOfTurn+ case .maxTokens: return .maxTokens+ case .stopString: return .stopString+ }+ }++ internal static func prefillFailureDiagnostics(config: PrefillRuntimeConfig,+ kvStorageMode: PrefillKVStorageMode,+ reason: String) -> PrefillExecutionDiagnostics {+ PrefillExecutionDiagnostics.unsupported(config: config,+ kvStorageMode: kvStorageMode,+ reason: reason)+ }+}++/// Mutable per-generation state shared between the progress callback and the+/// surrounding actor method. Single-threaded: the callback runs synchronously+/// inside `runRawCompletion` on the session actor's task.+private final class ProgressState: @unchecked Sendable {+ var generated = 0+ var promptTokenCount: Int?+ var prefillStart: Date?+ var decodeStart: Date?+ var firstTokenDate: Date?+ var countersAtDecodeStart: RunnerCounterSnapshot?++ var elapsedDecodeSeconds: Double {+ guard let decodeStart else { return 0 }+ return Date().timeIntervalSince(decodeStart)+ }++ var elapsedPrefillSeconds: Double? {+ guard let prefillStart else { return nil }+ let end = decodeStart ?? Date()+ return max(end.timeIntervalSince(prefillStart), 0)+ }+}++private struct RunnerCounterSnapshot {+ let cb1: UInt64+ let io: UInt64+ let cb2: UInt64+ let head: UInt64+ let rdadvise: UInt64+ let rdadviseCalls: UInt64+ let rdadviseBytes: UInt64+ let rdadviseFailures: UInt64+ let rdadviseSkipped: UInt64++ init(_ runner: RealForwardRunner) {+ cb1 = runner.totalCb1Nanos+ io = runner.totalIoNanos+ cb2 = runner.totalCb2Nanos+ head = runner.totalHeadNanos &+ runner.totalHeadFusedNanos+ rdadvise = runner.totalRDAdviseNanos+ rdadviseCalls = runner.totalRDAdviseCalls+ rdadviseBytes = runner.totalRDAdviseBytes+ rdadviseFailures = runner.totalRDAdviseFailures+ rdadviseSkipped = runner.totalRDAdviseSkipped+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swiftnew file mode 100644index 00000000..67ebe73b--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift@@ -0,0 +1,73 @@+import Foundation+import TurboFieldfareRepackCore++public struct AppModelInstallDescriptor: Equatable, Sendable {+ public let displayName: String+ public let repoID: String+ public let revision: String+ public let approximateDownloadBytes: UInt64+ public let installedBytes: UInt64+ public let rangeStagingBytes: UInt64+ public let reserveBytes: UInt64++ public init(displayName: String,+ repoID: String,+ revision: String,+ approximateDownloadBytes: UInt64,+ installedBytes: UInt64,+ rangeStagingBytes: UInt64,+ reserveBytes: UInt64) {+ self.displayName = displayName+ self.repoID = repoID+ self.revision = revision+ self.approximateDownloadBytes = approximateDownloadBytes+ self.installedBytes = installedBytes+ self.rangeStagingBytes = rangeStagingBytes+ self.reserveBytes = reserveBytes+ }++ public var requiredFreeBytes: UInt64 {+ installedBytes + rangeStagingBytes + reserveBytes+ }++ public static let `default` = AppModelInstallDescriptor(+ displayName: SupportedModelSource.displayName,+ repoID: SupportedModelSource.repoID,+ revision: SupportedModelSource.revision,+ approximateDownloadBytes: SupportedModelSource.approximateDownloadBytes,+ installedBytes: SupportedModelSource.installedBytes,+ rangeStagingBytes: UInt64(RemoteChunkPolicy.defaultBytes),+ reserveBytes: SupportedModelSource.reserveBytes)+}++public struct AppModelInstallRequirement: Equatable, Sendable {+ public let requiredBytes: UInt64+ public let availableBytes: UInt64++ public init(requiredBytes: UInt64, availableBytes: UInt64) {+ self.requiredBytes = requiredBytes+ self.availableBytes = availableBytes+ }++ public var canInstall: Bool { availableBytes >= requiredBytes }++ public var shortfallBytes: UInt64 {+ requiredBytes > availableBytes ? requiredBytes - availableBytes : 0+ }+}++public enum AppModelInstallReadiness: Equatable, Sendable {+ case checking+ case ready(AppModelInstallRequirement)+ case insufficientSpace(AppModelInstallRequirement)+ case failed(String)++ public var requirement: AppModelInstallRequirement? {+ switch self {+ case .ready(let requirement), .insufficientSpace(let requirement):+ return requirement+ case .checking, .failed:+ return nil+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swiftnew file mode 100644index 00000000..1ecf0a33--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift@@ -0,0 +1,47 @@+import Foundation++public enum AppModelInstallState: Equatable, Sendable {+ case idle+ case checking+ case downloadingMetadata+ case planning+ case reservingOutput+ case copyingPayload(doneBytes: UInt64, totalBytes: UInt64)+ case hashingOutput(String)+ case finalizing+ case cancelling+ case cancelled+ case installed(modelDirectory: URL)+ case failed(String)++ public var isInstalling: Bool {+ switch self {+ case .checking, .downloadingMetadata, .planning, .reservingOutput,+ .copyingPayload, .hashingOutput, .finalizing, .cancelling:+ return true+ case .idle, .cancelled, .installed, .failed:+ return false+ }+ }++ public var canCancel: Bool {+ switch self {+ case .checking, .downloadingMetadata, .planning, .reservingOutput,+ .copyingPayload, .hashingOutput, .finalizing:+ return true+ case .idle, .cancelling, .cancelled, .installed, .failed:+ return false+ }+ }+}++public enum AppModelInstallEvent: Equatable, Sendable {+ case checking+ case downloadingMetadata+ case planning+ case reservingOutput+ case copyingPayload(doneBytes: UInt64, totalBytes: UInt64)+ case hashingOutput(String)+ case finalizing+ case installed(URL)+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallationProbe.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallationProbe.swiftnew file mode 100644index 00000000..7401d9d3--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallationProbe.swift@@ -0,0 +1,35 @@+import Foundation+import TurboFieldfare++public enum AppModelInstallationStatus: Equatable, Sendable {+ case missing+ case partial(String)+ case complete+}++enum AppModelInstallationProbe {+ static func status(at directory: URL) -> AppModelInstallationStatus {+ let directory = directory.standardizedFileURL+ let manifestURL = directory.appendingPathComponent("manifest.json")+ guard FileManager.default.fileExists(atPath: manifestURL.path) else {+ return .missing+ }++ do {+ _ = try ManifestReader.load(directoryURL: directory, expecting: .gemma4_26B_A4B)+ let layout = directory.appendingPathComponent("packed_experts/layout.json")+ guard FileManager.default.fileExists(atPath: layout.path) else {+ return .partial("packed_experts/layout.json is missing")+ }+ let receipt = try VerifiedInstallReceiptReader.load(directoryURL: directory)+ let manifestHash = try Sha256Verifier.hashFile(at: manifestURL, chunkBytes: 65_536)+ try VerifiedInstallReceiptReader.validateManifestBinding(+ receipt,+ directoryURL: directory,+ manifestSha256: manifestHash)+ return .complete+ } catch {+ return .partial("\(error)")+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallerClient.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallerClient.swiftnew file mode 100644index 00000000..acec028a--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallerClient.swift@@ -0,0 +1,8 @@+import Foundation++public protocol AppModelInstallerClient: Sendable {+ var descriptor: AppModelInstallDescriptor { get }+ func checkInstallRequirement(outputDirectory: URL) throws -> AppModelInstallRequirement+ func installDefaultModel(outputDirectory: URL) -> AsyncThrowingStream<AppModelInstallEvent, Error>+ func cancel()+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelLocation.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelLocation.swiftnew file mode 100644index 00000000..7f8f44a3--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelLocation.swift@@ -0,0 +1,67 @@+import Foundation++enum AppModelLocation {+ static func defaultURL() -> URL {+ let fileManager = FileManager.default+ let applicationSupport = (try? fileManager.url(+ for: .applicationSupportDirectory,+ in: .userDomainMask,+ appropriateFor: nil,+ create: false)) ?? fileManager.homeDirectoryForCurrentUser+ return resolve(+ explicitURL: nil,+ executableURL: Bundle.main.executableURL,+ currentDirectoryURL: URL(fileURLWithPath: fileManager.currentDirectoryPath,+ isDirectory: true),+ applicationSupportURL: applicationSupport,+ fileExists: fileManager.fileExists(atPath:))+ }++ static func resolve(explicitURL: URL?,+ executableURL: URL?,+ currentDirectoryURL: URL,+ applicationSupportURL: URL,+ fileExists: (String) -> Bool) -> URL {+ if let explicitURL {+ return absoluteURL(explicitURL, relativeTo: currentDirectoryURL)+ }+ if let executableURL,+ let root = packageRoot(startingAt: executableURL.deletingLastPathComponent(),+ fileExists: fileExists) {+ return root.appendingPathComponent("scratch/gemma4.gturbo", isDirectory: true)+ .standardizedFileURL+ }+ if let root = packageRoot(startingAt: currentDirectoryURL, fileExists: fileExists) {+ return root.appendingPathComponent("scratch/gemma4.gturbo", isDirectory: true)+ .standardizedFileURL+ }+ return applicationSupportURL+ .appendingPathComponent("TurboFieldfare", isDirectory: true)+ .appendingPathComponent("gemma4.gturbo", isDirectory: true)+ .standardizedFileURL+ }++ private static func absoluteURL(_ url: URL, relativeTo base: URL) -> URL {+ if url.path.hasPrefix("/") {+ return url.standardizedFileURL+ }+ return base.appendingPathComponent(url.path, isDirectory: true).standardizedFileURL+ }++ private static func packageRoot(startingAt start: URL,+ fileExists: (String) -> Bool) -> URL? {+ var candidatePath = start.standardizedFileURL.path+ while true {+ let candidate = URL(fileURLWithPath: candidatePath, isDirectory: true)+ let package = candidate.appendingPathComponent("Package.swift").path+ let appSources = candidate.appendingPathComponent(+ "Sources/TurboFieldfareApp/Mac", isDirectory: true).path+ if fileExists(package), fileExists(appSources) {+ return candidate+ }+ let parentPath = (candidatePath as NSString).deletingLastPathComponent+ if parentPath.isEmpty || parentPath == candidatePath { return nil }+ candidatePath = parentPath+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/RepackModelInstallerClient.swift b/Sources/TurboFieldfareApp/Core/Installation/RepackModelInstallerClient.swiftnew file mode 100644index 00000000..9a06369f--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/RepackModelInstallerClient.swift@@ -0,0 +1,115 @@+import Foundation+import TurboFieldfareRepackCore+import Synchronization++public final class RepackModelInstallerClient: AppModelInstallerClient, Sendable {+ typealias InstallRunner = @Sendable (+ URL,+ @escaping @Sendable (ModelInstallProgress) -> Void+ ) async throws -> URL++ private struct ActiveInstall: Sendable {+ let id: UUID+ let task: Task<Void, Never>+ }++ private final class InstallTaskState: Sendable {+ let value = Mutex<ActiveInstall?>(nil)+ }++ public let descriptor: AppModelInstallDescriptor+ private let runInstall: InstallRunner+ private let taskState = InstallTaskState()++ public init(descriptor: AppModelInstallDescriptor = .default) {+ self.descriptor = descriptor+ self.runInstall = { outputDirectory, progress in+ let options = SupportedModelSource.installOptions(+ outputDirectory: outputDirectory,+ overwrite: true,+ token: ProcessInfo.processInfo.environment["HF_TOKEN"],+ retainPartialOnFailure: false)+ let result = try await RemoteStreamingRepacker(options: options).run(progress: progress)+ return URL(fileURLWithPath: result.outputDir).standardizedFileURL+ }+ }++ init(descriptor: AppModelInstallDescriptor = .default,+ runInstall: @escaping InstallRunner) {+ self.descriptor = descriptor+ self.runInstall = runInstall+ }++ public func checkInstallRequirement(outputDirectory: URL) throws -> AppModelInstallRequirement {+ let requirement = try DiskSpaceChecker.assess(+ path: outputDirectory.path,+ bytes: descriptor.installedBytes + descriptor.rangeStagingBytes,+ reserveBytes: descriptor.reserveBytes)+ return AppModelInstallRequirement(requiredBytes: requirement.requiredBytes,+ availableBytes: requirement.availableBytes)+ }++ public func installDefaultModel(outputDirectory: URL) -> AsyncThrowingStream<AppModelInstallEvent, Error> {+ AsyncThrowingStream { continuation in+ let id = UUID()+ let task = Task { [runInstall] in+ do {+ continuation.yield(.checking)+ let completedDirectory = try await runInstall(outputDirectory) { progress in+ continuation.yield(Self.event(for: progress))+ }+ try Task.checkCancellation()+ continuation.yield(.installed(completedDirectory))+ continuation.finish()+ } catch is CancellationError {+ continuation.finish(throwing: CancellationError())+ } catch {+ continuation.finish(throwing: error)+ }+ }++ let previous = taskState.value.withLock { active in+ let previous = active?.task+ active = ActiveInstall(id: id, task: task)+ return previous+ }+ previous?.cancel()++ continuation.onTermination = { [taskState] _ in+ let task = taskState.value.withLock { active -> Task<Void, Never>? in+ guard active?.id == id else { return nil }+ defer { active = nil }+ return active?.task+ }+ task?.cancel()+ }+ }+ }++ public func cancel() {+ let task = taskState.value.withLock { active -> Task<Void, Never>? in+ defer { active = nil }+ return active?.task+ }+ task?.cancel()+ }++ static func event(for progress: ModelInstallProgress) -> AppModelInstallEvent {+ switch progress {+ case .downloadingMetadata:+ return .downloadingMetadata+ case .planning:+ return .planning+ case .checkingDisk:+ return .checking+ case .reservingOutput:+ return .reservingOutput+ case .copyingPayload(let downloaded, let total):+ return .copyingPayload(doneBytes: downloaded, totalBytes: total)+ case .hashingOutput(let file):+ return .hashingOutput(file)+ case .finalizing:+ return .finalizing+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftnew file mode 100644index 00000000..a3b5b295--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -0,0 +1,621 @@+import Foundation+import TurboFieldfareRepackCore+import Observation++@MainActor+@Observable+public final class AppModel {+ public enum RunState: Equatable {+ case idle+ case running+ }++ public var modelPathText: String+ public var promptText: String = ""+ public private(set) var outputPromptText: String = ""+ public var outputText: String = ""+ public var runState: RunState = .idle+ public var runtimeOptions = AppRuntimeOptions()+ public var maxNewTokens: Int = 1_024+ public var maxContextTokens: Int = 4096+ public var temperature: Double = 0.1+ public var topKEnabled: Bool = true+ public var topK: Int = 64+ public var topPEnabled: Bool = true+ public var topP: Double = 0.95+ public var repetitionPenaltyEnabled: Bool = false+ public var repetitionPenalty: Double = 1.1+ public var diagnostics: AppDiagnostics?+ public var error: AppInferenceError?+ public var installState: AppModelInstallState = .idle+ public private(set) var installReadiness: AppModelInstallReadiness = .checking+ public private(set) var installationStatus: AppModelInstallationStatus++ public var loadState: AppModelLoadState = .notLoaded+ public private(set) var loadedRuntimeKey: AppLoadedRuntimeKey?+ public private(set) var phase: AppGenerationPhase = .idle+ public private(set) var liveTokenCount: Int = 0+ public private(set) var liveElapsedDecodeSeconds: Double = 0+ public private(set) var livePrefillDone: Int = 0+ public private(set) var livePrefillTotal: Int = 0+ public private(set) var liveMemoryBytes: UInt64?+ public private(set) var isCancellationPending: Bool = false++ private let client: any AppInferenceClient+ private let installer: any AppModelInstallerClient+ private var runTask: Task<Void, Never>?+ private var loadTask: Task<Void, Never>?+ private var installTask: Task<Void, Never>?+ private var unloadTask: Task<Void, Never>?+ private var loadGeneration: UInt64 = 0+ private var unloadGeneration: UInt64 = 0+ private var installGeneration: UInt64 = 0+ private var pendingExplicitLoadRuntimeKey: AppLoadedRuntimeKey?+ private var activeRunRuntimeKey: AppLoadedRuntimeKey?+ private var hasHandledTerminalEvent = false+ private let memorySampler: AppMemorySampler++ public init(modelDirectory: URL? = nil,+ client: any AppInferenceClient = RealInferenceClient(),+ installer: any AppModelInstallerClient = RepackModelInstallerClient(),+ memorySampler: AppMemorySampler = AppMemorySampler()) {+ let directory = (modelDirectory ?? AppModelLocation.defaultURL()).standardizedFileURL+ self.modelPathText = directory.path+ self.installationStatus = AppModelInstallationProbe.status(at: directory)+ self.client = client+ self.installer = installer+ self.memorySampler = memorySampler+ refreshInstallReadiness()+ }++ public var isRunning: Bool { runState == .running }++ public var isModelAvailable: Bool { loadState.isReady }++ public var hasStaleLoadedRuntime: Bool {+ guard loadState.isReady, let loadedRuntimeKey else { return false }+ return loadedRuntimeKey != currentRuntimeKey+ }++ public var canLoadModel: Bool {+ isModelInstalled && !isRunning && (loadState == .notLoaded || loadState.isFailed)+ }++ public var canCancelLoad: Bool {+ if case .loading = loadState { return loadTask != nil }+ return false+ }++ public var canReloadModel: Bool {+ isModelInstalled && !isRunning && loadState.isReady && hasStaleLoadedRuntime+ }++ public var canUnloadModel: Bool {+ isModelInstalled && !isRunning && loadState.isReady+ }++ public var isModelInstalled: Bool { installationStatus == .complete }++ public var requiresModelInstallation: Bool { !isModelInstalled }++ public var installDescriptor: AppModelInstallDescriptor { installer.descriptor }++ public var installRequirement: AppModelInstallRequirement? {+ installReadiness.requirement+ }++ public var isInstallingModel: Bool { installState.isInstalling }++ public var canInstallModel: Bool {+ guard case .ready = installReadiness else { return false }+ return !isRunning && !loadState.isLoading && !isInstallingModel+ && requiresModelInstallation+ }++ public var canCancelInstall: Bool { installState.canCancel }++ public var installDownloadedBytes: UInt64? {+ guard case .copyingPayload(let done, _) = installState else { return nil }+ return done+ }++ public var installTotalBytes: UInt64? {+ guard case .copyingPayload(_, let total) = installState else { return nil }+ return total+ }++ public var installProgressFraction: Double? {+ guard case .copyingPayload(let done, let total) = installState, total > 0 else {+ return nil+ }+ return min(max(Double(done) / Double(total), 0), 1)+ }++ public var canRun: Bool {+ !isRunning && isModelAvailable && !loadState.isLoading+ && !hasStaleLoadedRuntime+ && !promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }++ public var canCancel: Bool { isRunning && !isCancellationPending }++ public var hasOutputTranscript: Bool {+ !outputPromptText.isEmpty || !outputText.isEmpty+ }++ public var outputPlainText: String {+ let completion = generationTranscriptMailbox?.completeText ?? outputText+ switch (outputPromptText.isEmpty, completion.isEmpty) {+ case (true, true):+ return ""+ case (false, true):+ return outputPromptText+ case (true, false):+ return completion+ case (false, false):+ return outputPromptText + completion+ }+ }++ public var liveTokensPerSecond: Double {+ liveElapsedDecodeSeconds > 0 ? Double(liveTokenCount) / liveElapsedDecodeSeconds : 0+ }++ public var presentation: AppPresentationState {+ AppPresentationState.resolve(AppPresentationSnapshot(+ requiresInstallation: requiresModelInstallation,+ installState: installState,+ installReadiness: installReadiness,+ loadState: loadState,+ hasStaleRuntime: hasStaleLoadedRuntime,+ isRunning: isRunning,+ isGenerationCancellationPending: isCancellationPending,+ generationPhase: phase,+ livePrefillDone: livePrefillDone,+ livePrefillTotal: livePrefillTotal,+ lastStopReason: diagnostics?.stopReason))+ }++ public var currentProcessMemoryBytes: UInt64? {+ guard loadState.isReady || isRunning else { return nil }+ if let reporter = client as? any AppInferenceMemoryReporting,+ let bytes = reporter.currentInferenceMemoryBytes {+ return bytes+ }+ return memorySampler.sample()+ }++ public var generationTranscriptMailbox: GenerationTranscriptMailbox? {+ (client as? any AppInferenceTranscriptReporting)?.generationTranscriptMailbox+ }++ private var currentRuntimeKey: AppLoadedRuntimeKey {+ AppLoadedRuntimeKey(modelDirectory: URL(fileURLWithPath: modelPathText),+ maxContextTokens: maxContextTokens,+ options: runtimeOptions,+ forceLogitsHead: currentForceLogitsHead)+ }++ private var currentForceLogitsHead: Bool {+ temperature != 0 || (repetitionPenaltyEnabled && repetitionPenalty != 1)+ }++ public func setModelURL(_ url: URL) {+ guard !isRunning else { return }+ let path = url.standardizedFileURL.path+ guard path != modelPathText else { return }++ modelPathText = path+ loadGeneration &+= 1+ loadTask?.cancel()+ loadTask = nil+ installGeneration &+= 1+ installTask?.cancel()+ installer.cancel()+ installTask = nil+ installState = .idle+ pendingExplicitLoadRuntimeKey = nil+ activeRunRuntimeKey = nil+ loadedRuntimeKey = nil+ loadState = .notLoaded+ diagnostics = nil+ error = nil+ phase = .idle+ installationStatus = AppModelInstallationProbe.status(at: URL(fileURLWithPath: path))+ refreshInstallReadiness()++ if let lifecycle = client as? AppModelLifecycleClient {+ unloadGeneration &+= 1+ let generation = unloadGeneration+ let task = Task { [weak self, lifecycle] in+ await lifecycle.unload()+ self?.clearUnloadTask(generation: generation)+ }+ unloadTask = task+ }+ }++ public func loadModel() {+ guard canLoadModel else { return }+ beginLoad()+ }++ public func reloadModel() {+ guard canReloadModel else { return }+ beginLoad()+ }++ private func beginLoad() {+ guard let lifecycle = client as? AppModelLifecycleClient else {+ loadState = .failed(.modelLoadFailed("This client has no model load lifecycle."))+ return+ }+ let directory = URL(fileURLWithPath: modelPathText)+ let maxContext = maxContextTokens+ let options = runtimeOptions+ let forceLogitsHead = currentForceLogitsHead+ let runtimeKey = AppLoadedRuntimeKey(modelDirectory: directory,+ maxContextTokens: maxContext,+ options: options,+ forceLogitsHead: forceLogitsHead)+ let pendingUnload = unloadTask+ loadGeneration &+= 1+ let generation = loadGeneration+ pendingExplicitLoadRuntimeKey = runtimeKey+ error = nil+ loadState = .loading(.validatingDirectory)+ loadTask = Task.detached { [weak self, lifecycle, pendingUnload] in+ do {+ await pendingUnload?.value+ try Task.checkCancellation()+ try await lifecycle.ensureLoaded(modelDirectory: directory,+ maxContextTokens: maxContext,+ options: options,+ forceLogitsHead: forceLogitsHead) { [weak self] state in+ Task { @MainActor in+ self?.applyLoadState(state, generation: generation)+ }+ }+ } catch is CancellationError {+ } catch {+ // The attempt-local state relay already surfaced the failure.+ }+ await self?.clearLoadTask(generation: generation)+ }+ }++ public func cancelLoad() {+ guard canCancelLoad, let lifecycle = client as? AppModelLifecycleClient else { return }+ loadState = .cancelling+ loadGeneration &+= 1+ loadTask?.cancel()+ loadTask = nil+ pendingExplicitLoadRuntimeKey = nil+ unloadGeneration &+= 1+ let generation = unloadGeneration+ unloadTask = Task { [weak self, lifecycle] in+ await lifecycle.unload()+ guard let self, generation == self.unloadGeneration else { return }+ self.loadedRuntimeKey = nil+ self.loadState = .notLoaded+ self.clearUnloadTask(generation: generation)+ }+ }++ public func unloadModel() {+ guard canUnloadModel, let lifecycle = client as? AppModelLifecycleClient else { return }+ loadState = .unloading+ unloadGeneration &+= 1+ let generation = unloadGeneration+ unloadTask = Task { [weak self, lifecycle] in+ await lifecycle.unload()+ guard let self, generation == self.unloadGeneration else { return }+ self.loadedRuntimeKey = nil+ self.liveMemoryBytes = nil+ self.loadState = .notLoaded+ self.clearUnloadTask(generation: generation)+ }+ }++ public func installModel() {+ guard !isRunning, !loadState.isLoading, !isInstallingModel,+ requiresModelInstallation else {+ return+ }+ refreshInstallReadiness()+ guard canInstallModel else { return }+ installTask?.cancel()+ installer.cancel()+ let outputDirectory = URL(fileURLWithPath: modelPathText)+ installGeneration &+= 1+ let generation = installGeneration+ installState = .checking+ installTask = Task { [weak self, installer] in+ do {+ for try await event in installer.installDefaultModel(outputDirectory: outputDirectory) {+ guard let self else { return }+ self.applyInstallEvent(event, generation: generation)+ }+ self?.finishInstallStream(generation: generation)+ } catch is CancellationError {+ self?.finishInstallCancellation(generation: generation)+ } catch {+ self?.finishInstallFailure(error, generation: generation)+ }+ }+ }++ public func cancelInstall() {+ guard canCancelInstall else { return }+ installState = .cancelling+ installer.cancel()+ installTask?.cancel()+ }++ public func refreshInstallReadiness() {+ guard !isModelInstalled else { return }+ installReadiness = .checking+ do {+ let requirement = try installer.checkInstallRequirement(+ outputDirectory: URL(fileURLWithPath: modelPathText))+ installReadiness = requirement.canInstall+ ? .ready(requirement)+ : .insufficientSpace(requirement)+ } catch {+ installReadiness = .failed("\(error)")+ }+ }++ private func applyInstallEvent(_ event: AppModelInstallEvent, generation: UInt64) {+ guard generation == installGeneration else { return }+ switch event {+ case .checking:+ installState = .checking+ case .downloadingMetadata:+ installState = .downloadingMetadata+ case .planning:+ installState = .planning+ case .reservingOutput:+ installState = .reservingOutput+ case .copyingPayload(let done, let total):+ installState = .copyingPayload(doneBytes: done, totalBytes: total)+ case .hashingOutput(let file):+ installState = .hashingOutput(file)+ case .finalizing:+ installState = .finalizing+ case .installed(let directory):+ let directory = directory.standardizedFileURL+ installationStatus = AppModelInstallationProbe.status(at: directory)+ guard installationStatus == .complete else {+ finishInstallFailure(+ RepackError.configurationInvalid(detail: "completed install did not pass metadata validation"),+ generation: generation)+ return+ }+ installState = .installed(modelDirectory: directory)+ installTask = nil+ modelPathText = directory.path+ loadState = .notLoaded+ }+ }++ private func finishInstallStream(generation: UInt64) {+ guard generation == installGeneration, installTask != nil else { return }+ if installState == .cancelling {+ finishInstallCancellation(generation: generation)+ } else if !isModelInstalled {+ finishInstallFailure(+ RepackError.configurationInvalid(detail: "installer ended before completion"),+ generation: generation)+ }+ }++ private func finishInstallCancellation(generation: UInt64) {+ guard generation == installGeneration else { return }+ installTask = nil+ installState = .cancelled+ refreshInstallReadiness()+ }++ private func finishInstallFailure(_ error: Error, generation: UInt64) {+ guard generation == installGeneration else { return }+ installTask = nil+ installState = .failed("\(error)")+ if let repackError = error as? RepackError,+ case .diskSpaceInsufficient(_, let required, let available) = repackError {+ let requirement = AppModelInstallRequirement(requiredBytes: required,+ availableBytes: available)+ installReadiness = .insufficientSpace(requirement)+ } else {+ refreshInstallReadiness()+ }+ }++ func applyLoadState(_ state: AppModelLoadState) {+ applyLoadState(state, generation: loadGeneration)+ }++ private func applyLoadState(_ state: AppModelLoadState, generation: UInt64) {+ guard generation == loadGeneration else { return }+ if case .ready(let directory, _) = state,+ directory.standardizedFileURL.path+ != URL(fileURLWithPath: modelPathText).standardizedFileURL.path {+ return+ }+ loadState = state+ switch state {+ case .notLoaded:+ loadedRuntimeKey = nil+ case .loading, .cancelling, .unloading:+ break+ case .ready:+ loadedRuntimeKey = pendingExplicitLoadRuntimeKey+ ?? activeRunRuntimeKey+ ?? currentRuntimeKey+ pendingExplicitLoadRuntimeKey = nil+ case .failed(let loadError):+ pendingExplicitLoadRuntimeKey = nil+ error = loadError+ }+ }++ public func clearOutput() {+ guard !isRunning else { return }+ outputPromptText = ""+ outputText = ""+ generationTranscriptMailbox?.reset()+ diagnostics = nil+ error = nil+ }++ public func run() {+ guard canRun else { return }+ let request: AppGenerationRequest+ do {+ request = try makeRequest()+ } catch let appError as AppInferenceError {+ error = appError+ return+ } catch {+ let appError = AppInferenceError.unknown("\(error)")+ self.error = appError+ return+ }++ generationTranscriptMailbox?.reset()+ outputPromptText = request.prompt+ outputText = ""+ diagnostics = nil+ error = nil+ hasHandledTerminalEvent = false+ activeRunRuntimeKey = AppLoadedRuntimeKey(+ modelDirectory: request.modelDirectory,+ maxContextTokens: request.maxContextTokens,+ options: request.runtimeOptions,+ forceLogitsHead: !request.isPureGreedy)+ isCancellationPending = false+ liveTokenCount = 0+ liveElapsedDecodeSeconds = 0+ livePrefillDone = 0+ livePrefillTotal = 0+ liveMemoryBytes = nil+ phase = .prefill+ runState = .running++ runTask = Task.detached { [weak self, client, request] in+ guard let self else { return }+ do {+ for try await event in client.generate(request) {+ await self.apply(event)+ }+ } catch let appError as AppInferenceError {+ await self.finishStreamFailure(appError)+ } catch {+ await self.finishStreamFailure(.unknown("\(error)"))+ }+ }+ }++ public func cancel() {+ guard canCancel else { return }+ isCancellationPending = true+ client.cancel()+ }++ public func makeRequest() throws -> AppGenerationRequest {+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: modelPathText),+ prompt: promptText,+ maxNewTokens: maxNewTokens,+ maxContextTokens: maxContextTokens,+ temperature: Float(temperature),+ topK: topKEnabled ? topK : nil,+ topP: topKEnabled && topPEnabled ? Float(topP) : nil,+ repetitionPenalty: repetitionPenaltyEnabled ? Float(repetitionPenalty) : 1.0,+ runtimeOptions: runtimeOptions)+ try request.validate(requireModelDirectory: true)+ return request+ }++ func apply(_ event: AppInferenceEvent) {+ switch event {+ case .prefillProgress(let done, let total):+ phase = .prefill+ livePrefillDone = done+ livePrefillTotal = total+ case .token(let token):+ phase = .decode+ liveTokenCount = token.index + 1+ liveElapsedDecodeSeconds = token.elapsedDecodeSeconds+ if let reporter = client as? any AppInferenceMemoryReporting {+ liveMemoryBytes = reporter.currentInferenceMemoryBytes+ } else {+ liveMemoryBytes = memorySampler.sample()+ }+ if !token.textDelta.isEmpty {+ outputText += token.textDelta+ }+ case .finished(let diagnostics):+ finishSuccessfully(diagnostics)+ case .cancelled(let diagnostics):+ finishCancelled(diagnostics)+ case .failed(let appError, let partial):+ diagnostics = partial+ materializeServiceTranscript()+ finishWithError(appError)+ }+ }++ private func finishSuccessfully(_ diagnostics: AppDiagnostics) {+ guard !hasHandledTerminalEvent else { return }+ hasHandledTerminalEvent = true+ materializeServiceTranscript()+ self.diagnostics = diagnostics+ finishTerminalRun()+ }++ private func finishCancelled(_ diagnostics: AppDiagnostics) {+ guard !hasHandledTerminalEvent else { return }+ hasHandledTerminalEvent = true+ materializeServiceTranscript()+ self.diagnostics = diagnostics+ error = .cancelled+ finishTerminalRun()+ }++ private func materializeServiceTranscript() {+ guard let reporter = client as? any AppInferenceTranscriptReporting else { return }+ outputText = reporter.generationTranscriptMailbox.completeText+ }++ private func finishWithError(_ appError: AppInferenceError) {+ guard !hasHandledTerminalEvent else { return }+ hasHandledTerminalEvent = true+ error = appError+ finishTerminalRun()+ }++ private func finishStreamFailure(_ appError: AppInferenceError) {+ materializeServiceTranscript()+ finishWithError(appError)+ }++ private func finishTerminalRun() {+ phase = .idle+ runState = .idle+ isCancellationPending = false+ activeRunRuntimeKey = nil+ runTask = nil+ }++ private func clearLoadTask(generation: UInt64) {+ guard generation == loadGeneration else { return }+ loadTask = nil+ pendingExplicitLoadRuntimeKey = nil+ }++ private func clearUnloadTask(generation: UInt64) {+ guard generation == unloadGeneration else { return }+ unloadTask = nil+ }+}diff --git a/Sources/TurboFieldfareApp/Core/State/AppModelLoadState.swift b/Sources/TurboFieldfareApp/Core/State/AppModelLoadState.swiftnew file mode 100644index 00000000..e3da1037--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/State/AppModelLoadState.swift@@ -0,0 +1,49 @@+import Foundation++public enum AppModelLoadPhase: Equatable, Sendable {+ case validatingDirectory+ case tokenizer+ case verifyingWeights+ case preparingRunner++ public var label: String {+ switch self {+ case .validatingDirectory: return "Validating model directory"+ case .tokenizer: return "Loading tokenizer"+ case .verifyingWeights: return "Verifying weights"+ case .preparingRunner: return "Preparing runner"+ }+ }+}++public enum AppModelLoadState: Equatable, Sendable {+ case notLoaded+ case loading(AppModelLoadPhase)+ case cancelling+ case unloading+ case ready(modelDirectory: URL, loadSeconds: Double)+ case failed(AppInferenceError)++ public var isLoading: Bool {+ switch self {+ case .loading, .cancelling, .unloading: return true+ default: return false+ }+ }++ public var isReady: Bool {+ if case .ready = self { return true }+ return false+ }++ public var isFailed: Bool {+ if case .failed = self { return true }+ return false+ }+}++public enum AppGenerationPhase: String, Equatable, Sendable {+ case idle+ case prefill+ case decode+}diff --git a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swiftnew file mode 100644index 00000000..0098ac09--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift@@ -0,0 +1,162 @@+import Foundation++public enum AppPresentationSeverity: Equatable, Sendable {+ case neutral+ case active+ case success+ case warning+ case error+}++public struct AppPresentationSnapshot: Equatable, Sendable {+ public var requiresInstallation: Bool+ public var installState: AppModelInstallState+ public var installReadiness: AppModelInstallReadiness+ public var loadState: AppModelLoadState+ public var hasStaleRuntime: Bool+ public var isRunning: Bool+ public var isGenerationCancellationPending: Bool+ public var generationPhase: AppGenerationPhase+ public var livePrefillDone: Int+ public var livePrefillTotal: Int+ public var lastStopReason: AppStopReason?++ public init(requiresInstallation: Bool,+ installState: AppModelInstallState,+ installReadiness: AppModelInstallReadiness,+ loadState: AppModelLoadState,+ hasStaleRuntime: Bool,+ isRunning: Bool,+ isGenerationCancellationPending: Bool,+ generationPhase: AppGenerationPhase,+ livePrefillDone: Int = 0,+ livePrefillTotal: Int = 0,+ lastStopReason: AppStopReason? = nil) {+ self.requiresInstallation = requiresInstallation+ self.installState = installState+ self.installReadiness = installReadiness+ self.loadState = loadState+ self.hasStaleRuntime = hasStaleRuntime+ self.isRunning = isRunning+ self.isGenerationCancellationPending = isGenerationCancellationPending+ self.generationPhase = generationPhase+ self.livePrefillDone = livePrefillDone+ self.livePrefillTotal = livePrefillTotal+ self.lastStopReason = lastStopReason+ }+}++public struct AppPresentationState: Equatable, Sendable {+ public var label: String+ public var detail: String?+ public var severity: AppPresentationSeverity+ public var showsActivity: Bool++ public init(label: String,+ detail: String? = nil,+ severity: AppPresentationSeverity = .neutral,+ showsActivity: Bool = false) {+ self.label = label+ self.detail = detail+ self.severity = severity+ self.showsActivity = showsActivity+ }++ public static func resolve(_ snapshot: AppPresentationSnapshot) -> Self {+ if snapshot.installState.isInstalling {+ if case .cancelling = snapshot.installState {+ return Self(label: "Cancelling installation",+ severity: .active, showsActivity: true)+ }+ return Self(label: installLabel(snapshot.installState),+ severity: .active, showsActivity: true)+ }++ if snapshot.requiresInstallation {+ if case .failed(let message) = snapshot.installState {+ return Self(label: "Installation failed", detail: message,+ severity: .error)+ }+ if case .cancelled = snapshot.installState {+ return Self(label: "Installation cancelled", severity: .warning)+ }+ if case .failed(let message) = snapshot.installReadiness {+ return Self(label: "Storage check failed", detail: message,+ severity: .error)+ }+ if case .insufficientSpace(let requirement) = snapshot.installReadiness {+ return Self(label: "Not enough storage",+ detail: "\(requirement.shortfallBytes) bytes more required",+ severity: .warning)+ }+ if case .checking = snapshot.installReadiness {+ return Self(label: "Checking available space",+ severity: .active, showsActivity: true)+ }+ if case .ready = snapshot.installReadiness {+ return Self(label: "Model required")+ }+ return Self(label: "Model required")+ }++ switch snapshot.loadState {+ case .loading(let phase):+ return Self(label: phase.label, severity: .active, showsActivity: true)+ case .cancelling:+ return Self(label: "Cancelling load", severity: .active, showsActivity: true)+ case .unloading:+ return Self(label: "Unloading model", severity: .active, showsActivity: true)+ case .failed(let error):+ return Self(label: "Model load failed", detail: error.userMessage,+ severity: .error)+ case .notLoaded, .ready:+ break+ }++ if snapshot.isRunning {+ if snapshot.isGenerationCancellationPending {+ return Self(label: "Stopping", severity: .active, showsActivity: true)+ }+ switch snapshot.generationPhase {+ case .prefill:+ let label = snapshot.livePrefillTotal > 0+ ? "Prefill (\(snapshot.livePrefillDone)/\(snapshot.livePrefillTotal))"+ : "Prefill"+ return Self(label: label, severity: .active)+ case .decode:+ return Self(label: "Generating", severity: .active)+ case .idle:+ return Self(label: "Starting generation", severity: .active,+ showsActivity: true)+ }+ }++ if snapshot.hasStaleRuntime {+ return Self(label: "Reload required", severity: .warning)+ }++ if case .ready = snapshot.loadState {+ if let reason = snapshot.lastStopReason {+ return Self(label: "Done · \(reason.rawValue)", severity: .success)+ }+ return Self(label: "Ready", severity: .success)+ }++ return Self(label: "Installed · Not loaded")+ }++ private static func installLabel(_ state: AppModelInstallState) -> String {+ switch state {+ case .checking: return "Checking installation"+ case .downloadingMetadata: return "Downloading metadata"+ case .planning: return "Planning installation"+ case .reservingOutput: return "Reserving storage"+ case .copyingPayload: return "Downloading model"+ case .hashingOutput(let file): return "Verifying \(file)"+ case .finalizing: return "Finalizing installation"+ case .cancelling: return "Cancelling installation"+ case .idle, .cancelled, .installed, .failed:+ return "Model required"+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swiftnew file mode 100644index 00000000..bfdf37b5--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift@@ -0,0 +1,68 @@+import TurboFieldfareAppCore+import SwiftUI++struct RootView: View {+ let model: AppModel++ var body: some View {+ HStack(spacing: 0) {+ primaryContent+ .frame(minWidth: 720, maxWidth: .infinity, maxHeight: .infinity)++ Divider()++ InspectorView(model: model)+ .frame(width: 320)+ .frame(maxHeight: .infinity)+ .background(Color(nsColor: .windowBackgroundColor))+ }+ .containerBackground(for: .window) {+ LinearGradient(+ colors: [+ Color(nsColor: .windowBackgroundColor),+ Color(nsColor: .windowBackgroundColor).mix(with: .indigo, by: 0.04),+ ],+ startPoint: .top,+ endPoint: .bottom)+ }+ .tint(.indigo)+ .animation(.smooth(duration: 0.3), value: model.requiresModelInstallation)+ .animation(.smooth(duration: 0.25), value: model.error)+ .transaction { transaction in+ if model.isRunning {+ transaction.animation = nil+ }+ }+ }++ private var primaryContent: some View {+ Group {+ if model.requiresModelInstallation {+ ModelInstallView(model: model)+ } else {+ conversationView+ }+ }+ .safeAreaInset(edge: .top, spacing: 0) {+ StatusHUDView(model: model)+ }+ }++ private var conversationView: some View {+ OutputPaneView(model: model)+ .safeAreaInset(edge: .bottom, spacing: 0) {+ VStack(spacing: 10) {+ ErrorBanner(model: model)+ if model.promptText.isEmpty {+ PromptExamplesView { preset in+ model.promptText = preset.prefix+ }+ }+ PromptComposerView(model: model)+ }+ .padding(.horizontal, 20)+ .padding(.bottom, 16)+ }+ .animation(.smooth(duration: 0.2), value: model.promptText.isEmpty)+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swiftnew file mode 100644index 00000000..ae19a3aa--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift@@ -0,0 +1,63 @@+import AppKit+import TurboFieldfareAppCore+import SwiftUI++// Run as a regular foreground app even when launched as a bare SwiftPM+// executable (no .app bundle): Dock icon, click-to-activate, full main menu+// with Quit (Cmd+Q).+private final class ForegroundAppDelegate: NSObject, NSApplicationDelegate {+ func applicationDidFinishLaunching(_ notification: Notification) {+ NSApp.setActivationPolicy(.regular)+ if let iconURL = Bundle.module.url(+ forResource: "turbofieldfare-app-icon",+ withExtension: "png"+ ), let icon = NSImage(contentsOf: iconURL) {+ NSApp.applicationIconImage = icon+ NSApp.dockTile.display()+ }+ NSApp.activate()+ }++ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {+ true+ }+}++@main+struct TurboFieldfareMacApp: App {+ @NSApplicationDelegateAdaptor private var appDelegate: ForegroundAppDelegate+ @State private var model: AppModel++ init() {+ _model = State(initialValue: AppModel(client: DecodeServiceInferenceClient()))+ }++ var body: some Scene {+ Window("TurboFieldfare", id: "main") {+ RootView(model: model)+ .frame(minWidth: 1040, minHeight: 560)+ }+ .windowStyle(.hiddenTitleBar)+ .defaultSize(width: 1040, height: 720)+ .windowResizability(.contentMinSize)+ .commands {+ CommandMenu("Generation") {+ Button("Cancel Generation") { model.cancel() }+ .keyboardShortcut(".", modifiers: .command)+ .disabled(!model.canCancel)+ Button("Cancel Model Installation") { model.cancelInstall() }+ .disabled(!model.canCancelInstall)+ }+ CommandMenu("Model") {+ Button("Load Model", action: model.loadModel)+ .disabled(!model.canLoadModel)+ Button("Cancel Load", action: model.cancelLoad)+ .disabled(!model.canCancelLoad)+ Button("Reload Model", action: model.reloadModel)+ .disabled(!model.canReloadModel)+ Button("Unload Model", action: model.unloadModel)+ .disabled(!model.canUnloadModel)+ }+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift b/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swiftnew file mode 100644index 00000000..e42a6389--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Components/ErrorBanner.swift@@ -0,0 +1,40 @@+import TurboFieldfareAppCore+import SwiftUI++struct ErrorBanner: View {+ @Bindable var model: AppModel++ var body: some View {+ if let error = model.error, error != .cancelled {+ HStack(spacing: 8) {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.red)+ Text(error.userMessage)+ .font(.callout)+ .lineLimit(2)+ Spacer(minLength: 8)+ Button {+ model.error = nil+ } label: {+ Label("Dismiss error", systemImage: "xmark")+ .labelStyle(.iconOnly)+ .font(.caption.weight(.semibold))+ .frame(width: 28, height: 28)+ .contentShape(Circle())+ }+ .buttonStyle(.plain)+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 8)+ .background {+ Capsule()+ .fill(Color(nsColor: .controlBackgroundColor))+ .overlay {+ Capsule().stroke(.red.opacity(0.55), lineWidth: 1)+ }+ }+ .help(error.technicalDetail)+ .transition(.move(edge: .bottom).combined(with: .opacity))+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift b/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swiftnew file mode 100644index 00000000..c25c1419--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift@@ -0,0 +1,75 @@+import TurboFieldfareAppCore+import SwiftUI++struct GenerateControl: View {+ let model: AppModel+ private let controlHeight: CGFloat = 34++ var body: some View {+ if model.isRunning {+ runningPill+ } else {+ generateButton+ }+ }++ private var generateButton: some View {+ Button {+ model.run()+ } label: {+ Label("Generate", systemImage: "arrow.up")+ .font(.callout.weight(.semibold))+ .padding(.horizontal, 24)+ .frame(minWidth: 124, minHeight: controlHeight)+ .contentShape(Capsule())+ }+ .buttonStyle(.plain)+ .foregroundStyle(.white)+ .background(.indigo, in: .capsule)+ .overlay {+ Capsule().stroke(.white.opacity(0.16), lineWidth: 0.5)+ }+ .keyboardShortcut(.return, modifiers: .command)+ .disabled(!model.canRun)+ .opacity(model.canRun ? 1 : 0.62)+ }++ private var runningPill: some View {+ HStack(spacing: 10) {+ if model.isCancellationPending {+ Text("Stopping")+ .font(.callout.weight(.medium))+ } else if model.phase == .prefill {+ Text(model.presentation.label)+ .font(.callout.weight(.medium))+ .monospacedDigit()+ } else {+ Text("\(MetricFormat.rate(model.liveTokensPerSecond)) tok/s")+ .font(.callout.weight(.semibold))+ .monospacedDigit()+ }+ Button {+ model.cancel()+ } label: {+ Label("Stop generation", systemImage: "stop.fill")+ .labelStyle(.iconOnly)+ .font(.callout)+ .frame(width: 28, height: 28)+ .contentShape(Circle())+ }+ .buttonStyle(.plain)+ .keyboardShortcut(.cancelAction)+ .disabled(!model.canCancel)+ .help("Stop generation")+ }+ .padding(.leading, 18)+ .padding(.trailing, 4)+ .frame(minWidth: 140, minHeight: controlHeight)+ .contentShape(Capsule())+ .foregroundStyle(.white)+ .background(.indigo, in: .capsule)+ .overlay {+ Capsule().stroke(.white.opacity(0.16), lineWidth: 0.5)+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Components/HUDMetricView.swift b/Sources/TurboFieldfareApp/Mac/Components/HUDMetricView.swiftnew file mode 100644index 00000000..9c9d4fa5--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Components/HUDMetricView.swift@@ -0,0 +1,22 @@+import SwiftUI++struct HUDMetricView: View {+ let value: String+ let label: String+ var animated = true++ var body: some View {+ VStack(spacing: 1) {+ Text(value)+ .font(.system(.callout, design: .rounded).weight(.semibold))+ .monospacedDigit()+ .contentTransition(animated ? .numericText() : .identity)+ .animation(animated ? .snappy(duration: 0.25) : nil, value: value)+ Text(label)+ .font(.caption2)+ .textCase(.uppercase)+ .foregroundStyle(.secondary)+ }+ .frame(minWidth: 56)+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Components/ModelStatusBadge.swift b/Sources/TurboFieldfareApp/Mac/Components/ModelStatusBadge.swiftnew file mode 100644index 00000000..a39d8688--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Components/ModelStatusBadge.swift@@ -0,0 +1,32 @@+import TurboFieldfareAppCore+import SwiftUI++struct ModelStatusBadge: View {+ let model: AppModel++ var body: some View {+ HStack(spacing: 6) {+ statusDot+ Text("Gemma 4 26B")+ .font(.callout.weight(.semibold))+ .lineLimit(1)+ .help(model.installDescriptor.repoID)+ .accessibilityLabel("Model")+ .accessibilityValue(model.installDescriptor.repoID)+ }+ }++ @ViewBuilder+ private var statusDot: some View {+ switch model.presentation.severity {+ case .neutral: dot(.gray)+ case .active, .warning: dot(.orange)+ case .success: dot(.green)+ case .error: dot(.red)+ }+ }++ private func dot(_ color: Color) -> some View {+ Circle().fill(color).frame(width: 8, height: 8).accessibilityHidden(true)+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swiftnew file mode 100644index 00000000..8379dac2--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift@@ -0,0 +1,224 @@+import AppKit+import TurboFieldfareAppCore+import SwiftUI++struct InspectorView: View {+ @Bindable var model: AppModel++ var body: some View {+ Form {+ modelSection+ samplingSection+ expertCacheSection+ runtimeSection+ RunnerDiagnosticsSection(diagnostics: model.diagnostics)+ }+ .formStyle(.grouped)+ .scrollContentBackground(.hidden)+ .background(Color(nsColor: .windowBackgroundColor))+ }++ private var modelSection: some View {+ Section("Model") {+ LabeledContent("Path") {+ HStack(spacing: 6) {+ Text((model.modelPathText as NSString).abbreviatingWithTildeInPath)+ .font(.caption)+ .truncationMode(.middle)+ .lineLimit(1)+ .foregroundStyle(.secondary)+ .help(model.modelPathText)+ Button {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(model.modelPathText, forType: .string)+ } label: {+ Label("Copy model path", systemImage: "doc.on.doc")+ .labelStyle(.iconOnly)+ }+ .buttonStyle(.borderless)+ .help("Copy model path")+ }+ }+ if model.canUnloadModel {+ Button("Unload Model", action: model.unloadModel)+ }+ LabeledContent("State") {+ Text(model.presentation.label)+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ if model.requiresModelInstallation {+ LabeledContent("Download") {+ Text(MetricFormat.storage(model.installDescriptor.approximateDownloadBytes))+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ LabeledContent("Installed size") {+ Text(MetricFormat.storage(model.installDescriptor.installedBytes))+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ if let requirement = model.installRequirement {+ LabeledContent("Available") {+ Text(MetricFormat.storage(requirement.availableBytes))+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ }+ }+ }+ }+ .disabled(model.isRunning || model.isInstallingModel)+ }++ private var samplingSection: some View {+ Section("Sampling") {+ LabeledContent("Max response") {+ Stepper(value: $model.maxNewTokens, in: 1...4096, step: 16) {+ Text("\(model.maxNewTokens)").monospacedDigit()+ }+ .fixedSize()+ }+ LabeledContent("Max context") {+ Stepper(value: $model.maxContextTokens, in: 256...8192, step: 256) {+ Text("\(model.maxContextTokens)").monospacedDigit()+ }+ .fixedSize()+ }+ LabeledContent("Temperature") {+ HStack(spacing: 8) {+ Slider(value: $model.temperature, in: 0...2, step: 0.05)+ Text(model.temperature, format: .number.precision(.fractionLength(2)))+ .monospacedDigit()+ .frame(width: 36, alignment: .trailing)+ }+ }+ Toggle("Top-K", isOn: $model.topKEnabled)+ .toggleStyle(.switch)+ if model.topKEnabled {+ LabeledContent("K value") {+ Stepper(value: $model.topK, in: 1...256, step: 1) {+ Text("\(model.topK)").monospacedDigit()+ }+ .fixedSize()+ }+ }+ Toggle("Top-P", isOn: $model.topPEnabled)+ .toggleStyle(.switch)+ .disabled(!model.topKEnabled)+ if model.topKEnabled && model.topPEnabled {+ LabeledContent("P value") {+ HStack(spacing: 8) {+ Slider(value: $model.topP, in: 0.01...1, step: 0.01)+ Text(model.topP, format: .number.precision(.fractionLength(2)))+ .monospacedDigit()+ .frame(width: 36, alignment: .trailing)+ }+ }+ }+ Toggle("Repetition penalty", isOn: $model.repetitionPenaltyEnabled)+ .toggleStyle(.switch)+ if model.repetitionPenaltyEnabled {+ LabeledContent("Penalty value") {+ HStack(spacing: 8) {+ Slider(value: $model.repetitionPenalty, in: 1...1.8, step: 0.05)+ Text(model.repetitionPenalty, format: .number.precision(.fractionLength(2)))+ .monospacedDigit()+ .frame(width: 36, alignment: .trailing)+ }+ }+ }+ Text("Defaults: 1,024 tokens, temperature 0.10, Top-K 64, Top-P 0.95. Repetition penalty is off.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .disabled(model.isRunning || model.loadState.isLoading)+ }++ private var expertCacheSection: some View {+ Section("Expert cache") {+ LabeledContent("Slots") {+ Picker("Slots", selection: $model.runtimeOptions.expertCacheSlots) {+ ForEach(AppRuntimeOptions.allowedSlotCounts, id: \.self) { slots in+ Text(AppRuntimeOptions.slotsLabel(for: slots)).tag(slots)+ }+ }+ .pickerStyle(.menu)+ .labelsHidden()+ .fixedSize()+ }+ VStack(alignment: .leading, spacing: 8) {+ Text("Policy")+ Picker("Policy", selection: $model.runtimeOptions.expertCachePolicy) {+ ForEach(AppExpertCachePolicy.allCases) { policy in+ Text(policy.label).tag(policy)+ }+ }+ .pickerStyle(.segmented)+ .labelsHidden()+ }+ if model.runtimeOptions.expertCacheSlots > 16 {+ Text("Slot counts above 16 trade extra RAM for fewer expert reads.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ .disabled(model.isRunning || model.loadState.isLoading)+ }++ private var runtimeSection: some View {+ Section("Runtime") {+ Toggle("Prefill", isOn: $model.runtimeOptions.prefillEnabled)+ LabeledContent("Prefill chunk") {+ Picker("Prefill chunk", selection: $model.runtimeOptions.prefillChunkTokens) {+ ForEach(AppRuntimeOptions.allowedPrefillChunkTokens, id: \.self) { tokens in+ Text("\(tokens) tokens").tag(tokens)+ }+ }+ .pickerStyle(.menu)+ .labelsHidden()+ .fixedSize()+ }+ .disabled(!model.runtimeOptions.prefillEnabled)+ Toggle("TurboQuant K4/V4 (Experimental)",+ isOn: $model.runtimeOptions.turboQuantKVEnabled)+ Text("This is an experimental feature and may reduce output quality.")+ .font(.caption)+ .foregroundStyle(.secondary)+ VStack(alignment: .leading, spacing: 8) {+ Text("RDADVISE")+ Picker("RDADVISE", selection: $model.runtimeOptions.rdadvisePolicy) {+ ForEach(AppRDAdvicePolicy.allCases) { mode in+ Text(mode.label).tag(mode)+ }+ }+ .pickerStyle(.segmented)+ .labelsHidden()+ }+ Text("RDADVISE is experimental. It may speed up short decodes but slow down long decodes.")+ .font(.caption)+ .foregroundStyle(.secondary)+ LabeledContent("Model verification") {+ Picker("Model verification", selection: $model.runtimeOptions.modelVerification) {+ ForEach(AppModelVerification.allCases) { choice in+ Text(choice.label).tag(choice)+ }+ }+ .pickerStyle(.menu)+ .labelsHidden()+ .fixedSize()+ }+ if model.runtimeOptions.modelVerification == .trustedInstall {+ Text("Trust verified install checks the signed-off receipt and file sizes instead of hashing all model files again.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ if model.hasStaleLoadedRuntime {+ Text("Reload required")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ .disabled(model.isRunning || model.loadState.isLoading)+ }++}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/MetricFormat.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/MetricFormat.swiftnew file mode 100644index 00000000..94b028f9--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/MetricFormat.swift@@ -0,0 +1,56 @@+import Foundation++@MainActor+enum MetricFormat {+ private static let memoryFormatter: ByteCountFormatter = {+ let formatter = ByteCountFormatter()+ formatter.countStyle = .memory+ return formatter+ }()++ private static let storageFormatter: ByteCountFormatter = {+ let formatter = ByteCountFormatter()+ formatter.countStyle = .file+ formatter.allowedUnits = [.useMB, .useGB, .useTB]+ formatter.includesUnit = true+ formatter.isAdaptive = true+ return formatter+ }()++ static func seconds(_ value: Double?) -> String {+ guard let value else { return "\u{2014}" }+ if value < 1 { return String(format: "%.0f ms", value * 1000) }+ return String(format: "%.2f s", value)+ }++ static func milliseconds(_ value: Double?) -> String {+ guard let value else { return "\u{2014}" }+ return "\(value.formatted(.number.precision(.fractionLength(1)))) ms"+ }++ static func rate(_ value: Double) -> String {+ String(format: "%.1f", value)+ }++ static func percent(_ value: Double) -> String {+ String(format: "%.1f%%", value)+ }++ static func perToken(_ value: Double) -> String {+ "\(value.formatted(.number.precision(.fractionLength(1))))/tok"+ }++ static func megabytesPerToken(_ value: Double) -> String {+ "\(value.formatted(.number.precision(.fractionLength(1)))) MB/tok"+ }++ static func memory(_ bytes: UInt64?) -> String {+ guard let bytes else { return "\u{2014}" }+ return memoryFormatter.string(fromByteCount: Int64(bytes))+ }++ static func storage(_ bytes: UInt64) -> String {+ storageFormatter.string(fromByteCount: Int64(clamping: bytes))+ }++}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swiftnew file mode 100644index 00000000..a0404926--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift@@ -0,0 +1,132 @@+import TurboFieldfareAppCore+import SwiftUI++struct RunnerDiagnosticsSection: View {+ let diagnostics: AppDiagnostics?++ var body: some View {+ Section("Last run") {+ if let diagnostics {+ groupLabel("Result")+ DiagnosticRow("Settings", diagnostics.runtimeOptions.resultSummary, multiline: true)+ DiagnosticRow("Prompt tokens", diagnostics.promptTokenCount.map(String.init) ?? "unknown")+ DiagnosticRow("Output tokens", "\(diagnostics.generatedTokens)")+ DiagnosticRow("Stop", diagnostics.stopReason.rawValue)++ groupLabel("Performance")+ DiagnosticRow("Prompt prefill", MetricFormat.seconds(diagnostics.prefillSeconds))+ DiagnosticRow("Request TTFT", MetricFormat.seconds(diagnostics.requestStartTimeToFirstTokenSeconds))+ DiagnosticRow("Decode rate", "\(MetricFormat.rate(diagnostics.tokensPerSecond)) tok/s")+ DiagnosticRow("Peak memory", MetricFormat.memory(diagnostics.peakMemoryBytes))+ DiagnosticRow("I/O / token",+ MetricFormat.milliseconds(diagnostics.runner?.ioMillisecondsPerToken))++ if hasIssues(diagnostics) {+ groupLabel("Issues")+ issueRows(diagnostics)+ }++ if let runner = diagnostics.runner {+ DisclosureGroup("Advanced") {+ AdvancedRunnerDiagnosticsView(diagnostics: diagnostics, runner: runner)+ }+ }+ } else {+ Text("No runs yet")+ .font(.caption)+ .foregroundStyle(.tertiary)+ }+ }+ }++ @ViewBuilder+ private func issueRows(_ diagnostics: AppDiagnostics) -> some View {+ if let prefill = diagnostics.prefill {+ if prefill.requestedMode.rawValue != prefill.executedMode.rawValue {+ DiagnosticRow("Prefill mode",+ "\(prefill.requestedMode.rawValue) -> \(prefill.executedMode.rawValue)")+ }+ if prefill.chunkCompleteness != .complete {+ DiagnosticRow("Prefill status", prefill.chunkCompleteness.rawValue)+ }+ if let reason = prefill.unsupportedReason, !reason.isEmpty {+ DiagnosticRow("Unsupported reason", reason, multiline: true)+ }+ }+ if let failures = diagnostics.runner?.rdadviseFailures, failures > 0 {+ DiagnosticRow("RDADVISE failures", "\(failures)")+ }+ }++ private func hasIssues(_ diagnostics: AppDiagnostics) -> Bool {+ let prefillHasIssue = diagnostics.prefill.map {+ $0.requestedMode.rawValue != $0.executedMode.rawValue+ || $0.chunkCompleteness != .complete+ || !($0.unsupportedReason?.isEmpty ?? true)+ } ?? false+ return prefillHasIssue || (diagnostics.runner?.rdadviseFailures ?? 0) > 0+ }++ private func groupLabel(_ title: String) -> some View {+ Text(title)+ .font(.caption)+ .textCase(.uppercase)+ .foregroundStyle(.tertiary)+ .accessibilityHeading(.h3)+ }+}++private struct AdvancedRunnerDiagnosticsView: View {+ let diagnostics: AppDiagnostics+ let runner: AppRunnerDiagnostics++ var body: some View {+ VStack(spacing: 8) {+ DiagnosticRow("Decode duration", MetricFormat.seconds(diagnostics.decodeSeconds))+ DiagnosticRow("cb1 / token", MetricFormat.milliseconds(runner.cb1MillisecondsPerToken))+ DiagnosticRow("cb2 / token", MetricFormat.milliseconds(runner.cb2MillisecondsPerToken))+ DiagnosticRow("Head / token", MetricFormat.milliseconds(runner.headMillisecondsPerToken))+ if hasRDAdviceActivity {+ DiagnosticRow("RDADVISE / token",+ MetricFormat.milliseconds(runner.rdadviseMillisecondsPerToken))+ DiagnosticRow("RDADVISE calls", MetricFormat.perToken(runner.rdadviseCallsPerToken))+ DiagnosticRow("RDADVISE data",+ MetricFormat.megabytesPerToken(runner.rdadviseMegabytesPerToken))+ DiagnosticRow("RDADVISE skipped", MetricFormat.perToken(runner.rdadviseSkippedPerToken))+ }+ }+ .frame(maxWidth: .infinity)+ }++ private var hasRDAdviceActivity: Bool {+ runner.rdadviseMillisecondsPerToken > 0+ || runner.rdadviseCallsPerToken > 0+ || runner.rdadviseMegabytesPerToken > 0+ || runner.rdadviseSkippedPerToken > 0+ }+}++private struct DiagnosticRow: View {+ let label: String+ let value: String+ let multiline: Bool++ init(_ label: String, _ value: String, multiline: Bool = false) {+ self.label = label+ self.value = value+ self.multiline = multiline+ }++ var body: some View {+ LabeledContent(label) {+ Text(value)+ .font(.caption)+ .monospacedDigit()+ .foregroundStyle(.secondary)+ .textSelection(.enabled)+ .multilineTextAlignment(.trailing)+ .lineLimit(multiline ? nil : 2)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swiftnew file mode 100644index 00000000..edaecc27--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift@@ -0,0 +1,112 @@+import TurboFieldfareAppCore+import SwiftUI++struct StatusHUDView: View {+ let model: AppModel++ var body: some View {+ strip+ .padding(.top, 10)+ .padding(.leading, 84)+ .padding(.trailing, 20)+ }++ private var strip: some View {+ HStack(spacing: 12) {+ ModelStatusBadge(model: model)+ Divider().frame(height: 16)+ PhaseLabel(model: model)+ Spacer(minLength: 12)+ if showsMetrics {+ HUDMetricView(value: rateText, label: "tok/s", animated: !model.isRunning)+ HUDMetricView(value: tokensText, label: "tokens", animated: !model.isRunning)+ HUDMetricView(value: memoryText, label: "memory", animated: !model.isRunning)+ }+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ .background {+ Capsule()+ .fill(Color(nsColor: .controlBackgroundColor))+ .overlay {+ Capsule().stroke(.separator.opacity(0.5), lineWidth: 0.5)+ }+ }+ .gesture(WindowDragGesture())+ }++ private var rateText: String {+ if model.phase == .decode { return MetricFormat.rate(model.liveTokensPerSecond) }+ if let d = model.diagnostics { return MetricFormat.rate(d.tokensPerSecond) }+ return "\u{2014}"+ }++ private var tokensText: String {+ if model.isRunning { return "\(model.liveTokenCount)" }+ if let d = model.diagnostics { return "\(d.generatedTokens)" }+ return "\u{2014}"+ }++ private var memoryText: String {+ MetricFormat.memory(model.currentProcessMemoryBytes)+ }++ private var showsMetrics: Bool {+ model.loadState.isReady || model.isRunning || model.diagnostics != nil+ }+}++private struct PhaseLabel: View {+ let model: AppModel++ var body: some View {+ HStack(spacing: 6) {+ switch content {+ case .loading(let label):+ ProgressView().controlSize(.mini)+ Text(label)+ case .pulse(let label):+ PulsingDot()+ Text(label).monospacedDigit()+ case .steady(let label):+ Circle().fill(.indigo).frame(width: 7, height: 7)+ Text(label)+ case .quiet(let label):+ Text(label).foregroundStyle(.secondary)+ }+ }+ .font(.caption.weight(.medium))+ .lineLimit(1)+ .accessibilityElement(children: .ignore)+ .accessibilityLabel("Model status")+ .accessibilityValue(model.presentation.label)+ }++ private enum Content {+ case loading(String)+ case pulse(String)+ case steady(String)+ case quiet(String)+ }++ private var content: Content {+ let presentation = model.presentation+ if presentation.showsActivity { return .loading(presentation.label) }+ if model.isRunning && model.phase == .prefill { return .pulse(presentation.label) }+ if model.isRunning && model.phase == .decode { return .steady(presentation.label) }+ return .quiet(presentation.label)+ }+}++private struct PulsingDot: View {+ var body: some View {+ Circle()+ .fill(.indigo)+ .frame(width: 7, height: 7)+ .phaseAnimator([0.4, 1.0]) { dot, opacity in+ dot.opacity(opacity)+ } animation: { _ in+ .easeInOut(duration: 0.7)+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swiftnew file mode 100644index 00000000..9a8aeffe--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift@@ -0,0 +1,276 @@+import AppKit+import TurboFieldfareAppCore+import SwiftUI++struct OutputPaneView: View {+ let model: AppModel++ var body: some View {+ Group {+ if model.hasOutputTranscript {+ transcript+ } else {+ placeholder+ }+ }+ .contextMenu {+ Button("Copy All") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(model.outputPlainText, forType: .string)+ }+ .disabled(!model.hasOutputTranscript)+ Button("Clear") { model.clearOutput() }+ .disabled(model.isRunning || !model.hasOutputTranscript)+ }+ }++ @ViewBuilder+ private var placeholder: some View {+ ScrollView {+ Group {+ if model.phase == .prefill {+ prefillPlaceholder+ } else {+ emptyPlaceholder+ }+ }+ .padding(.horizontal, 24)+ .padding(.vertical, 20)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .defaultScrollAnchor(.bottom, for: .sizeChanges)+ }++ private var transcript: some View {+ VStack(alignment: .leading, spacing: 16) {+ IncrementalTranscriptView(+ prompt: model.outputPromptText,+ output: model.outputText,+ mailbox: model.generationTranscriptMailbox)+ .frame(maxWidth: .infinity, maxHeight: .infinity)++ if model.phase == .prefill {+ prefillStatus+ }+ }+ .padding(.horizontal, 24)+ .padding(.vertical, 20)+ }++ private var prefillPlaceholder: some View {+ prefillStatus+ .frame(maxWidth: .infinity, minHeight: 240)+ }++ private var prefillStatus: some View {+ VStack(spacing: 10) {+ Text("Processing prompt")+ .font(.callout)+ .foregroundStyle(.secondary)+ if model.livePrefillTotal > 0 {+ Text("\(model.livePrefillDone) of \(model.livePrefillTotal) tokens")+ .font(.caption)+ .monospacedDigit()+ .foregroundStyle(.tertiary)+ }+ }+ }++ private var emptyPlaceholder: some View {+ VStack(spacing: 8) {+ Image(systemName: placeholderSymbol)+ .font(.title2)+ .foregroundStyle(.quaternary)+ if !needsModelLoad {+ Text("Give TurboFieldfare a beginning, and it will continue the text from there.")+ .font(.callout)+ .foregroundStyle(.secondary)+ }+ Text(placeholderHint)+ .font(.callout)+ .foregroundStyle(.tertiary)+ if let detail = model.presentation.detail {+ Text(detail)+ .font(.caption)+ .foregroundStyle(model.presentation.severity == .error ? .red : .secondary)+ .multilineTextAlignment(.center)+ }+ if model.canLoadModel {+ Button(model.loadState.isFailed ? "Retry Load" : "Load Model",+ action: model.loadModel)+ .buttonStyle(.borderedProminent)+ .controlSize(.large)+ } else if model.canReloadModel {+ Button("Reload Model", action: model.reloadModel)+ .buttonStyle(.borderedProminent)+ } else if model.canCancelLoad {+ Button("Cancel Load", action: model.cancelLoad)+ }+ }+ .frame(maxWidth: .infinity, minHeight: 240)+ }++ private var needsModelLoad: Bool {+ !model.loadState.isReady+ }++ private var placeholderSymbol: String {+ needsModelLoad ? "cube.transparent" : "text.cursor"+ }++ private var placeholderHint: String {+ if model.loadState.isFailed { return "The model could not be loaded" }+ if model.hasStaleLoadedRuntime { return "Reload the model to use changed settings" }+ return needsModelLoad+ ? "Load the model to begin"+ : "Enter a prompt and press \u{2318}\u{21A9} to generate"+ }+}++private struct IncrementalTranscriptView: NSViewRepresentable {+ var prompt: String+ var output: String+ var mailbox: GenerationTranscriptMailbox?++ @MainActor+ final class Coordinator: NSObject {+ var prompt = ""+ var output = ""+ weak var scrollView: NSScrollView?+ weak var textView: NSTextView?+ var mailbox: GenerationTranscriptMailbox?+ var timer: Timer?++ func attach(scrollView: NSScrollView, textView: NSTextView) {+ self.scrollView = scrollView+ self.textView = textView+ guard timer == nil else { return }+ let timer = Timer(timeInterval: 0.1, target: self,+ selector: #selector(drainMailbox),+ userInfo: nil, repeats: true)+ timer.tolerance = 0.02+ RunLoop.main.add(timer, forMode: .common)+ self.timer = timer+ }++ func synchronize(prompt: String, output: String,+ mailbox: GenerationTranscriptMailbox?) {+ self.mailbox = mailbox+ let completion = mailbox?.drain().completeText ?? output+ apply(prompt: prompt, output: completion)+ }++ @objc private func drainMailbox() {+ guard let mailbox else { return }+ let snapshot = mailbox.drain()+ guard !snapshot.pendingText.isEmpty || snapshot.completeText != output else { return }+ apply(prompt: prompt, output: snapshot.completeText)+ }++ func invalidate() {+ timer?.invalidate()+ timer = nil+ mailbox = nil+ }++ private func apply(prompt: String, output: String) {+ guard let scrollView, let textView, let storage = textView.textStorage else {+ return+ }+ let wasAtBottom = isAtBottom(scrollView)+ let selection = textView.selectedRanges++ storage.beginEditing()+ if prompt != self.prompt || !output.hasPrefix(self.output) {+ let replacement = NSMutableAttributedString(+ string: prompt,+ attributes: promptAttributes())+ replacement.append(NSAttributedString(+ string: output,+ attributes: outputAttributes()))+ storage.setAttributedString(replacement)+ } else if output.count > self.output.count {+ let delta = String(output.dropFirst(self.output.count))+ storage.append(NSAttributedString(+ string: delta,+ attributes: outputAttributes()))+ }+ storage.endEditing()++ self.prompt = prompt+ self.output = output+ let restoredSelection = selection.map { value in+ let range = value.rangeValue+ let location = min(range.location, storage.length)+ let length = min(range.length, storage.length - location)+ return NSValue(range: NSRange(location: location, length: length))+ }+ if restoredSelection.isEmpty {+ textView.setSelectedRange(NSRange(location: storage.length, length: 0))+ } else {+ textView.selectedRanges = restoredSelection+ }+ if wasAtBottom { textView.scrollToEndOfDocument(nil) }+ }++ private func isAtBottom(_ scrollView: NSScrollView) -> Bool {+ guard let document = scrollView.documentView else { return true }+ let visible = scrollView.contentView.bounds+ return visible.maxY >= document.bounds.maxY - 24+ }++ private func outputAttributes() -> [NSAttributedString.Key: Any] {+ [.font: NSFont.monospacedSystemFont(+ ofSize: NSFont.systemFontSize, weight: .regular),+ .foregroundColor: NSColor.labelColor,+ .paragraphStyle: paragraphStyle()]+ }++ private func promptAttributes() -> [NSAttributedString.Key: Any] {+ [.font: NSFont.monospacedSystemFont(+ ofSize: NSFont.systemFontSize, weight: .bold),+ .foregroundColor: NSColor.labelColor,+ .paragraphStyle: paragraphStyle()]+ }++ private func paragraphStyle() -> NSParagraphStyle {+ let style = NSMutableParagraphStyle()+ style.lineSpacing = 3+ return style+ }+ }++ func makeCoordinator() -> Coordinator { Coordinator() }++ func makeNSView(context: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.hasVerticalScroller = true+ scrollView.autohidesScrollers = true+ scrollView.drawsBackground = false++ let textView = NSTextView()+ textView.isEditable = false+ textView.isSelectable = true+ textView.drawsBackground = false+ textView.textContainerInset = NSSize(width: 0, height: 0)+ textView.isVerticallyResizable = true+ textView.isHorizontallyResizable = false+ textView.autoresizingMask = [.width]+ textView.textContainer?.widthTracksTextView = true+ textView.textContainer?.lineFragmentPadding = 0+ scrollView.documentView = textView+ return scrollView+ }++ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ guard let textView = scrollView.documentView as? NSTextView else { return }+ context.coordinator.attach(scrollView: scrollView, textView: textView)+ context.coordinator.synchronize(+ prompt: prompt, output: output, mailbox: mailbox)+ }++ static func dismantleNSView(_ nsView: NSScrollView,+ coordinator: Coordinator) {+ coordinator.invalidate()+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swiftnew file mode 100644index 00000000..3e51b3cf--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift@@ -0,0 +1,84 @@+import TurboFieldfareAppCore+import SwiftUI++struct PromptComposerView: View {+ @Bindable var model: AppModel+ @FocusState private var promptFocused: Bool++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ editor+ footer+ }+ .padding(14)+ .background {+ RoundedRectangle(cornerRadius: 22)+ .fill(Color(nsColor: .controlBackgroundColor))+ .overlay {+ RoundedRectangle(cornerRadius: 22)+ .stroke(.separator.opacity(0.5), lineWidth: 0.5)+ }+ }+ }++ private var editor: some View {+ TextEditor(text: $model.promptText)+ .accessibilityLabel("Prompt")+ .font(.body)+ .scrollContentBackground(.hidden)+ .focused($promptFocused)+ .frame(height: editorHeight)+ .overlay(alignment: .topLeading) {+ if model.promptText.isEmpty {+ // Matches the NSTextView text origin: 5pt line fragment+ // padding, no vertical inset.+ Text("Prompt")+ .font(.body)+ .foregroundStyle(.tertiary)+ .padding(.leading, 5)+ .allowsHitTesting(false)+ }+ }+ }++ private var editorHeight: CGFloat {+ model.promptText.isEmpty ? 38 : 76+ }++ private var footer: some View {+ HStack(spacing: 10) {+ Spacer()+ clearAction+ GenerateControl(model: model)+ }+ }++ @ViewBuilder+ private var clearAction: some View {+ if !model.isRunning && model.hasOutputTranscript {+ Button {+ model.clearOutput()+ } label: {+ Label("Clear output", systemImage: "trash")+ .labelStyle(.iconOnly)+ .frame(width: 28, height: 28)+ .contentShape(Circle())+ }+ .buttonStyle(.borderless)+ .help("Clear output")+ } else if !model.isRunning && !model.promptText.isEmpty {+ Button {+ model.promptText = ""+ promptFocused = true+ } label: {+ Label("Clear prompt", systemImage: "xmark.circle.fill")+ .labelStyle(.iconOnly)+ .symbolRenderingMode(.hierarchical)+ .frame(width: 28, height: 28)+ .contentShape(Circle())+ }+ .buttonStyle(.borderless)+ .help("Clear prompt")+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swiftnew file mode 100644index 00000000..d5d637ba--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift@@ -0,0 +1,93 @@+import TurboFieldfareAppCore+import SwiftUI++struct PromptExamplesView: View {+ let select: (AppPromptPreset) -> Void++ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(alignment: .firstTextBaseline) {+ VStack(alignment: .leading, spacing: 2) {+ Text("Continue an example")+ .font(.headline)+ Text("Gemma continues the text you select.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ Spacer()+ moreExamples+ }++ LazyVGrid(columns: columns, alignment: .leading, spacing: 10) {+ primaryCards+ }+ }+ .padding(14)+ .background {+ RoundedRectangle(cornerRadius: 18)+ .fill(Color(nsColor: .controlBackgroundColor))+ .overlay {+ RoundedRectangle(cornerRadius: 18)+ .stroke(.separator.opacity(0.5), lineWidth: 0.5)+ }+ }+ .transition(.opacity.combined(with: .move(edge: .bottom)))+ .accessibilityElement(children: .contain)+ }++ @ViewBuilder+ private var primaryCards: some View {+ ForEach(AppPromptPreset.primary) { preset in+ Button {+ select(preset)+ } label: {+ VStack(alignment: .leading, spacing: 6) {+ Text(preset.title)+ .font(.caption.weight(.semibold))+ .foregroundStyle(.primary)+ .lineLimit(2)+ Text(preset.prefix)+ .font(.caption2)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.leading)+ .lineLimit(3)+ Spacer(minLength: 0)+ }+ .frame(maxWidth: .infinity, minHeight: 96, alignment: .topLeading)+ .padding(10)+ .contentShape(.rect)+ }+ .buttonStyle(.plain)+ .background(.quaternary.opacity(0.25), in: .rect(cornerRadius: 12))+ .overlay {+ RoundedRectangle(cornerRadius: 12)+ .stroke(.separator.opacity(0.35), lineWidth: 0.5)+ }+ .accessibilityLabel(preset.title)+ .accessibilityValue(preset.prefix)+ .accessibilityHint("Copies this beginning into the prompt editor")+ }+ }++ private var columns: [GridItem] {+ Array(repeating: GridItem(.flexible(minimum: 0), spacing: 10, alignment: .top), count: 3)+ }++ private var moreExamples: some View {+ Menu("More examples") {+ ForEach(AppPromptPreset.secondary) { preset in+ Button {+ select(preset)+ } label: {+ VStack(alignment: .leading) {+ Text(preset.title)+ Text(preset.prefix)+ }+ }+ }+ }+ .menuStyle(.borderlessButton)+ .fixedSize()+ .accessibilityHint("Shows additional text beginnings")+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swiftnew file mode 100644index 00000000..73b6c3bd--- /dev/null+++ b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift@@ -0,0 +1,173 @@+import TurboFieldfareAppCore+import SwiftUI++struct ModelInstallView: View {+ let model: AppModel++ var body: some View {+ ScrollView {+ VStack(spacing: 22) {+ identity+ storageCard+ progressArea+ actions+ }+ .frame(maxWidth: 560)+ .padding(.horizontal, 28)+ .padding(.vertical, 48)+ .frame(maxWidth: .infinity)+ }+ }++ private var identity: some View {+ VStack(spacing: 10) {+ Image(systemName: "externaldrive.badge.plus")+ .font(.system(.largeTitle, design: .rounded))+ .foregroundStyle(.indigo)+ .accessibilityHidden(true)+ Text("Model required")+ .font(.title.bold())+ .accessibilityHeading(.h1)+ Text("TurboFieldfare needs \(model.installDescriptor.displayName) before it can generate text.")+ .font(.body)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ }+ }++ private var storageCard: some View {+ VStack(spacing: 12) {+ if let requirement = model.installRequirement {+ StorageRow(label: "Space required",+ value: MetricFormat.storage(requirement.requiredBytes))+ StorageRow(label: "Available on this Mac",+ value: MetricFormat.storage(requirement.availableBytes))+ capacityStatus(requirement)+ } else if case .failed(let message) = model.installReadiness {+ HStack(spacing: 8) {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.red)+ Text(message).foregroundStyle(.secondary)+ Spacer()+ }+ } else {+ HStack(spacing: 8) {+ ProgressView().controlSize(.small)+ Text(readinessLabel)+ .foregroundStyle(.secondary)+ Spacer()+ }+ }+ Text(model.modelPathText)+ .font(.caption.monospaced())+ .foregroundStyle(.tertiary)+ .lineLimit(2)+ .truncationMode(.middle)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .padding(18)+ .background {+ RoundedRectangle(cornerRadius: 20)+ .fill(Color(nsColor: .controlBackgroundColor))+ .overlay {+ RoundedRectangle(cornerRadius: 20)+ .stroke(.separator.opacity(0.5), lineWidth: 0.5)+ }+ }+ }++ @ViewBuilder+ private func capacityStatus(_ requirement: AppModelInstallRequirement) -> some View {+ if requirement.canInstall {+ Label("Enough space to install", systemImage: "checkmark.circle.fill")+ .foregroundStyle(.green)+ .frame(maxWidth: .infinity, alignment: .leading)+ } else {+ Label("\(MetricFormat.storage(requirement.shortfallBytes)) more is required",+ systemImage: "exclamationmark.triangle.fill")+ .foregroundStyle(.orange)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }++ @ViewBuilder+ private var progressArea: some View {+ if model.isInstallingModel {+ VStack(spacing: 10) {+ if let fraction = model.installProgressFraction,+ let downloaded = model.installDownloadedBytes,+ let total = model.installTotalBytes {+ ProgressView(value: fraction)+ .accessibilityLabel("Model download")+ .accessibilityValue(Text(MetricFormat.percent(fraction * 100)))+ HStack {+ Text("Downloaded \(MetricFormat.storage(downloaded)) of \(MetricFormat.storage(total))")+ Spacer()+ Text(MetricFormat.percent(fraction * 100))+ }+ .font(.caption.monospacedDigit())+ .foregroundStyle(.secondary)+ } else {+ Text(model.presentation.label)+ .font(.callout)+ .foregroundStyle(.secondary)+ }+ }+ .frame(maxWidth: .infinity)+ } else if case .cancelled = model.installState {+ Label("Installation cancelled", systemImage: "xmark.circle")+ .foregroundStyle(.secondary)+ } else if case .failed(let message) = model.installState {+ Label(message, systemImage: "exclamationmark.triangle.fill")+ .font(.callout)+ .foregroundStyle(.red)+ .multilineTextAlignment(.center)+ }+ }++ private var actions: some View {+ HStack(spacing: 12) {+ if model.isInstallingModel {+ Button("Cancel", action: model.cancelInstall)+ .buttonStyle(.bordered)+ .keyboardShortcut(.cancelAction)+ .disabled(!model.canCancelInstall)+ } else {+ Button("Check Again", action: model.refreshInstallReadiness)+ .buttonStyle(.bordered)+ .disabled(model.isInstallingModel)++ Button("Install", action: model.installModel)+ .buttonStyle(.borderedProminent)+ .disabled(!model.canInstallModel)+ }+ }+ .controlSize(.large)+ }++ private var readinessLabel: String {+ switch model.installReadiness {+ case .checking:+ return "Checking available space"+ case .failed(let message):+ return message+ case .ready, .insufficientSpace:+ return "Checking available space"+ }+ }+}++private struct StorageRow: View {+ let label: String+ let value: String++ var body: some View {+ HStack(alignment: .firstTextBaseline) {+ Text(label).foregroundStyle(.secondary)+ Spacer(minLength: 16)+ Text(value)+ .monospacedDigit()+ .multilineTextAlignment(.trailing)+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Mac/Resources/turbofieldfare-app-icon.png b/Sources/TurboFieldfareApp/Mac/Resources/turbofieldfare-app-icon.pngnew file mode 100644index 00000000..1857f268Binary files /dev/null and b/Sources/TurboFieldfareApp/Mac/Resources/turbofieldfare-app-icon.png differdiff --git a/Sources/TurboFieldfareCLI/Args.swift b/Sources/TurboFieldfareCLI/Args.swiftnew file mode 100644index 00000000..af0bc657--- /dev/null+++ b/Sources/TurboFieldfareCLI/Args.swift@@ -0,0 +1,183 @@+public struct Args: Equatable, Sendable {+ public var model: String+ public var prompt: String+ public var maxNew: Int+ public var maxContext: Int+ public var temperature: Float+ public var topK: Int?+ public var topP: Float?+ public var repetitionPenalty: Float+ public var seed: UInt64?+ public var stops: [String]+ public var quiet: Bool++ public init(model: String,+ prompt: String,+ maxNew: Int = 1_024,+ maxContext: Int = 4096,+ temperature: Float = 0.1,+ topK: Int? = 64,+ topP: Float? = 0.95,+ repetitionPenalty: Float = 1.0,+ seed: UInt64? = nil,+ stops: [String] = [],+ quiet: Bool = false) {+ self.model = model+ self.prompt = prompt+ self.maxNew = maxNew+ self.maxContext = maxContext+ self.temperature = temperature+ self.topK = topK+ self.topP = topP+ self.repetitionPenalty = repetitionPenalty+ self.seed = seed+ self.stops = stops+ self.quiet = quiet+ }+}++public enum ArgsError: Error, Equatable, CustomStringConvertible {+ case helpRequested+ case unknownFlag(String)+ case missingValue(flag: String)+ case invalidValue(flag: String, value: String)+ case requiredMissing(String)++ public var description: String {+ switch self {+ case .helpRequested: return "help requested"+ case .unknownFlag(let flag): return "unknown flag: \(flag)"+ case .missingValue(let flag): return "missing value for \(flag)"+ case .invalidValue(let flag, let value): return "invalid value for \(flag): \(value)"+ case .requiredMissing(let flag): return "required flag missing: \(flag)"+ }+ }+}++extension Args {+ public static let usage = """+ TurboFieldfareCLI — text completion with Gemma 4 26B-A4B++ usage: TurboFieldfareCLI --model <dir> --prompt <string> [options]++ required:+ --model <dir> Path to a .gturbo model directory.+ --prompt <string> Raw-completion prompt.++ options:+ --max-new <int> Generated-token limit (default 1024).+ --max-context <int> Context limit in tokens (default 4096).+ --temperature <float> Sampling temperature (default 0.1; 0 = greedy).+ --top-k <int> Top-k truncation, 1...256 (default 64; 0 = off).+ --top-p <float> Nucleus truncation (default 0.95).+ --repetition-penalty <f> Repetition penalty (default 1.0).+ --seed <uint64> Deterministic sampling seed (default off).+ --stop <string> Stop substring (repeatable).+ --quiet Suppress the timing footer.+ --help Show this message.+ """++ public static func parse(_ argv: [String]) throws -> Args {+ var model: String?+ var prompt: String?+ var maxNew = 1_024+ var maxContext = 4096+ var temperature: Float = 0.1+ var topK: Int? = 64+ var topP: Float? = 0.95+ var repetitionPenalty: Float = 1.0+ var seed: UInt64?+ var stops: [String] = []+ var quiet = false++ var index = 0+ while index < argv.count {+ let flag = argv[index]+ switch flag {+ case "--help":+ throw ArgsError.helpRequested+ case "--quiet":+ quiet = true+ index += 1+ case "--model":+ model = try takeValue(argv, &index, flag: flag)+ case "--prompt":+ prompt = try takeValue(argv, &index, flag: flag)+ case "--max-new":+ let value = try takeValue(argv, &index, flag: flag)+ guard let parsed = Int(value), parsed > 0 else {+ throw ArgsError.invalidValue(flag: flag, value: value)+ }+ maxNew = parsed+ case "--max-context":+ let value = try takeValue(argv, &index, flag: flag)+ guard let parsed = Int(value), parsed > 0 else {+ throw ArgsError.invalidValue(flag: flag, value: value)+ }+ maxContext = parsed+ case "--temperature":+ let value = try takeValue(argv, &index, flag: flag)+ guard let parsed = Float(value), parsed >= 0 else {+ throw ArgsError.invalidValue(flag: flag, value: value)+ }+ temperature = parsed+ case "--top-k":+ let value = try takeValue(argv, &index, flag: flag)+ guard let parsed = Int(value), (0...256).contains(parsed) else {+ throw ArgsError.invalidValue(flag: flag, value: value)+ }+ topK = parsed == 0 ? nil : parsed+ case "--top-p":+ let value = try takeValue(argv, &index, flag: flag)+ guard let parsed = Float(value), parsed > 0, parsed <= 1 else {+ throw ArgsError.invalidValue(flag: flag, value: value)+ }+ topP = parsed+ case "--repetition-penalty":+ let value = try takeValue(argv, &index, flag: flag)+ guard let parsed = Float(value), parsed > 0 else {+ throw ArgsError.invalidValue(flag: flag, value: value)+ }+ repetitionPenalty = parsed+ case "--seed":+ let value = try takeValue(argv, &index, flag: flag)+ guard let parsed = UInt64(value) else {+ throw ArgsError.invalidValue(flag: flag, value: value)+ }+ seed = parsed+ case "--stop":+ stops.append(try takeValue(argv, &index, flag: flag))+ default:+ throw ArgsError.unknownFlag(flag)+ }+ }++ guard let model else { throw ArgsError.requiredMissing("--model") }+ guard let prompt else { throw ArgsError.requiredMissing("--prompt") }+ if temperature > 0, topK == nil, let topP, topP < 1 {+ throw ArgsError.invalidValue(+ flag: "--top-p",+ value: "\(topP) requires --top-k between 1 and 256")+ }+ return Args(model: model,+ prompt: prompt,+ maxNew: maxNew,+ maxContext: maxContext,+ temperature: temperature,+ topK: topK,+ topP: topP,+ repetitionPenalty: repetitionPenalty,+ seed: seed,+ stops: stops,+ quiet: quiet)+ }++ private static func takeValue(_ argv: [String],+ _ index: inout Int,+ flag: String) throws -> String {+ guard index + 1 < argv.count else { throw ArgsError.missingValue(flag: flag) }+ let value = argv[index + 1]+ index += 2+ return value+ }+}diff --git a/Sources/TurboFieldfareCLI/Command/main.swift b/Sources/TurboFieldfareCLI/Command/main.swiftnew file mode 100644index 00000000..969e86b5--- /dev/null+++ b/Sources/TurboFieldfareCLI/Command/main.swift@@ -0,0 +1,44 @@+import Darwin+import Foundation+import TurboFieldfareCLICore++let rawArgv = Array(CommandLine.arguments.dropFirst())+let parsedArgs: Args+do {+ parsedArgs = try Args.parse(rawArgv)+} catch ArgsError.helpRequested {+ print(Args.usage)+ exit(0)+} catch {+ FileHandle.standardError.write(Data("error: \(error)\n\n".utf8))+ FileHandle.standardError.write(Data(Args.usage.utf8))+ FileHandle.standardError.write(Data("\n".utf8))+ exit(2)+}++// Keep the cancellable task off the top-level executor so the blocking signal+// bridge cannot prevent it from starting.+final class RunBox: @unchecked Sendable {+ var code: Int32 = 0+ var task: Task<Void, Never>?+}++func drive(_ args: Args) -> Int32 {+ let box = RunBox()+ let sem = DispatchSemaphore(value: 0)+ box.task = Task {+ let result = await run(args: args)+ box.code = result.exitCode+ sem.signal()+ }++ signal(SIGINT, SIG_IGN)+ let sigintSource = DispatchSource.makeSignalSource(signal: SIGINT, queue: .global())+ sigintSource.setEventHandler { box.task?.cancel() }+ sigintSource.resume()++ sem.wait()+ return box.code+}++exit(drive(parsedArgs))diff --git a/Sources/TurboFieldfareCLI/Run.swift b/Sources/TurboFieldfareCLI/Run.swiftnew file mode 100644index 00000000..69b367f0--- /dev/null+++ b/Sources/TurboFieldfareCLI/Run.swift@@ -0,0 +1,90 @@+import Foundation+import Metal+import TurboFieldfare++public struct RunResult: Equatable, Sendable {+ public let exitCode: Int32+ public init(exitCode: Int32) { self.exitCode = exitCode }+}++public func run(args: Args,+ stdout: FileHandle = .standardOutput,+ stderr: FileHandle = .standardError) async -> RunResult {+ do {+ let config = GenerationConfig(+ maxNewTokens: args.maxNew,+ temperature: args.temperature,+ topK: args.topK,+ topP: args.topP,+ repetitionPenalty: args.repetitionPenalty,+ seed: args.seed,+ stopStrings: args.stops,+ extraStopTokens: [])+ let runtime = RuntimeConfiguration(+ forceLogitsHead: !config.isPureGreedy)+ let modelURL = URL(fileURLWithPath: args.model)+ let tokenizer = try await GFTokenizer.load(forModelDirectory: modelURL)+ let promptIds = tokenizer.encode(args.prompt, addBOS: true)+ guard !promptIds.isEmpty else { return errored(stderr, "empty prompt", 2) }+ guard promptIds.count + args.maxNew <= args.maxContext else {+ return errored(+ stderr,+ "context overflow: prompt \(promptIds.count) + maxNew \(args.maxNew) exceeds maxContext \(args.maxContext)",+ 2)+ }++ guard MTLCreateSystemDefaultDevice() != nil else {+ return errored(stderr, "no Metal device", 1)+ }+ let context = try MetalContext()+ let model = try Model.load(+ directoryURL: modelURL,+ device: context.device,+ streamingMode: .pread(slotCount: runtime.expertCacheSlots),+ expertCachePolicy: runtime.modelExpertCachePolicy,+ integrityPolicy: .fullSha256)+ let runner = try RealForwardRunner(+ model: model,+ context: context,+ maxContext: args.maxContext,+ runtimeConfiguration: runtime)+ let scratch = try RawCompletionScratch(context: context,+ vocab: model.config.vocabSize)+ let stats = try await runRawCompletion(+ producer: runner,+ tokenizer: tokenizer,+ promptIds: promptIds,+ config: config,+ context: context,+ scratch: scratch,+ prefillConfig: runtime.prefillConfig) { progress in+ switch progress {+ case .prefill:+ break+ case .token(_, _, let delta):+ if !delta.isEmpty { stdout.write(Data(delta.utf8)) }+ case .tail(let tail):+ stdout.write(Data(tail.utf8))+ }+ }++ if !args.quiet {+ let tokensPerSecond = stats.decodeSeconds > 0+ ? Double(stats.newTokens) / stats.decodeSeconds+ : 0+ let footer = "\n[stop=\(String(describing: stats.reason)) prefill=\(stats.prefillTokens)tok new=\(stats.newTokens)tok decode=\(String(format: "%.2f", stats.decodeSeconds))s tok/s=\(String(format: "%.3f", tokensPerSecond))]\n"+ stderr.write(Data(footer.utf8))+ }+ return RunResult(exitCode: 0)+ } catch is CancellationError {+ stdout.write(Data("\n".utf8))+ return RunResult(exitCode: 130)+ } catch {+ return errored(stderr, "\(error)", 1)+ }+}++private func errored(_ stderr: FileHandle, _ message: String, _ code: Int32) -> RunResult {+ stderr.write(Data("error: \(message)\n".utf8))+ return RunResult(exitCode: code)+}diff --git a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swiftnew file mode 100644index 00000000..1501ac13--- /dev/null+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift@@ -0,0 +1,230 @@+import Foundation++public struct DecodeRuntimeOptions: Codable, Sendable, Equatable {+ public var expertCacheSlots: Int+ public var expertCachePolicy: String+ public var prefillEnabled: Bool+ public var prefillChunkTokens: Int+ public var turboQuantKVEnabled: Bool+ public var rdadvisePolicy: String+ public var modelVerification: String++ public init(expertCacheSlots: Int = 16,+ expertCachePolicy: String = "lfu",+ prefillEnabled: Bool = true,+ prefillChunkTokens: Int = 128,+ turboQuantKVEnabled: Bool = false,+ rdadvisePolicy: String = "off",+ modelVerification: String = "full-sha256") {+ self.expertCacheSlots = expertCacheSlots+ self.expertCachePolicy = expertCachePolicy+ self.prefillEnabled = prefillEnabled+ self.prefillChunkTokens = prefillChunkTokens+ self.turboQuantKVEnabled = turboQuantKVEnabled+ self.rdadvisePolicy = rdadvisePolicy+ self.modelVerification = modelVerification+ }+}++public struct DecodeLoadRequest: Codable, Sendable {+ public var modelPath: String+ public var maxContextTokens: Int+ public var runtimeOptions: DecodeRuntimeOptions+ public var forceLogitsHead: Bool+ public var requestID: UUID++ public init(modelPath: String, maxContextTokens: Int,+ runtimeOptions: DecodeRuntimeOptions = DecodeRuntimeOptions(),+ forceLogitsHead: Bool = false,+ requestID: UUID = UUID()) {+ self.modelPath = modelPath+ self.maxContextTokens = maxContextTokens+ self.runtimeOptions = runtimeOptions+ self.forceLogitsHead = forceLogitsHead+ self.requestID = requestID+ }+}++public struct DecodeGenerationRequest: Codable, Sendable {+ public var prompt: String+ public var maxNewTokens: Int+ public var maxContextTokens: Int+ public var temperature: Float+ public var repetitionPenalty: Float+ public var runtimeOptions: DecodeRuntimeOptions+ public var generationID: UUID++ public init(prompt: String, maxNewTokens: Int, maxContextTokens: Int,+ temperature: Float, repetitionPenalty: Float = 1,+ runtimeOptions: DecodeRuntimeOptions = DecodeRuntimeOptions(),+ generationID: UUID = UUID()) {+ self.prompt = prompt+ self.maxNewTokens = maxNewTokens+ self.maxContextTokens = maxContextTokens+ self.temperature = temperature+ self.repetitionPenalty = repetitionPenalty+ self.runtimeOptions = runtimeOptions+ self.generationID = generationID+ }+}++public enum DecodeServiceCommand: Codable, Sendable {+ case load(DecodeLoadRequest)+ case generate(DecodeGenerationRequest)+ case cancel+ case unload(UUID)+ case shutdown+}++public enum DecodeServiceEventKind: String, Codable, Sendable {+ case loading+ case ready+ case prefill+ case snapshot+ case finished+ case cancelled+ case failed+ case unloaded+}++public struct DecodeRunnerDiagnostics: Codable, Sendable, Equatable {+ public var cb1MillisecondsPerToken: Double+ public var ioMillisecondsPerToken: Double+ public var cb2MillisecondsPerToken: Double+ public var headMillisecondsPerToken: Double+ public var rdadviseMillisecondsPerToken: Double+ public var rdadviseCallsPerToken: Double+ public var rdadviseMegabytesPerToken: Double+ public var rdadviseSkippedPerToken: Double+ public var rdadviseFailures: UInt64++ public init(cb1MillisecondsPerToken: Double,+ ioMillisecondsPerToken: Double,+ cb2MillisecondsPerToken: Double,+ headMillisecondsPerToken: Double,+ rdadviseMillisecondsPerToken: Double,+ rdadviseCallsPerToken: Double,+ rdadviseMegabytesPerToken: Double,+ rdadviseSkippedPerToken: Double,+ rdadviseFailures: UInt64) {+ self.cb1MillisecondsPerToken = cb1MillisecondsPerToken+ self.ioMillisecondsPerToken = ioMillisecondsPerToken+ self.cb2MillisecondsPerToken = cb2MillisecondsPerToken+ self.headMillisecondsPerToken = headMillisecondsPerToken+ self.rdadviseMillisecondsPerToken = rdadviseMillisecondsPerToken+ self.rdadviseCallsPerToken = rdadviseCallsPerToken+ self.rdadviseMegabytesPerToken = rdadviseMegabytesPerToken+ self.rdadviseSkippedPerToken = rdadviseSkippedPerToken+ self.rdadviseFailures = rdadviseFailures+ }+}++public struct DecodePrefillDiagnostics: Codable, Sendable, Equatable {+ public var requestedMode: String+ public var executedMode: String+ public var kvStorageMode: String?+ public var chunkCompleteness: String+ public var unsupportedReason: String?++ public init(requestedMode: String, executedMode: String,+ kvStorageMode: String?, chunkCompleteness: String,+ unsupportedReason: String?) {+ self.requestedMode = requestedMode+ self.executedMode = executedMode+ self.kvStorageMode = kvStorageMode+ self.chunkCompleteness = chunkCompleteness+ self.unsupportedReason = unsupportedReason+ }+}++public struct DecodeServiceEvent: Codable, Sendable {+ public var kind: DecodeServiceEventKind+ public var generationID: UUID+ public var sequence: UInt64+ public var textDelta: String+ public var tokenCount: Int+ public var promptTokenCount: Int?+ public var prefillDone: Int?+ public var prefillTotal: Int?+ public var prefillSeconds: Double?+ public var timeToFirstTokenSeconds: Double?+ public var decodeSeconds: Double+ public var tokensPerSecond: Double+ public var stopReason: String?+ public var error: String?+ public var currentMemoryBytes: UInt64?+ public var peakMemoryBytes: UInt64?+ public var prefill: DecodePrefillDiagnostics?+ public var runner: DecodeRunnerDiagnostics?++ public init(kind: DecodeServiceEventKind, generationID: UUID,+ sequence: UInt64 = 0, textDelta: String = "",+ tokenCount: Int = 0, promptTokenCount: Int? = nil,+ prefillDone: Int? = nil, prefillTotal: Int? = nil,+ prefillSeconds: Double? = nil,+ timeToFirstTokenSeconds: Double? = nil,+ decodeSeconds: Double = 0, tokensPerSecond: Double = 0,+ stopReason: String? = nil, error: String? = nil,+ currentMemoryBytes: UInt64? = nil, peakMemoryBytes: UInt64? = nil,+ prefill: DecodePrefillDiagnostics? = nil,+ runner: DecodeRunnerDiagnostics? = nil) {+ self.kind = kind+ self.generationID = generationID+ self.sequence = sequence+ self.textDelta = textDelta+ self.tokenCount = tokenCount+ self.promptTokenCount = promptTokenCount+ self.prefillDone = prefillDone+ self.prefillTotal = prefillTotal+ self.prefillSeconds = prefillSeconds+ self.timeToFirstTokenSeconds = timeToFirstTokenSeconds+ self.decodeSeconds = decodeSeconds+ self.tokensPerSecond = tokensPerSecond+ self.stopReason = stopReason+ self.error = error+ self.currentMemoryBytes = currentMemoryBytes+ self.peakMemoryBytes = peakMemoryBytes+ self.prefill = prefill+ self.runner = runner+ }+}++public enum DecodeFrameCodec {+ public static let maximumPayloadBytes = 4 * 1_024 * 1_024++ public static func encode<T: Encodable>(_ value: T) throws -> Data {+ let payload = try JSONEncoder().encode(value)+ guard payload.count <= maximumPayloadBytes else { throw DecodeFrameError.oversized }+ var length = UInt32(payload.count).littleEndian+ var frame = withUnsafeBytes(of: &length) { Data($0) }+ frame.append(payload)+ return frame+ }++ public static func read<T: Decodable>(_ type: T.Type, from handle: FileHandle) throws -> T {+ let header = try readExactly(4, from: handle)+ let count = header.withUnsafeBytes { raw -> UInt32 in+ raw.loadUnaligned(as: UInt32.self).littleEndian+ }+ guard count <= maximumPayloadBytes else { throw DecodeFrameError.oversized }+ let payload = try readExactly(Int(count), from: handle)+ return try JSONDecoder().decode(type, from: payload)+ }++ private static func readExactly(_ count: Int, from handle: FileHandle) throws -> Data {+ var result = Data()+ result.reserveCapacity(count)+ while result.count < count {+ guard let chunk = try handle.read(upToCount: count - result.count), !chunk.isEmpty else {+ throw DecodeFrameError.unexpectedEOF+ }+ result.append(chunk)+ }+ return result+ }+}++public enum DecodeFrameError: Error {+ case oversized+ case unexpectedEOF+}diff --git a/Sources/TurboFieldfareDecodeProtocol/DecodeUnixSocket.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeUnixSocket.swiftnew file mode 100644index 00000000..db8eaad1--- /dev/null+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeUnixSocket.swift@@ -0,0 +1,69 @@+import Darwin+import Foundation++public enum DecodeUnixSocket {+ public static func connect(path: String) throws -> (input: FileHandle, output: FileHandle) {+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)+ guard fd >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ do {+ var address = try makeAddress(path: path)+ let result = withUnsafePointer(to: &address) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ guard result == 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ return try handles(for: fd)+ } catch {+ Darwin.close(fd)+ throw error+ }+ }++ public static func listenAndAccept(path: String) throws+ -> (input: FileHandle, output: FileHandle) {+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)+ guard fd >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ do {+ var address = try makeAddress(path: path)+ unlink(path)+ let bindResult = withUnsafePointer(to: &address) {+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ Darwin.bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))+ }+ }+ guard bindResult == 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ guard listen(fd, 1) == 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ let accepted = Darwin.accept(fd, nil, nil)+ guard accepted >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ Darwin.close(fd)+ return try handles(for: accepted)+ } catch {+ Darwin.close(fd)+ unlink(path)+ throw error+ }+ }++ private static func handles(for fd: Int32) throws+ -> (input: FileHandle, output: FileHandle) {+ let outputFD = dup(fd)+ guard outputFD >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }+ return (FileHandle(fileDescriptor: fd, closeOnDealloc: true),+ FileHandle(fileDescriptor: outputFD, closeOnDealloc: true))+ }++ private static func makeAddress(path: String) throws -> sockaddr_un {+ let bytes = Array(path.utf8)+ var address = sockaddr_un()+ guard bytes.count < MemoryLayout.size(ofValue: address.sun_path) else {+ throw POSIXError(.ENAMETOOLONG)+ }+ address.sun_family = sa_family_t(AF_UNIX)+ withUnsafeMutableBytes(of: &address.sun_path) { destination in+ destination.copyBytes(from: bytes)+ destination[bytes.count] = 0+ }+ return address+ }+}diff --git a/Sources/TurboFieldfareDecodeService/DecodeCommandQueue.swift b/Sources/TurboFieldfareDecodeService/DecodeCommandQueue.swiftnew file mode 100644index 00000000..523571e8--- /dev/null+++ b/Sources/TurboFieldfareDecodeService/DecodeCommandQueue.swift@@ -0,0 +1,30 @@+import Foundation+import TurboFieldfareDecodeProtocol++final class DecodeCommandQueue: @unchecked Sendable {+ private let condition = NSCondition()+ private var commands: [DecodeServiceCommand] = []+ private var closed = false++ func append(_ command: DecodeServiceCommand) {+ condition.lock()+ commands.append(command)+ condition.signal()+ condition.unlock()+ }++ func close() {+ condition.lock()+ closed = true+ condition.broadcast()+ condition.unlock()+ }++ func next() -> DecodeServiceCommand? {+ condition.lock()+ defer { condition.unlock() }+ while commands.isEmpty && !closed { condition.wait() }+ guard !commands.isEmpty else { return nil }+ return commands.removeFirst()+ }+}diff --git a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swiftnew file mode 100644index 00000000..ca48f53a--- /dev/null+++ b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift@@ -0,0 +1,159 @@+import Foundation+import TurboFieldfare+import TurboFieldfareAppCore+import TurboFieldfareDecodeProtocol++final class DecodeServiceOutbox: @unchecked Sendable {+ private struct PrefillProgress {+ var done: Int+ var total: Int+ }++ private struct State {+ var pendingText = ""+ var latestPrefill: PrefillProgress?+ var latestToken: AppTokenEvent?+ var terminal: DecodeServiceEvent?+ var finished = false+ var sequence: UInt64 = 0+ }++ private let condition = NSCondition()+ private var state = State()+ private let generationID: UUID+ private let memorySampler = AppMemorySampler()++ init(generationID: UUID) {+ self.generationID = generationID+ memorySampler.resetPeak()+ }++ func publish(_ event: AppInferenceEvent) {+ condition.lock()+ switch event {+ case .prefillProgress(let done, let total):+ state.latestPrefill = PrefillProgress(done: done, total: total)+ condition.signal()+ case .token(let token):+ state.pendingText += token.textDelta+ state.latestToken = token+ case .finished(let diagnostics):+ state.terminal = terminal(.finished, diagnostics: diagnostics)+ case .cancelled(let diagnostics):+ state.terminal = terminal(.cancelled, diagnostics: diagnostics)+ case .failed(let error, let diagnostics):+ state.terminal = terminal(+ .failed, diagnostics: diagnostics, error: error.userMessage)+ }+ if state.terminal != nil { condition.signal() }+ condition.unlock()+ }++ func finish(error: Error? = nil) {+ condition.lock()+ if state.terminal == nil, let error {+ state.terminal = DecodeServiceEvent(+ kind: .failed, generationID: generationID, error: "\(error)")+ }+ state.finished = true+ condition.broadcast()+ condition.unlock()+ }++ func runWriter(to handle: FileHandle) throws {+ while true {+ condition.lock()+ if state.terminal == nil, !state.finished {+ _ = condition.wait(until: Date().addingTimeInterval(0.1))+ }+ let prefill = state.latestPrefill+ let text = state.pendingText+ let token = state.latestToken+ let terminal = state.terminal+ let done = state.finished+ state.latestPrefill = nil+ state.pendingText = ""+ state.latestToken = nil+ state.terminal = nil+ var prefillSequence: UInt64?+ if prefill != nil {+ state.sequence &+= 1+ prefillSequence = state.sequence+ }+ var tokenSequence: UInt64?+ if !text.isEmpty || token != nil {+ state.sequence &+= 1+ tokenSequence = state.sequence+ }+ condition.unlock()++ if let prefill, let prefillSequence {+ let snapshot = DecodeServiceEvent(+ kind: .prefill, generationID: generationID,+ sequence: prefillSequence,+ prefillDone: prefill.done, prefillTotal: prefill.total)+ try handle.write(contentsOf: DecodeFrameCodec.encode(snapshot))+ }+ if !text.isEmpty || token != nil {+ let elapsed = token?.elapsedDecodeSeconds ?? 0+ let count = (token?.index ?? -1) + 1+ let snapshot = DecodeServiceEvent(+ kind: .snapshot, generationID: generationID,+ sequence: tokenSequence ?? 0, textDelta: text, tokenCount: count,+ decodeSeconds: elapsed,+ tokensPerSecond: elapsed > 0 ? Double(count) / elapsed : 0,+ currentMemoryBytes: memorySampler.sample(),+ peakMemoryBytes: memorySampler.peakBytes)+ try handle.write(contentsOf: DecodeFrameCodec.encode(snapshot))+ }+ if let terminal {+ try handle.write(contentsOf: DecodeFrameCodec.encode(terminal))+ }+ if done, terminal == nil { return }+ if terminal != nil && done { return }+ }+ }++ private func terminal(_ kind: DecodeServiceEventKind,+ diagnostics: AppDiagnostics?,+ error: String? = nil) -> DecodeServiceEvent {+ DecodeServiceEvent(+ kind: kind, generationID: generationID,+ tokenCount: diagnostics?.generatedTokens ?? 0,+ promptTokenCount: diagnostics?.promptTokenCount,+ prefillSeconds: diagnostics?.prefillSeconds,+ timeToFirstTokenSeconds: diagnostics?.timeToFirstTokenSeconds,+ decodeSeconds: diagnostics?.decodeSeconds ?? 0,+ tokensPerSecond: diagnostics?.tokensPerSecond ?? 0,+ stopReason: diagnostics?.stopReason.rawValue,+ error: error,+ currentMemoryBytes: memorySampler.sample(),+ peakMemoryBytes: memorySampler.peakBytes,+ prefill: diagnostics?.prefill.map(Self.prefillDiagnostics),+ runner: diagnostics?.runner.map(Self.runnerDiagnostics))+ }++ private static func prefillDiagnostics(_ value: PrefillExecutionDiagnostics)+ -> DecodePrefillDiagnostics {+ DecodePrefillDiagnostics(+ requestedMode: value.requestedMode.rawValue,+ executedMode: value.executedMode.rawValue,+ kvStorageMode: value.kvStorageMode?.rawValue,+ chunkCompleteness: value.chunkCompleteness.rawValue,+ unsupportedReason: value.unsupportedReason)+ }++ private static func runnerDiagnostics(_ value: AppRunnerDiagnostics)+ -> DecodeRunnerDiagnostics {+ DecodeRunnerDiagnostics(+ cb1MillisecondsPerToken: value.cb1MillisecondsPerToken,+ ioMillisecondsPerToken: value.ioMillisecondsPerToken,+ cb2MillisecondsPerToken: value.cb2MillisecondsPerToken,+ headMillisecondsPerToken: value.headMillisecondsPerToken,+ rdadviseMillisecondsPerToken: value.rdadviseMillisecondsPerToken,+ rdadviseCallsPerToken: value.rdadviseCallsPerToken,+ rdadviseMegabytesPerToken: value.rdadviseMegabytesPerToken,+ rdadviseSkippedPerToken: value.rdadviseSkippedPerToken,+ rdadviseFailures: value.rdadviseFailures)+ }+}diff --git a/Sources/TurboFieldfareDecodeService/Entry.swift b/Sources/TurboFieldfareDecodeService/Entry.swiftnew file mode 100644index 00000000..2d8b5f1f--- /dev/null+++ b/Sources/TurboFieldfareDecodeService/Entry.swift@@ -0,0 +1,193 @@+import Darwin+import Foundation+import TurboFieldfareAppCore+import TurboFieldfareDecodeProtocol++@main enum TurboFieldfareDecodeServiceMain {+ static func main() async {+ let socketPath = argument(after: "--socket")+ let launchLabel = argument(after: "--launch-label")+ let handles: (input: FileHandle, output: FileHandle)+ do {+ handles = if let socketPath {+ try DecodeUnixSocket.listenAndAccept(path: socketPath)+ } else {+ (.standardInput, .standardOutput)+ }+ } catch {+ FileHandle.standardError.write(Data("Decode service transport failed: \(error)\n".utf8))+ Foundation.exit(1)+ }+ defer {+ if let socketPath { unlink(socketPath) }+ if let launchLabel { retireLaunchJob(launchLabel) }+ }++ let client = RealInferenceClient()+ let commands = DecodeCommandQueue()+ let input = Thread {+ do {+ while true {+ let command = try DecodeFrameCodec.read(+ DecodeServiceCommand.self, from: handles.input)+ if case .cancel = command { client.cancel() }+ commands.append(command)+ if case .shutdown = command { break }+ }+ } catch {+ commands.close()+ }+ }+ input.name = "TurboFieldfare.DecodeService.Input"+ input.qualityOfService = .userInitiated+ input.start()++ var modelDirectory: URL?+ var loadedOptions: DecodeRuntimeOptions?+ while let command = await nextCommand(commands) {+ switch command {+ case .load(let request):+ let directory = URL(fileURLWithPath: request.modelPath)+ do {+ let options = try appRuntimeOptions(request.runtimeOptions)+ try await client.ensureLoaded(+ modelDirectory: directory,+ maxContextTokens: request.maxContextTokens,+ options: options,+ forceLogitsHead: request.forceLogitsHead) { _ in }+ modelDirectory = directory+ loadedOptions = request.runtimeOptions+ let memory = AppMemorySampler().sample()+ try write(DecodeServiceEvent(+ kind: .ready, generationID: request.requestID,+ currentMemoryBytes: memory, peakMemoryBytes: memory),+ to: handles.output)+ } catch {+ try? write(DecodeServiceEvent(+ kind: .failed, generationID: request.requestID,+ error: "\(error)"), to: handles.output)+ }+ case .generate(let request):+ guard let modelDirectory else {+ try? write(DecodeServiceEvent(+ kind: .failed, generationID: request.generationID,+ error: "model is not loaded"), to: handles.output)+ continue+ }+ guard request.runtimeOptions == loadedOptions else {+ try? write(DecodeServiceEvent(+ kind: .failed, generationID: request.generationID,+ error: "generation runtime options do not match the loaded session"),+ to: handles.output)+ continue+ }++ let outbox = DecodeServiceOutbox(generationID: request.generationID)+ let writerFinished = DispatchSemaphore(value: 0)+ let writer = Thread {+ defer { writerFinished.signal() }+ do { try outbox.runWriter(to: handles.output) }+ catch {+ FileHandle.standardError.write(Data("IPC writer failed: \(error)\n".utf8))+ }+ }+ writer.name = "TurboFieldfare.DecodeService.Writer"+ writer.qualityOfService = .userInitiated+ writer.start()++ do {+ let options = try appRuntimeOptions(request.runtimeOptions)+ let generation = AppGenerationRequest(+ modelDirectory: modelDirectory, prompt: request.prompt,+ maxNewTokens: request.maxNewTokens,+ maxContextTokens: request.maxContextTokens,+ temperature: request.temperature,+ repetitionPenalty: request.repetitionPenalty,+ runtimeOptions: options)+ for try await event in client.generate(generation) {+ outbox.publish(event)+ }+ outbox.finish()+ } catch {+ outbox.finish(error: error)+ }+ await withCheckedContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ writerFinished.wait()+ continuation.resume()+ }+ }+ case .cancel:+ break+ case .unload(let requestID):+ await client.unload()+ modelDirectory = nil+ loadedOptions = nil+ try? write(DecodeServiceEvent(+ kind: .unloaded, generationID: requestID), to: handles.output)+ case .shutdown:+ await client.unload()+ return+ }+ }+ }++ private static func nextCommand(_ commands: DecodeCommandQueue)+ async -> DecodeServiceCommand? {+ await withCheckedContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ continuation.resume(returning: commands.next())+ }+ }+ }++ private static func write(_ event: DecodeServiceEvent,+ to handle: FileHandle) throws {+ try handle.write(contentsOf: DecodeFrameCodec.encode(event))+ }++ private static func appRuntimeOptions(_ options: DecodeRuntimeOptions) throws+ -> AppRuntimeOptions {+ guard let cachePolicy = AppExpertCachePolicy(+ rawValue: options.expertCachePolicy) else {+ throw AppInferenceError.invalidRequest(+ "unknown expert cache policy \(options.expertCachePolicy)")+ }+ guard let rdadvisePolicy = AppRDAdvicePolicy(+ rawValue: options.rdadvisePolicy) else {+ throw AppInferenceError.invalidRequest(+ "unknown RDADVISE policy \(options.rdadvisePolicy)")+ }+ guard let modelVerification = AppModelVerification(+ rawValue: options.modelVerification) else {+ throw AppInferenceError.invalidRequest(+ "unknown model verification \(options.modelVerification)")+ }+ let resolved = AppRuntimeOptions(+ expertCacheSlots: options.expertCacheSlots,+ expertCachePolicy: cachePolicy,+ prefillEnabled: options.prefillEnabled,+ prefillChunkTokens: options.prefillChunkTokens,+ turboQuantKVEnabled: options.turboQuantKVEnabled,+ rdadvisePolicy: rdadvisePolicy,+ modelVerification: modelVerification)+ try resolved.validate()+ return resolved+ }++ private static func argument(after name: String) -> String? {+ let arguments = CommandLine.arguments+ guard let index = arguments.firstIndex(of: name),+ arguments.indices.contains(index + 1) else { return nil }+ return arguments[index + 1]+ }++ private static func retireLaunchJob(_ label: String) {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/bin/launchctl")+ process.arguments = ["bootout", "gui/\(getuid())/\(label)"]+ process.standardOutput = FileHandle.nullDevice+ process.standardError = FileHandle.nullDevice+ try? process.run()+ }+}diff --git a/Sources/TurboFieldfareRepack/Command/main.swift b/Sources/TurboFieldfareRepack/Command/main.swiftnew file mode 100644index 00000000..836fe808--- /dev/null+++ b/Sources/TurboFieldfareRepack/Command/main.swift@@ -0,0 +1,133 @@+import Foundation+import TurboFieldfareRepackCore++private let usage = """+Usage:+ TurboFieldfareRepack --output <model.gturbo> [--overwrite]+ TurboFieldfareRepack --verify-install --input-gturbo <model.gturbo>+ TurboFieldfareRepack --help++The installer streams the supported Gemma 4 checkpoint from Hugging Face and+repackages it without materializing the source checkpoint on disk. Set HF_TOKEN+only if Hugging Face requests authentication.+"""++private struct Arguments {+ var output: String?+ var overwrite = false+ var verifyInstall = false+ var inputGTurbo: String?++ static func parse(_ values: [String]) throws -> Arguments {+ var parsed = Arguments()+ var index = 1+ while index < values.count {+ let flag = values[index]+ switch flag {+ case "--help":+ throw ParseError.help+ case "--overwrite":+ parsed.overwrite = true+ index += 1+ case "--verify-install":+ parsed.verifyInstall = true+ index += 1+ case "--output", "--input-gturbo":+ guard index + 1 < values.count else {+ throw ParseError.missingValue(flag)+ }+ if flag == "--output" {+ parsed.output = values[index + 1]+ } else {+ parsed.inputGTurbo = values[index + 1]+ }+ index += 2+ default:+ throw ParseError.unknown(flag)+ }+ }++ if parsed.verifyInstall {+ guard parsed.inputGTurbo != nil else {+ throw ParseError.missingRequired("--input-gturbo")+ }+ guard parsed.output == nil, !parsed.overwrite else {+ throw ParseError.invalidMode("verification accepts only --input-gturbo")+ }+ } else {+ guard parsed.output != nil else {+ throw ParseError.missingRequired("--output")+ }+ guard parsed.inputGTurbo == nil else {+ throw ParseError.invalidMode("--input-gturbo requires --verify-install")+ }+ }+ return parsed+ }+}++private enum ParseError: Error, CustomStringConvertible {+ case help+ case unknown(String)+ case missingValue(String)+ case missingRequired(String)+ case invalidMode(String)++ var description: String {+ switch self {+ case .help: return "help"+ case .unknown(let flag): return "unknown argument: \(flag)"+ case .missingValue(let flag): return "missing value for \(flag)"+ case .missingRequired(let flag): return "missing required argument: \(flag)"+ case .invalidMode(let message): return message+ }+ }+}++private func printError(_ message: String) {+ FileHandle.standardError.write(Data((message + "\n").utf8))+}++private func run(_ values: [String]) async -> Int32 {+ let arguments: Arguments+ do {+ arguments = try Arguments.parse(values)+ } catch ParseError.help {+ print(usage)+ return 0+ } catch {+ printError("error: \(error)\n\n\(usage)")+ return 2+ }++ if arguments.verifyInstall, let input = arguments.inputGTurbo {+ do {+ let result = try VerifiedInstallTool.run(+ options: VerifyInstallOptions(inputGTurbo: input))+ print("Verified \(result.fileCount) files (\(result.bytesVerified) bytes)")+ print("Receipt: \(result.receiptPath)")+ return 0+ } catch {+ printError("verification failed: \(error)")+ return 1+ }+ }++ guard let output = arguments.output else { return 2 }+ let options = SupportedModelSource.installOptions(+ outputDirectory: URL(fileURLWithPath: output),+ overwrite: arguments.overwrite,+ token: ProcessInfo.processInfo.environment["HF_TOKEN"])+ do {+ let result = try await RemoteStreamingRepacker(options: options).run()+ print("Installed \(SupportedModelSource.displayName)")+ print("Source revision: \(result.resolvedCommit)")+ print("Model: \(result.outputDir)")+ return 0+ } catch {+ printError("install failed: \(error)")+ return 1+ }+}++exit(await run(CommandLine.arguments))diff --git a/Sources/TurboFieldfareRepack/Core/Format/ArchInfo.swift b/Sources/TurboFieldfareRepack/Core/Format/ArchInfo.swiftnew file mode 100644index 00000000..8f4398c9--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Format/ArchInfo.swift@@ -0,0 +1,84 @@+import Foundation++/// Architecture facts mirrored into `manifest.json -> arch`. Cross-checked by+/// the runtime loader at startup.+struct ArchInfo: Sendable, Equatable {+ let hiddenSize: Int+ let intermediateSize: Int // shared expert FFN+ let moeIntermediateSize: Int // per-expert FFN+ let numHeads: Int+ let numKVHeads: Int+ let numFullKVHeads: Int+ let headDim: Int+ let fullHeadDim: Int+ let vocabSize: Int+ let slidingWindow: Int+ let finalLogitSoftcap: Double+ let ropeTheta: Double+ let fullRopeTheta: Double+ let partialRotaryFactor: Double+ let numLayers: Int+ let numExperts: Int+ let topKExperts: Int+ let tieWordEmbeddings: Bool+ let attentionKEqV: Bool+ /// 1 if `full_attention`, 0 if `sliding_attention`. Indexed by layer.+ let fullAttentionLayerMask: [UInt8]+ let hiddenActivation: String++ static func load(configPath: String) throws -> ArchInfo {+ let data = try Data(contentsOf: URL(fileURLWithPath: configPath))+ guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let tc = root["text_config"] as? [String: Any] else {+ throw RepackError.configJsonInvalid(path: configPath, detail: "no text_config")+ }+ func i(_ k: String) throws -> Int {+ guard let n = (tc[k] as? Int) ?? (tc[k] as? NSNumber)?.intValue else {+ throw RepackError.configJsonInvalid(path: configPath, detail: "missing \(k)")+ }+ return n+ }+ func d(_ k: String) throws -> Double {+ guard let n = (tc[k] as? Double) ?? (tc[k] as? NSNumber)?.doubleValue else {+ throw RepackError.configJsonInvalid(path: configPath, detail: "missing \(k)")+ }+ return n+ }+ let layerTypes = (tc["layer_types"] as? [String]) ?? []+ let mask = layerTypes.map { UInt8($0 == "full_attention" ? 1 : 0) }+ let rope = (tc["rope_parameters"] as? [String: Any]) ?? [:]+ let ropeFull = (rope["full_attention"] as? [String: Any]) ?? [:]+ let ropeSWA = (rope["sliding_attention"] as? [String: Any]) ?? [:]+ let prf = (ropeFull["partial_rotary_factor"] as? Double)+ ?? (ropeFull["partial_rotary_factor"] as? NSNumber)?.doubleValue ?? 0.25+ let fullTheta = (ropeFull["rope_theta"] as? Double)+ ?? (ropeFull["rope_theta"] as? NSNumber)?.doubleValue ?? 1_000_000.0+ let swaTheta = (ropeSWA["rope_theta"] as? Double)+ ?? (ropeSWA["rope_theta"] as? NSNumber)?.doubleValue ?? 10_000.0+ let kEqV = (tc["attention_k_eq_v"] as? Bool) ?? false+ let tie = (tc["tie_word_embeddings"] as? Bool) ?? false+ let act = (tc["hidden_activation"] as? String) ?? "gelu_pytorch_tanh"+ return ArchInfo(+ hiddenSize: try i("hidden_size"),+ intermediateSize: try i("intermediate_size"),+ moeIntermediateSize: try i("moe_intermediate_size"),+ numHeads: try i("num_attention_heads"),+ numKVHeads: try i("num_key_value_heads"),+ numFullKVHeads: try i("num_global_key_value_heads"),+ headDim: try i("head_dim"),+ fullHeadDim: try i("global_head_dim"),+ vocabSize: try i("vocab_size"),+ slidingWindow: try i("sliding_window"),+ finalLogitSoftcap: try d("final_logit_softcapping"),+ ropeTheta: swaTheta,+ fullRopeTheta: fullTheta,+ partialRotaryFactor: prf,+ numLayers: try i("num_hidden_layers"),+ numExperts: try i("num_experts"),+ topKExperts: try i("top_k_experts"),+ tieWordEmbeddings: tie,+ attentionKEqV: kEqV,+ fullAttentionLayerMask: mask,+ hiddenActivation: act)+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Format/GTurboEncoders.swift b/Sources/TurboFieldfareRepack/Core/Format/GTurboEncoders.swiftnew file mode 100644index 00000000..5d2754f6--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Format/GTurboEncoders.swift@@ -0,0 +1,81 @@+import Foundation++/// Little-endian binary encoders for the resident `IndexHeader` and 72-byte+/// `IndexEntry` records. Used by the resident writer and the+/// matching loader-side parsers; kept in one place so the on-disk layout+/// changes only here.+enum GTurboBinary {++ static let indexHeaderBytes: Int = 24+ static let indexEntryBytes: Int = 72++ /// Write `IndexHeader { indexSize, residentSize, entryCount }` (24 bytes, LE).+ static func writeIndexHeader(into buf: UnsafeMutableRawPointer,+ indexSize: UInt64,+ residentSize: UInt64,+ entryCount: UInt64) {+ var off = 0+ writeU64LE(buf, &off, indexSize)+ writeU64LE(buf, &off, residentSize)+ writeU64LE(buf, &off, entryCount)+ }++ /// Write one `IndexEntry` (72 bytes, LE) at `dst`. See gturbo-format.md.+ static func writeIndexEntry(into dst: UnsafeMutableRawPointer,+ entry: ResidentEntry,+ nameOffset: UInt32) {+ var off = 0+ writeU32LE(dst, &off, nameOffset)+ writeU16LE(dst, &off, UInt16(entry.name.utf8.count))+ writeU8(dst, &off, entry.dtype)+ writeU8(dst, &off, 0) // reserved+ writeU64LE(dst, &off, entry.fileOffset)+ writeU64LE(dst, &off, entry.sizeBytes)+ writeU32LE(dst, &off, entry.logicalShape4[0])+ writeU32LE(dst, &off, entry.logicalShape4[1])+ writeU32LE(dst, &off, entry.logicalShape4[2])+ writeU32LE(dst, &off, entry.logicalShape4[3])+ writeU64LE(dst, &off, entry.scaleOffset)+ writeU64LE(dst, &off, entry.scaleSize)+ writeU64LE(dst, &off, entry.biasOffset)+ writeU64LE(dst, &off, entry.biasSize)+ precondition(off == indexEntryBytes)+ }++ @inline(__always)+ private static func writeU64LE(_ buf: UnsafeMutableRawPointer, _ off: inout Int, _ v: UInt64) {+ let p = buf.advanced(by: off).assumingMemoryBound(to: UInt8.self)+ var x = v.littleEndian+ withUnsafeBytes(of: &x) { src in+ for i in 0..<8 { p[i] = src[i] }+ }+ off += 8+ }++ @inline(__always)+ private static func writeU32LE(_ buf: UnsafeMutableRawPointer, _ off: inout Int, _ v: UInt32) {+ let p = buf.advanced(by: off).assumingMemoryBound(to: UInt8.self)+ var x = v.littleEndian+ withUnsafeBytes(of: &x) { src in+ for i in 0..<4 { p[i] = src[i] }+ }+ off += 4+ }++ @inline(__always)+ private static func writeU16LE(_ buf: UnsafeMutableRawPointer, _ off: inout Int, _ v: UInt16) {+ let p = buf.advanced(by: off).assumingMemoryBound(to: UInt8.self)+ var x = v.littleEndian+ withUnsafeBytes(of: &x) { src in+ for i in 0..<2 { p[i] = src[i] }+ }+ off += 2+ }++ @inline(__always)+ private static func writeU8(_ buf: UnsafeMutableRawPointer, _ off: inout Int, _ v: UInt8) {+ buf.advanced(by: off).assumingMemoryBound(to: UInt8.self)[0] = v+ off += 1+ }++}diff --git a/Sources/TurboFieldfareRepack/Core/Format/GTurboJSON.swift b/Sources/TurboFieldfareRepack/Core/Format/GTurboJSON.swiftnew file mode 100644index 00000000..f83acee7--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Format/GTurboJSON.swift@@ -0,0 +1,155 @@+import Foundation++/// JSON encoders for `manifest.json` and `packed_experts/layout.json`. The+/// files are small (kilobytes), so we use Foundation's `JSONSerialization`+/// rather than streaming.+enum GTurboJSON {++ static let magic = "GTURBO"+ static let versionMajor = 1+ static let versionMinor = 0++ struct FileEntry {+ let size: UInt64+ let sha256: String+ }++ struct QuantBitWidths {+ var embedding: Int+ var attention: Int+ var router: Int+ var sharedExpert: Int+ var routedExpert: Int+ }++ static func encodeManifest(plan: RepackPlan,+ modelID: String,+ sourceSnapshotHash: String,+ files: [(relativePath: String, info: FileEntry)],+ expertsPerLayer: Int,+ numLayers: Int,+ expertStride: UInt64,+ bitWidths: QuantBitWidths) throws -> Data {+ let arch = plan.arch+ let archDict: [String: Any] = [+ "hiddenSize": arch.hiddenSize,+ "ffnIntermediate": arch.intermediateSize,+ "moeIntermediateSize": arch.moeIntermediateSize,+ "numHeads": arch.numHeads,+ "numKVHeads": arch.numKVHeads,+ "numFullKVHeads": arch.numFullKVHeads,+ "headDim": arch.headDim,+ "fullHeadDim": arch.fullHeadDim,+ "vocabSize": arch.vocabSize,+ "slidingWindow": arch.slidingWindow,+ "finalLogitSoftcap": arch.finalLogitSoftcap,+ "ropeTheta": arch.ropeTheta,+ "fullRopeTheta": arch.fullRopeTheta,+ "partialRotaryFactor": arch.partialRotaryFactor,+ "numLayers": arch.numLayers,+ "numExperts": arch.numExperts,+ "topKExperts": arch.topKExperts,+ "tieWordEmbeddings": arch.tieWordEmbeddings,+ "attentionKEqV": arch.attentionKEqV,+ "hiddenActivation": arch.hiddenActivation,+ "fullAttentionLayerMask": arch.fullAttentionLayerMask.map { Int($0) }+ ]+ let quantBits = [+ "embedding": bitWidths.embedding,+ "attention": bitWidths.attention,+ "router": bitWidths.router,+ "sharedExpert": bitWidths.sharedExpert,+ "routedExpert": bitWidths.routedExpert,+ ]+ var quantDict: [String: Any] = [:]+ for (slot, bits) in quantBits {+ quantDict[slot] = [+ "weightBits": bits,+ "scheme": plan.baseMode,+ "scaleType": "BF16",+ "biasType": "BF16",+ "groupSize": plan.baseGroupSize+ ]+ }++ var filesDict: [String: Any] = [:]+ for (path, info) in files {+ filesDict[path] = ["size": info.size, "sha256": info.sha256]+ }++ let manifest: [String: Any] = [+ "magic": GTurboJSON.magic,+ "versionMajor": GTurboJSON.versionMajor,+ "versionMinor": GTurboJSON.versionMinor,+ "flags": [+ "streamingPresent": true,+ "turboQuantKV": false,+ "aneSharedExpert": false+ ],+ "modelID": modelID,+ "sourceSnapshotHash": sourceSnapshotHash,+ "arch": archDict,+ "quant": quantDict,+ "files": filesDict,+ "expertsPerLayer": expertsPerLayer,+ "numLayers": numLayers,+ "expertStride": expertStride,+ "bitWidthOverridesHonored": plan.bitsOverrideCount+ ]+ return try JSONSerialization.data(withJSONObject: manifest,+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])+ }++ static func encodeLayout(plan: RepackPlan,+ expertStride: UInt64) throws -> Data {+ let arch = plan.arch+ var layersArr: [[String: Any]] = []+ layersArr.reserveCapacity(plan.layers.count)+ for lp in plan.layers {+ let layerFile = (lp.path as NSString).lastPathComponent+ var experts: [[String: Any]] = []+ experts.reserveCapacity(lp.expertsPerLayer)+ for e in 0..<lp.expertsPerLayer {+ let base = UInt64(e) * lp.expertStride+ var tensors: [String: Any] = [:]+ for slice in lp.subTensors {+ let key: String+ switch slice.component {+ case "weights": key = slice.role+ case "scales": key = slice.role + "_scales"+ case "biases": key = slice.role + "_biases"+ default: key = slice.role + "_" + slice.component+ }+ var t: [String: Any] = [+ "offset": slice.offsetInExpertBlob,+ "size": slice.sizeInExpertBlob,+ "dtype": slice.dtype == 0 ? "U32" : "BF16",+ "shape": slice.logicalShape.map { Int($0) }+ ]+ if let bits = slice.bitsForWeights { t["bits"] = bits }+ tensors[key] = t+ }+ let expertEntry: [String: Any] = [+ "expert": e,+ "offset": base,+ "size": lp.expertStride,+ "tensors": tensors+ ]+ experts.append(expertEntry)+ }+ layersArr.append([+ "layer": lp.layerIndex,+ "file": layerFile,+ "experts": experts+ ])+ }+ let obj: [String: Any] = [+ "expertStride": expertStride,+ "numLayers": arch.numLayers,+ "expertsPerLayer": plan.layers.first?.expertsPerLayer ?? 0,+ "layers": layersArr+ ]+ return try JSONSerialization.data(withJSONObject: obj,+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Format/GTurboLayoutValidator.swift b/Sources/TurboFieldfareRepack/Core/Format/GTurboLayoutValidator.swiftnew file mode 100644index 00000000..dad58d50--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Format/GTurboLayoutValidator.swift@@ -0,0 +1,54 @@+import Foundation++enum GTurboLayoutValidator {+ static func validate(path: String, plan: RepackPlan) throws {+ let data = try Data(contentsOf: URL(fileURLWithPath: path))+ guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let layers = root["layers"] as? [[String: Any]] else {+ throw RepackError.configurationInvalid(detail: "layout.json validation failed: malformed root")+ }+ for layerObj in layers {+ guard let layerIndex = layerObj["layer"] as? Int,+ let experts = layerObj["experts"] as? [[String: Any]],+ let planLayer = plan.layers.first(where: { $0.layerIndex == layerIndex }) else {+ throw RepackError.configurationInvalid(detail: "layout.json validation failed: malformed layer")+ }+ if planLayer.expertsPerLayer == 0 { continue }+ var seenLogical = Set<Int>()+ var seenOffsets = Set<UInt64>()+ for expertObj in experts {+ guard let expert = expertObj["expert"] as? Int,+ let offset = (expertObj["offset"] as? NSNumber)?.uint64Value,+ let size = (expertObj["size"] as? NSNumber)?.uint64Value else {+ throw RepackError.configurationInvalid(detail: "layout.json validation failed: malformed expert")+ }+ guard expert >= 0 && expert < planLayer.expertsPerLayer else {+ throw RepackError.configurationInvalid(detail: "layout.json validation failed: expert out of range")+ }+ guard seenLogical.insert(expert).inserted else {+ throw RepackError.configurationInvalid(detail: "layout.json validation failed: duplicate expert \(expert)")+ }+ guard seenOffsets.insert(offset).inserted else {+ throw RepackError.configurationInvalid(detail: "layout.json validation failed: duplicate offset \(offset)")+ }+ guard offset % Layout.pageBytes == 0 else {+ throw RepackError.configurationInvalid(detail: "layout.json validation failed: unaligned offset \(offset)")+ }+ let expected = UInt64(expert) * planLayer.expertStride+ guard offset == expected else {+ throw RepackError.configurationInvalid(detail:+ "layout.json validation failed: offset \(offset) != expert * stride \(expected)")+ }+ guard size == planLayer.expertStride,+ offset + size <= planLayer.fileSize else {+ throw RepackError.configurationInvalid(detail:+ "layout.json validation failed: expert range outside layer file")+ }+ }+ guard seenLogical.count == planLayer.expertsPerLayer else {+ throw RepackError.configurationInvalid(detail:+ "layout.json validation failed: missing experts in layer \(layerIndex)")+ }+ }+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Format/IndexLoader.swift b/Sources/TurboFieldfareRepack/Core/Format/IndexLoader.swiftnew file mode 100644index 00000000..894363bb--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Format/IndexLoader.swift@@ -0,0 +1,101 @@+import Foundation++/// Parses `model.safetensors.index.json` and `config.json -> quantization`.+enum IndexLoader {++ struct SourceMetadata {+ let indexPath: String+ let configPath: String+ let indexSha256Hex: String+ /// `tensor_name -> shard_filename`+ let weightMap: [String: String]+ /// Base bits / group_size / mode for any tensor not in the override table.+ let baseBits: Int+ let baseGroupSize: Int+ let baseMode: String+ /// Per-tensor overrides (keyed by tensor name **without** the trailing+ /// `.weight` — matches the way `config.json` writes them).+ let bitsOverrides: [String: QuantSpec]+ /// Resolved set of shard files referenced by the index, in+ /// encounter order. Order is stable enough for sequential I/O.+ let shardFilenames: [String]+ }++ static func load(snapshotDir: String) throws -> SourceMetadata {+ let indexPath = (snapshotDir as NSString).appendingPathComponent("model.safetensors.index.json")+ let configPath = (snapshotDir as NSString).appendingPathComponent("config.json")++ let weightMap: [String: String]+ do {+ let data = try Data(contentsOf: URL(fileURLWithPath: indexPath))+ guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let m = root["weight_map"] as? [String: String] else {+ throw RepackError.indexJsonInvalid(path: indexPath, detail: "no weight_map")+ }+ weightMap = m+ } catch let e as RepackError {+ throw e+ } catch {+ throw RepackError.indexJsonInvalid(path: indexPath, detail: "\(error)")+ }++ let indexSha = try Sha256Stream.hashFile(path: indexPath)++ var baseBits = 4+ var baseGroup = 64+ var baseMode = "affine"+ var overrides: [String: QuantSpec] = [:]+ do {+ let data = try Data(contentsOf: URL(fileURLWithPath: configPath))+ guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ throw RepackError.configJsonInvalid(path: configPath, detail: "not a JSON object")+ }+ guard let quant = root["quantization"] as? [String: Any] else {+ throw RepackError.configJsonInvalid(path: configPath, detail: "no quantization slot")+ }+ if let b = quant["bits"] as? Int { baseBits = b }+ if let g = quant["group_size"] as? Int { baseGroup = g }+ if let m = quant["mode"] as? String { baseMode = m }+ for (k, v) in quant where !(k == "bits" || k == "group_size" || k == "mode") {+ guard let entry = v as? [String: Any] else { continue }+ let bits = (entry["bits"] as? Int) ?? baseBits+ let g = (entry["group_size"] as? Int) ?? baseGroup+ guard g == baseGroup else {+ throw RepackError.configJsonInvalid(+ path: configPath,+ detail: "quantization override \(k) group_size \(g) != base \(baseGroup)")+ }+ overrides[k] = QuantSpec(bits: bits)+ }+ } catch let e as RepackError {+ throw e+ } catch {+ throw RepackError.configJsonInvalid(path: configPath, detail: "\(error)")+ }++ var seen = Set<String>()+ var shards: [String] = []+ for k in weightMap.keys.sorted() {+ let shard = weightMap[k]!+ if !seen.contains(shard) { seen.insert(shard); shards.append(shard) }+ }++ return SourceMetadata(indexPath: indexPath, configPath: configPath,+ indexSha256Hex: indexSha,+ weightMap: weightMap,+ baseBits: baseBits, baseGroupSize: baseGroup,+ baseMode: baseMode,+ bitsOverrides: overrides,+ shardFilenames: shards)+ }++ /// Resolves the bits/group for one tensor name (with or without `.weight`).+ static func quantSpec(forTensor name: String,+ meta: SourceMetadata) -> QuantSpec {+ let stripped = name.hasSuffix(".weight")+ ? String(name.dropLast(".weight".count))+ : name+ if let o = meta.bitsOverrides[stripped] { return o }+ return QuantSpec(bits: meta.baseBits)+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Format/Safetensors.swift b/Sources/TurboFieldfareRepack/Core/Format/Safetensors.swiftnew file mode 100644index 00000000..9a0ff26f--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Format/Safetensors.swift@@ -0,0 +1,82 @@+import Foundation++/// Parses bounded safetensors header bytes fetched by the remote installer.+/// Tensor payload coordinates remain absolute source-file offsets so later+/// range requests can copy only the required tiles.+enum Safetensors {+ static let maxHeaderBytes: UInt64 = 1 << 24 // 16 MB — generous; observed ~95 KB++ struct Header {+ let tensors: [SourceTensor]+ }++ static func parseHeaderBytes(path: String,+ fileSize: UInt64,+ headerBytes data: Data) throws -> Header {+ let headerSize = UInt64(data.count)+ if headerSize > maxHeaderBytes || headerSize > fileSize - 8 {+ throw RepackError.safetensorsHeaderTooLarge(path: path, size: headerSize)+ }+ let rawObj = try JSONSerialization.jsonObject(with: data, options: [])+ guard let dict = rawObj as? [String: Any] else {+ throw RepackError.safetensorsHeaderInvalid(path: path, detail: "header is not a JSON object")+ }++ let payloadBase = UInt64(8) + headerSize+ var tensors: [SourceTensor] = []+ tensors.reserveCapacity(dict.count)+ for (name, value) in dict {+ if name == "__metadata__" { continue }+ guard let entry = value as? [String: Any] else {+ throw RepackError.safetensorsHeaderInvalid(path: path,+ detail: "entry for \(name) is not a dict")+ }+ guard let dtypeStr = entry["dtype"] as? String else {+ throw RepackError.safetensorsHeaderInvalid(path: path,+ detail: "entry for \(name) has no dtype")+ }+ let dtype: SourceTensor.Dtype+ switch dtypeStr {+ case "U32": dtype = .u32+ case "BF16": dtype = .bf16+ case "F16": dtype = .fp16+ case "F32": dtype = .fp32+ default: throw RepackError.safetensorsUnknownDtype(path: path, dtype: dtypeStr)+ }+ guard let shape = entry["shape"] as? [Any] else {+ throw RepackError.safetensorsHeaderInvalid(path: path,+ detail: "entry for \(name) has no shape")+ }+ let shapeU64: [UInt64] = try shape.map { e in+ if let n = e as? NSNumber { return n.uint64Value }+ if let n = e as? Int { return UInt64(n) }+ throw RepackError.safetensorsHeaderInvalid(path: path,+ detail: "entry for \(name) has non-integer shape entry")+ }+ guard let offs = entry["data_offsets"] as? [Any], offs.count == 2,+ let begin = (offs[0] as? NSNumber)?.uint64Value ?? (offs[0] as? Int).map({ UInt64($0) }),+ let end = (offs[1] as? NSNumber)?.uint64Value ?? (offs[1] as? Int).map({ UInt64($0) })+ else {+ throw RepackError.safetensorsHeaderInvalid(path: path,+ detail: "entry for \(name) has bad data_offsets")+ }+ let abs = payloadBase + begin+ let size = end - begin+ let endAbs = abs + size+ if endAbs > fileSize {+ throw RepackError.safetensorsTensorOutOfRange(path: path, name: name,+ end: endAbs, fileSize: fileSize)+ }+ let elemBytes = UInt64(dtype.elementBytes)+ let elements = shapeU64.reduce(UInt64(1), *)+ if elements * elemBytes != size {+ throw RepackError.shapeMismatch(name: name,+ detail: "shape product \(elements)*\(elemBytes) != size \(size)")+ }+ tensors.append(SourceTensor(name: name, shardPath: path, dtype: dtype,+ shape: shapeU64,+ absoluteOffset: abs, sizeBytes: size))+ }+ return Header(tensors: tensors)+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Format/TensorMetadata.swift b/Sources/TurboFieldfareRepack/Core/Format/TensorMetadata.swiftnew file mode 100644index 00000000..b642c8b5--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Format/TensorMetadata.swift@@ -0,0 +1,29 @@+import Foundation++/// One physical tensor in a safetensors shard. Coordinates are absolute file+/// offsets so the writer can map and copy a single tensor without re-parsing+/// the shard header.+struct SourceTensor: Sendable, Hashable {+ enum Dtype: UInt8, Sendable, Hashable {+ case u32 = 0+ case bf16 = 1+ case fp16 = 2+ case fp32 = 3++ var elementBytes: Int {+ switch self { case .u32: 4; case .bf16: 2; case .fp16: 2; case .fp32: 4 }+ }+ }++ let name: String+ let shardPath: String+ let dtype: Dtype+ let shape: [UInt64]+ let absoluteOffset: UInt64+ let sizeBytes: UInt64+}++/// Bit-width override resolved from `config.json -> quantization`.+struct QuantSpec: Sendable, Hashable {+ let bits: Int+}diff --git a/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift b/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swiftnew file mode 100644index 00000000..65db0fde--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift@@ -0,0 +1,158 @@+import Foundation++struct RangeCopy: Sendable, Equatable {+ let shardID: String+ let sourceOffset: UInt64+ let size: UInt64+ let destinationPath: String+ let destinationOffset: UInt64++ init(shardID: String,+ sourceOffset: UInt64,+ size: UInt64,+ destinationPath: String,+ destinationOffset: UInt64) {+ self.shardID = shardID+ self.sourceOffset = sourceOffset+ self.size = size+ self.destinationPath = destinationPath+ self.destinationOffset = destinationOffset+ }+}++struct CoalescedRangeCopy: Sendable, Equatable {+ let shardID: String+ let sourceOffset: UInt64+ let size: UInt64+ let destinations: [RangeCopy]+}++struct RangeCopyPlan: Sendable {+ let coalescedCopies: [CoalescedRangeCopy]+ let remoteBytesToDownload: UInt64+}++enum RangeCopyPlanner {+ static func plan(repackPlan: RepackPlan,+ rangeChunkBytes: Int) throws -> RangeCopyPlan {+ var copies: [RangeCopy] = []+ copies.reserveCapacity(repackPlan.resident.entries.count * 3)++ for entry in repackPlan.resident.entries {+ copies.append(RangeCopy(shardID: entry.sourceWeight.shardPath,+ sourceOffset: entry.sourceWeight.absoluteOffset,+ size: entry.sizeBytes,+ destinationPath: repackPlan.resident.path,+ destinationOffset: entry.fileOffset))+ if let scales = entry.sourceScales {+ copies.append(RangeCopy(shardID: scales.shardPath,+ sourceOffset: scales.absoluteOffset,+ size: entry.scaleSize,+ destinationPath: repackPlan.resident.path,+ destinationOffset: entry.scaleOffset))+ }+ if let biases = entry.sourceBiases {+ copies.append(RangeCopy(shardID: biases.shardPath,+ sourceOffset: biases.absoluteOffset,+ size: entry.biasSize,+ destinationPath: repackPlan.resident.path,+ destinationOffset: entry.biasOffset))+ }+ }++ for layer in repackPlan.layers where layer.expertsPerLayer > 0 {+ for expert in 0..<layer.expertsPerLayer {+ let blobBase = UInt64(expert) * layer.expertStride+ for slice in layer.subTensors {+ copies.append(RangeCopy(+ shardID: slice.sourceTensor.shardPath,+ sourceOffset: slice.sourceTensor.absoluteOffset+ + UInt64(expert) * slice.sourceOffsetPerExpert,+ size: slice.sizeInExpertBlob,+ destinationPath: layer.path,+ destinationOffset: blobBase + slice.offsetInExpertBlob))+ }+ }+ }++ let coalesced = try coalesce(copies: copies, rangeChunkBytes: rangeChunkBytes)+ let downloaded = coalesced.reduce(UInt64(0)) { $0 + $1.size }+ return RangeCopyPlan(coalescedCopies: coalesced,+ remoteBytesToDownload: downloaded)+ }++ static func coalesce(copies: [RangeCopy],+ rangeChunkBytes: Int) throws -> [CoalescedRangeCopy] {+ guard rangeChunkBytes > 0 else {+ throw RepackError.configurationInvalid(detail: "rangeChunkBytes must be positive")+ }+ let sorted = splitLargeCopies(copies, rangeChunkBytes: rangeChunkBytes).sorted {+ if $0.shardID != $1.shardID { return $0.shardID < $1.shardID }+ return $0.sourceOffset < $1.sourceOffset+ }+ var out: [CoalescedRangeCopy] = []+ var currentShard: String?+ var currentStart: UInt64 = 0+ var currentEnd: UInt64 = 0+ var currentDestinations: [RangeCopy] = []++ func flush() {+ guard let shard = currentShard else { return }+ out.append(CoalescedRangeCopy(shardID: shard,+ sourceOffset: currentStart,+ size: currentEnd - currentStart,+ destinations: currentDestinations))+ }++ for copy in sorted where copy.size > 0 {+ let copyEnd = copy.sourceOffset + copy.size+ if currentShard == nil {+ currentShard = copy.shardID+ currentStart = copy.sourceOffset+ currentEnd = copyEnd+ currentDestinations = [copy]+ continue+ }+ let proposedStart = currentStart+ let proposedEnd = max(currentEnd, copyEnd)+ let canMerge = currentShard == copy.shardID+ && proposedEnd >= proposedStart+ && proposedEnd - proposedStart <= UInt64(rangeChunkBytes)+ if canMerge {+ currentEnd = proposedEnd+ currentDestinations.append(copy)+ } else {+ flush()+ currentShard = copy.shardID+ currentStart = copy.sourceOffset+ currentEnd = copyEnd+ currentDestinations = [copy]+ }+ }+ flush()+ return out+ }++ private static func splitLargeCopies(_ copies: [RangeCopy],+ rangeChunkBytes: Int) -> [RangeCopy] {+ let limit = UInt64(rangeChunkBytes)+ var out: [RangeCopy] = []+ for copy in copies {+ var remaining = copy.size+ var src = copy.sourceOffset+ var dst = copy.destinationOffset+ while remaining > 0 {+ let n = min(remaining, limit)+ out.append(RangeCopy(shardID: copy.shardID,+ sourceOffset: src,+ size: n,+ destinationPath: copy.destinationPath,+ destinationOffset: dst))+ remaining -= n+ src += n+ dst += n+ }+ }+ return out+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift b/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swiftnew file mode 100644index 00000000..41aa86ac--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift@@ -0,0 +1,469 @@+import Foundation++/// On-disk page alignment unit for `.gturbo` files. Fixed at 16 KB regardless+/// of host page size — the format is the contract, not the kernel.+enum Layout {+ static let pageBytes: UInt64 = 16_384+}++// MARK: - Plan data types++struct ResidentEntry: Sendable {+ let name: String+ /// dtype byte for IndexEntry: 0 = U32, 1 = BF16, 2 = FP16, 3 = FP32.+ let dtype: UInt8+ /// Logical shape after dequant (max rank 4; trailing zeros).+ let logicalShape4: [UInt32]+ /// File offset where the (packed) weight bytes start.+ let fileOffset: UInt64+ /// Size in bytes of the weight bytes.+ let sizeBytes: UInt64+ /// Offset where BF16 scales start (0 if none).+ let scaleOffset: UInt64+ let scaleSize: UInt64+ /// Offset where BF16 biases start (0 if none).+ let biasOffset: UInt64+ let biasSize: UInt64+ /// Quantization spec (nil for unquantized scalars/norms).+ let quantSpec: QuantSpec?++ /// Source tensors that supply this entry's bytes.+ let sourceWeight: SourceTensor+ let sourceScales: SourceTensor?+ let sourceBiases: SourceTensor?+}++struct ResidentFilePlan: Sendable {+ let path: String+ let entries: [ResidentEntry]+ let stringTable: [UInt8]+ let stringTableOffsets: [UInt32] // per-entry offsets into the table+ let indexSize: UInt64 // header + entries + table + padding+ let residentSize: UInt64 // tensor payload region+ var totalSize: UInt64 { indexSize + residentSize }+}++struct PerExpertTensorSlice: Sendable {+ let role: String // "gate" | "up" | "down"+ let component: String // "weights" | "scales" | "biases"+ let dtype: UInt8 // 0=U32, 1=BF16+ let logicalShape: [UInt64] // per-expert logical shape+ let offsetInExpertBlob: UInt64 // within each expert blob+ let sizeInExpertBlob: UInt64+ /// For each expert e (0..<expertsPerLayer): source byte offset & size.+ let sourceOffsetPerExpert: UInt64 // stride per expert in source+ let sourceTensor: SourceTensor+ let bitsForWeights: Int? // 4 for routed expert weight; nil for scales/biases+}++struct LayerFilePlan: Sendable {+ let layerIndex: Int+ let path: String+ let expertsPerLayer: Int+ let expertStride: UInt64+ let subTensors: [PerExpertTensorSlice] // 9 entries: gate/up/down × {weights, scales, biases}+ var fileSize: UInt64 { UInt64(expertsPerLayer) * expertStride }++ init(layerIndex: Int,+ path: String,+ expertsPerLayer: Int,+ expertStride: UInt64,+ subTensors: [PerExpertTensorSlice]) {+ self.layerIndex = layerIndex+ self.path = path+ self.expertsPerLayer = expertsPerLayer+ self.expertStride = expertStride+ self.subTensors = subTensors+ }+}++struct RepackPlan: Sendable {+ let arch: ArchInfo+ let baseMode: String // "affine"+ let baseGroupSize: Int // 64+ let bitsOverrideCount: Int+ let resident: ResidentFilePlan+ let layers: [LayerFilePlan]+ let matchedModelID: String?+}++// MARK: - Planner++enum RepackPlanner {++ /// Classify a tensor name. Routed-expert tensors split off the LM bucket.+ enum Bucket: Equatable {+ case lmResident+ case routedExpert(role: String, layer: Int) // role = "gate"|"up"|"down"+ case excludedMultimodal+ case unknown+ }++ static func classify(_ name: String, numLayers: Int) -> Bucket {+ if name.hasPrefix("language_model.") {+ // Routed expert?+ if let role = routedExpertRole(in: name),+ let layer = layerIndex(in: name),+ layer >= 0 && layer < numLayers {+ return .routedExpert(role: role, layer: layer)+ }+ return .lmResident+ }+ if isMultimodalTensorName(name) {+ return .excludedMultimodal+ }+ return .unknown+ }++ private static func routedExpertRole(in name: String) -> String? {+ guard name.contains(".experts.switch_glu.") else { return nil }+ if name.contains(".gate_proj.") { return "gate" }+ if name.contains(".up_proj.") { return "up" }+ if name.contains(".down_proj.") { return "down" }+ return nil+ }++ private static func layerIndex(in name: String) -> Int? {+ // matches "...layers.<N>...."+ guard let r = name.range(of: ".layers.") else { return nil }+ let tail = name[r.upperBound...]+ guard let dot = tail.firstIndex(of: ".") else { return nil }+ return Int(tail[tail.startIndex..<dot])+ }++ /// Build the plan from parsed shard headers + source metadata.+ /// - throws: classification + companion + override count failures.+ static func plan(meta: IndexLoader.SourceMetadata,+ arch: ArchInfo,+ shardHeaders: [Safetensors.Header],+ outputDir: String) throws -> RepackPlan {++ // Companion tensors may live in different shards, so resolve them+ // through one global registry.+ var registry: [String: SourceTensor] = [:]+ registry.reserveCapacity(meta.weightMap.count)+ for h in shardHeaders {+ for t in h.tensors { registry[t.name] = t }+ }++ // Source allowlisting owns exact fingerprint validation. Preserve the+ // declared override count for the output manifest audit.+ let bitsOverrideCount = meta.bitsOverrides.count++ var lmResidentBases: [String] = []+ var routedByLayerAndRole: [Int: [String: String]] = [:]+ for (name, _) in registry {+ if name.hasSuffix(".scales") || name.hasSuffix(".biases") { continue }+ let b = classify(name, numLayers: arch.numLayers)+ switch b {+ case .lmResident: lmResidentBases.append(name)+ case .routedExpert(let role, let layer):+ var byRole = routedByLayerAndRole[layer] ?? [:]+ if byRole[role] != nil {+ throw RepackError.configurationInvalid(detail:+ "two routed-expert tensors for layer \(layer) role \(role)")+ }+ byRole[role] = name+ routedByLayerAndRole[layer] = byRole+ case .excludedMultimodal: continue+ case .unknown: throw RepackError.unknownTensorPrefix(name: name)+ }+ }++ // Sort deterministically. The LM order follows a fixed template.+ lmResidentBases.sort(by: lmResidentOrdering())++ let residentPath = (outputDir as NSString).appendingPathComponent("model_weights.bin")+ let resident = try planResidentFile(path: residentPath,+ baseNames: lmResidentBases,+ registry: registry, meta: meta)++ let layersDir = (outputDir as NSString).appendingPathComponent("packed_experts")+ var layerPlans: [LayerFilePlan] = []+ layerPlans.reserveCapacity(arch.numLayers)+ for layer in 0..<arch.numLayers {+ let bundle = routedByLayerAndRole[layer] ?? [:]+ // Synthetic snapshots may legitimately have no routed experts.+ guard let gName = bundle["gate"], let uName = bundle["up"], let dName = bundle["down"] else {+ if bundle.isEmpty {+ layerPlans.append(LayerFilePlan(layerIndex: layer,+ path: (layersDir as NSString).appendingPathComponent("layer_\(String(format: "%02d", layer)).bin"),+ expertsPerLayer: 0,+ expertStride: 0,+ subTensors: []))+ continue+ }+ throw RepackError.configurationInvalid(detail:+ "layer \(layer) routed-expert bundle incomplete: \(bundle)")+ }+ let path = (layersDir as NSString)+ .appendingPathComponent("layer_\(String(format: "%02d", layer)).bin")+ let lp = try planLayerFile(path: path, layer: layer,+ gateName: gName, upName: uName, downName: dName,+ registry: registry, meta: meta, arch: arch)+ layerPlans.append(lp)+ }++ let matched = SourceFingerprint.modelID(forIndexSha256: meta.indexSha256Hex)++ return RepackPlan(arch: arch,+ baseMode: meta.baseMode,+ baseGroupSize: meta.baseGroupSize,+ bitsOverrideCount: bitsOverrideCount,+ resident: resident,+ layers: layerPlans,+ matchedModelID: matched)+ }++ private static func isMultimodalTensorName(_ name: String) -> Bool {+ name.hasPrefix("vision_tower.") ||+ name.hasPrefix("embed_vision.") ||+ name.hasPrefix("audio_tower.")+ }++ // MARK: - Resident planning++ private static func planResidentFile(path: String,+ baseNames: [String],+ registry: [String: SourceTensor],+ meta: IndexLoader.SourceMetadata) throws+ -> ResidentFilePlan {+ let entryCount = baseNames.count++ var stringTable: [UInt8] = []+ var offsets: [UInt32] = []+ offsets.reserveCapacity(entryCount)+ for n in baseNames {+ offsets.append(UInt32(stringTable.count))+ stringTable.append(contentsOf: n.utf8)+ }++ // Index size includes the fixed header, fixed-width entries, and the+ // string table, padded to a 16 KB page boundary.+ let rawIdx = UInt64(GTurboBinary.indexHeaderBytes+ + entryCount * GTurboBinary.indexEntryBytes+ + stringTable.count)+ let indexSize = roundUpToPage(rawIdx)++ var fileCursor = indexSize+ var entries: [ResidentEntry] = []+ entries.reserveCapacity(entryCount)++ for name in baseNames {+ guard let weight = registry[name] else {+ throw RepackError.missingTensor(name: name)+ }+ let dtype = ietnyDtype(weight.dtype)+ let isQuantizedPacked = (weight.dtype == .u32) && name.hasSuffix(".weight")++ if isQuantizedPacked {+ let base = String(name.dropLast(".weight".count))+ guard let scales = registry[base + ".scales"] else {+ throw RepackError.missingScalesCompanion(name: name)+ }+ guard let biases = registry[base + ".biases"] else {+ throw RepackError.missingBiasesCompanion(name: name)+ }+ if scales.dtype != .bf16 || biases.dtype != .bf16 {+ throw RepackError.dtypeMismatch(name: name,+ detail: "expected BF16 scales/biases, got \(scales.dtype)/\(biases.dtype)")+ }+ let spec = IndexLoader.quantSpec(forTensor: name, meta: meta)+ let logical = logicalShape(forPackedSource: weight.shape, bits: spec.bits)++ let wOff = fileCursor+ let wSize = weight.sizeBytes+ let sOff = wOff + wSize+ let sSize = scales.sizeBytes+ let bOff = sOff + sSize+ let bSize = biases.sizeBytes+ fileCursor = bOff + bSize++ entries.append(ResidentEntry(+ name: name, dtype: 0,+ logicalShape4: padTo4(logical),+ fileOffset: wOff, sizeBytes: wSize,+ scaleOffset: sOff, scaleSize: sSize,+ biasOffset: bOff, biasSize: bSize,+ quantSpec: spec,+ sourceWeight: weight, sourceScales: scales, sourceBiases: biases))+ } else {+ // Unquantized (BF16 norm / scalar) — no companions.+ let off = fileCursor+ let size = weight.sizeBytes+ fileCursor = off + size++ entries.append(ResidentEntry(+ name: name, dtype: dtype,+ logicalShape4: padTo4(weight.shape),+ fileOffset: off, sizeBytes: size,+ scaleOffset: 0, scaleSize: 0,+ biasOffset: 0, biasSize: 0,+ quantSpec: nil,+ sourceWeight: weight, sourceScales: nil, sourceBiases: nil))+ }+ }++ let residentSize = fileCursor - indexSize++ return ResidentFilePlan(path: path,+ entries: entries,+ stringTable: stringTable,+ stringTableOffsets: offsets,+ indexSize: indexSize,+ residentSize: residentSize)+ }++ // MARK: - Layer planning++ private static func planLayerFile(path: String, layer: Int,+ gateName: String, upName: String, downName: String,+ registry: [String: SourceTensor],+ meta: IndexLoader.SourceMetadata,+ arch: ArchInfo) throws -> LayerFilePlan {+ let expertCount = arch.numExperts+ let roles: [(role: String, name: String)] = [+ ("gate", gateName), ("up", upName), ("down", downName)+ ]+ var subs: [PerExpertTensorSlice] = []+ subs.reserveCapacity(9)+ var blobCursor: UInt64 = 0++ for (role, name) in roles {+ guard let w = registry[name] else { throw RepackError.missingTensor(name: name) }+ if w.dtype != .u32 || w.shape.count != 3 || Int(w.shape[0]) != expertCount {+ throw RepackError.shapeMismatch(name: name,+ detail: "expected U32 rank-3 with leading \(expertCount), got \(w.dtype) \(w.shape)")+ }+ let base = name.hasSuffix(".weight") ? String(name.dropLast(".weight".count)) : name+ guard let s = registry[base + ".scales"] else { throw RepackError.missingScalesCompanion(name: name) }+ guard let b = registry[base + ".biases"] else { throw RepackError.missingBiasesCompanion(name: name) }+ if s.dtype != .bf16 || b.dtype != .bf16 {+ throw RepackError.dtypeMismatch(name: name,+ detail: "expected BF16 scales/biases, got \(s.dtype)/\(b.dtype)")+ }++ let perExpertWeightSize = w.sizeBytes / UInt64(expertCount)+ let perExpertScaleSize = s.sizeBytes / UInt64(expertCount)+ let perExpertBiasSize = b.sizeBytes / UInt64(expertCount)+ if perExpertWeightSize * UInt64(expertCount) != w.sizeBytes ||+ perExpertScaleSize * UInt64(expertCount) != s.sizeBytes ||+ perExpertBiasSize * UInt64(expertCount) != b.sizeBytes {+ throw RepackError.shapeMismatch(name: name,+ detail: "source bytes not evenly divisible by \(expertCount) experts")+ }++ let spec = IndexLoader.quantSpec(forTensor: name, meta: meta)+ let perExpertSourceShape = Array(w.shape.dropFirst())+ let logicalPerExpert = logicalShape(forPackedSource: perExpertSourceShape, bits: spec.bits)+ let scalesLogical = Array(s.shape.dropFirst())+ let biasesLogical = Array(b.shape.dropFirst())++ let wSlice = PerExpertTensorSlice(+ role: role, component: "weights", dtype: 0,+ logicalShape: logicalPerExpert,+ offsetInExpertBlob: blobCursor, sizeInExpertBlob: perExpertWeightSize,+ sourceOffsetPerExpert: perExpertWeightSize, sourceTensor: w,+ bitsForWeights: spec.bits)+ blobCursor += perExpertWeightSize+ let sSlice = PerExpertTensorSlice(+ role: role, component: "scales", dtype: 1,+ logicalShape: scalesLogical,+ offsetInExpertBlob: blobCursor, sizeInExpertBlob: perExpertScaleSize,+ sourceOffsetPerExpert: perExpertScaleSize, sourceTensor: s,+ bitsForWeights: nil)+ blobCursor += perExpertScaleSize+ let bSlice = PerExpertTensorSlice(+ role: role, component: "biases", dtype: 1,+ logicalShape: biasesLogical,+ offsetInExpertBlob: blobCursor, sizeInExpertBlob: perExpertBiasSize,+ sourceOffsetPerExpert: perExpertBiasSize, sourceTensor: b,+ bitsForWeights: nil)+ blobCursor += perExpertBiasSize++ subs.append(wSlice); subs.append(sSlice); subs.append(bSlice)+ }++ let expertStride = roundUpToPage(blobCursor)+ return LayerFilePlan(layerIndex: layer, path: path,+ expertsPerLayer: expertCount,+ expertStride: expertStride,+ subTensors: subs)+ }++ // MARK: - Helpers++ private static func ietnyDtype(_ d: SourceTensor.Dtype) -> UInt8 {+ switch d { case .u32: 0; case .bf16: 1; case .fp16: 2; case .fp32: 3 }+ }++ private static func roundUpToPage(_ v: UInt64) -> UInt64 {+ let p = Layout.pageBytes+ return ((v + p - 1) / p) * p+ }++ private static func padTo4(_ s: [UInt64]) -> [UInt32] {+ var out: [UInt32] = []+ out.reserveCapacity(4)+ for v in s.prefix(4) { out.append(UInt32(v)) }+ while out.count < 4 { out.append(0) }+ return out+ }++ /// Logical shape of a packed quantized tensor whose source is `[D0,..,Dn-1, Dn/factor]`.+ private static func logicalShape(forPackedSource source: [UInt64], bits: Int) -> [UInt64] {+ let factor = UInt64(32 / bits)+ guard !source.isEmpty else { return source }+ var out = source+ out[out.count - 1] = source[source.count - 1] * factor+ return out+ }++ /// Stable order for the resident LM tensor list. Embedding first, then+ /// per-layer groups in layer index order, then the final norm.+ private static func lmResidentOrdering() -> (String, String) -> Bool {+ // Compute a sort key per name; we order by (group rank, layer, slot rank, name).+ func key(_ n: String) -> (Int, Int, Int, String) {+ if n == "language_model.model.embed_tokens.weight" { return (0, 0, 0, n) }+ if n == "language_model.model.norm.weight" { return (3, 0, 0, n) }+ if let li = layerIndex(in: n) {+ let slot = slotRank(in: n)+ return (1, li, slot, n)+ }+ return (2, 0, 0, n)+ }+ return { a, b in+ let ka = key(a), kb = key(b)+ if ka.0 != kb.0 { return ka.0 < kb.0 }+ if ka.1 != kb.1 { return ka.1 < kb.1 }+ if ka.2 != kb.2 { return ka.2 < kb.2 }+ return ka.3 < kb.3+ }+ }++ /// Within-layer slot order. Mirrors the per-layer description in the+ /// architecture doc.+ private static func slotRank(in n: String) -> Int {+ if n.contains(".self_attn.q_proj.weight") { return 0 }+ if n.contains(".self_attn.k_proj.weight") { return 1 }+ if n.contains(".self_attn.v_proj.weight") { return 2 }+ if n.contains(".self_attn.o_proj.weight") { return 3 }+ if n.contains(".self_attn.q_norm.weight") { return 4 }+ if n.contains(".self_attn.k_norm.weight") { return 5 }+ if n.contains(".router.proj.weight") { return 6 }+ if n.contains(".router.scale") { return 7 }+ if n.contains(".router.per_expert_scale") { return 8 }+ if n.contains(".mlp.gate_proj.weight") { return 9 }+ if n.contains(".mlp.up_proj.weight") { return 10 }+ if n.contains(".mlp.down_proj.weight") { return 11 }+ if n.hasSuffix(".input_layernorm.weight") { return 12 }+ if n.hasSuffix(".post_attention_layernorm.weight") { return 13 }+ if n.hasSuffix(".pre_feedforward_layernorm.weight") { return 14 }+ if n.hasSuffix(".pre_feedforward_layernorm_2.weight") { return 15 }+ if n.hasSuffix(".post_feedforward_layernorm.weight") { return 16 }+ if n.hasSuffix(".post_feedforward_layernorm_1.weight") { return 17 }+ if n.hasSuffix(".post_feedforward_layernorm_2.weight") { return 18 }+ if n.hasSuffix(".layer_scalar") { return 19 }+ return 100+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/HuggingFaceRemote.swift b/Sources/TurboFieldfareRepack/Core/Remote/HuggingFaceRemote.swiftnew file mode 100644index 00000000..ef59cb3f--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/HuggingFaceRemote.swift@@ -0,0 +1,283 @@+import Foundation++public struct RemoteFileInfo: Sendable, Hashable {+ public let filename: String+ public let resolvedCommit: String+ public let size: UInt64+ public let acceptsRanges: Bool+}++public struct TemporaryRangeFile: Sendable {+ public let path: String+ public let byteCount: UInt64+}++public struct HuggingFaceRemoteSource: Sendable {+ public let repoID: String+ public let requestedRevision: String+ public let resolvedCommit: String?+ public let token: String?+ public let session: URLSession+ public let baseURL: URL+ public let tempDirectory: String+ public let retryPolicy: RemoteRetryPolicy++ public init(repoID: String,+ requestedRevision: String,+ resolvedCommit: String? = nil,+ token: String? = nil,+ session: URLSession = .shared,+ baseURL: URL = URL(string: "https://huggingface.co")!,+ tempDirectory: String = NSTemporaryDirectory(),+ retryPolicy: RemoteRetryPolicy = RemoteRetryPolicy()) {+ self.repoID = repoID+ self.requestedRevision = requestedRevision+ self.resolvedCommit = resolvedCommit+ self.token = token+ self.session = session+ self.baseURL = baseURL+ self.tempDirectory = tempDirectory+ self.retryPolicy = retryPolicy+ }++ public func pinned(commit: String) -> HuggingFaceRemoteSource {+ HuggingFaceRemoteSource(repoID: repoID,+ requestedRevision: requestedRevision,+ resolvedCommit: commit,+ token: token,+ session: session,+ baseURL: baseURL,+ tempDirectory: tempDirectory,+ retryPolicy: retryPolicy)+ }++ public func fileURL(filename: String) throws -> URL {+ try validateRepoID(repoID)+ try validateFilename(filename)+ let revision = resolvedCommit ?? requestedRevision+ var url = baseURL+ for part in repoID.split(separator: "/") {+ url.appendPathComponent(String(part))+ }+ url.appendPathComponent("resolve")+ url.appendPathComponent(revision)+ for part in filename.split(separator: "/") {+ url.appendPathComponent(String(part))+ }+ return url+ }++ public func resolveFileInfo(filename: String,+ audit: RepackAudit? = nil) async throws -> RemoteFileInfo {+ try await withRemoteRetries(retryPolicy,+ audit: audit) {+ try await resolveFileInfoOnce(filename: filename)+ }+ }++ private func resolveFileInfoOnce(filename: String) async throws -> RemoteFileInfo {+ let url = try fileURL(filename: filename)+ var request = URLRequest(url: url)+ request.httpMethod = "HEAD"+ applyHeaders(to: &request)+ let (_, response) = try await session.data(for: request)+ guard let http = response as? HTTPURLResponse else {+ throw RepackError.remoteProtocolInvalid(detail: "missing HTTP response for \(filename)")+ }+ guard (200..<400).contains(http.statusCode) else {+ throw RepackError.remoteHTTPStatus(url: redact(url), status: http.statusCode)+ }+ let commit = header(http, "X-Repo-Commit") ?? resolvedCommit+ guard let commit, commit.count == 40 else {+ throw RepackError.remoteProtocolInvalid(detail: "missing full X-Repo-Commit for \(filename)")+ }+ let size = try remoteSize(http: http, filename: filename)+ return RemoteFileInfo(filename: filename,+ resolvedCommit: commit,+ size: size,+ acceptsRanges: (header(http, "Accept-Ranges") ?? "").lowercased().contains("bytes"))+ }++ public func fetchSmallFile(filename: String,+ info: RemoteFileInfo,+ capBytes: UInt64,+ outputPath: String,+ audit: RepackAudit? = nil) async throws {+ guard info.size <= capBytes else {+ throw RepackError.remoteFileTooLarge(path: filename, size: info.size, cap: capBytes)+ }+ try await withRemoteRetries(retryPolicy,+ audit: audit) {+ let tmp = try await downloadRangeToTempFileOnce(filename: filename,+ info: info,+ offset: 0,+ length: Int(info.size))+ do {+ try Posix.mkdirP((outputPath as NSString).deletingLastPathComponent)+ if FileManager.default.fileExists(atPath: outputPath) {+ try FileManager.default.removeItem(atPath: outputPath)+ }+ try FileManager.default.moveItem(atPath: tmp.path, toPath: outputPath)+ } catch {+ try? FileManager.default.removeItem(atPath: tmp.path)+ throw error+ }+ }+ }++ public func downloadRangeToTempFile(filename: String,+ info: RemoteFileInfo,+ offset: UInt64,+ length: Int,+ audit: RepackAudit? = nil) async throws -> TemporaryRangeFile {+ try await withRemoteRetries(retryPolicy,+ audit: audit) {+ try await downloadRangeToTempFileOnce(filename: filename,+ info: info,+ offset: offset,+ length: length)+ }+ }++ private func downloadRangeToTempFileOnce(filename: String,+ info: RemoteFileInfo,+ offset: UInt64,+ length: Int) async throws -> TemporaryRangeFile {+ guard length >= 0 else {+ throw RepackError.remoteProtocolInvalid(detail: "negative range length")+ }+ if length == 0 {+ let path = (tempDirectory as NSString)+ .appendingPathComponent("turbofieldfare-range-\(UUID().uuidString).tmp")+ FileManager.default.createFile(atPath: path, contents: Data())+ return TemporaryRangeFile(path: path, byteCount: 0)+ }+ let end = offset + UInt64(length) - 1+ guard end < info.size else {+ throw RepackError.remoteProtocolInvalid(detail: "range \(offset)-\(end) exceeds \(info.filename)")+ }+ let url = try pinned(commit: info.resolvedCommit).fileURL(filename: filename)+ var request = URLRequest(url: url)+ request.httpMethod = "GET"+ request.setValue("bytes=\(offset)-\(end)", forHTTPHeaderField: "Range")+ request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")+ applyHeaders(to: &request)+ let (downloadedURL, response) = try await session.download(for: request)+ guard let http = response as? HTTPURLResponse else {+ throw RepackError.remoteProtocolInvalid(detail: "missing HTTP response for range \(filename)")+ }+ guard http.statusCode == 206 else {+ throw RepackError.remoteHTTPStatus(url: redact(url), status: http.statusCode)+ }+ try validateRangeResponse(http: http,+ filename: filename,+ offset: offset,+ end: end,+ total: info.size,+ length: UInt64(length))++ try Posix.mkdirP(tempDirectory)+ let target = (tempDirectory as NSString)+ .appendingPathComponent("turbofieldfare-range-\(UUID().uuidString).tmp")+ if FileManager.default.fileExists(atPath: target) {+ try FileManager.default.removeItem(atPath: target)+ }+ do {+ try FileManager.default.moveItem(at: downloadedURL, to: URL(fileURLWithPath: target))+ } catch {+ try? FileManager.default.removeItem(at: downloadedURL)+ throw error+ }+ let attrs = try FileManager.default.attributesOfItem(atPath: target)+ let actual = (attrs[.size] as? NSNumber)?.uint64Value ?? 0+ guard actual == UInt64(length) else {+ try? FileManager.default.removeItem(atPath: target)+ throw RepackError.remoteProtocolInvalid(detail:+ "range \(filename) wrote \(actual), expected \(length)")+ }+ return TemporaryRangeFile(path: target, byteCount: actual)+ }++ private func applyHeaders(to request: inout URLRequest) {+ if let token, request.url?.host == baseURL.host {+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")+ }+ request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")+ }+}++private func validateRepoID(_ repoID: String) throws {+ let parts = repoID.split(separator: "/")+ guard parts.count == 2, parts.allSatisfy({ !$0.isEmpty && !$0.contains("..") }) else {+ throw RepackError.configurationInvalid(detail: "invalid repo id \(repoID)")+ }+}++private func validateFilename(_ filename: String) throws {+ guard !filename.isEmpty,+ !filename.hasPrefix("/"),+ !filename.contains(".."),+ !filename.contains("?"),+ !filename.contains("#") else {+ throw RepackError.configurationInvalid(detail: "invalid remote filename \(filename)")+ }+}++private func header(_ response: HTTPURLResponse, _ name: String) -> String? {+ for (k, v) in response.allHeaderFields {+ if String(describing: k).caseInsensitiveCompare(name) == .orderedSame {+ return String(describing: v)+ }+ }+ return nil+}++private func remoteSize(http: HTTPURLResponse, filename: String) throws -> UInt64 {+ if let linked = header(http, "X-Linked-Size"), let size = UInt64(linked) {+ return size+ }+ if let contentLength = header(http, "Content-Length"), let size = UInt64(contentLength) {+ return size+ }+ throw RepackError.remoteProtocolInvalid(detail: "missing remote size for \(filename)")+}++private func validateRangeResponse(http: HTTPURLResponse,+ filename: String,+ offset: UInt64,+ end: UInt64,+ total: UInt64,+ length: UInt64) throws {+ guard (header(http, "Content-Encoding") ?? "identity").lowercased() == "identity" else {+ throw RepackError.remoteProtocolInvalid(detail: "compressed range response for \(filename)")+ }+ guard let contentLength = header(http, "Content-Length"),+ UInt64(contentLength) == length else {+ throw RepackError.remoteProtocolInvalid(detail: "wrong Content-Length for \(filename)")+ }+ guard let range = header(http, "Content-Range") else {+ throw RepackError.remoteProtocolInvalid(detail: "missing Content-Range for \(filename)")+ }+ let prefix = "bytes "+ guard range.hasPrefix(prefix) else {+ throw RepackError.remoteProtocolInvalid(detail: "malformed Content-Range \(range)")+ }+ let rest = range.dropFirst(prefix.count)+ let parts = rest.split(separator: "/", maxSplits: 1)+ guard parts.count == 2,+ UInt64(parts[1]) == total else {+ throw RepackError.remoteProtocolInvalid(detail: "wrong Content-Range total \(range)")+ }+ let bounds = parts[0].split(separator: "-", maxSplits: 1)+ guard bounds.count == 2,+ UInt64(bounds[0]) == offset,+ UInt64(bounds[1]) == end else {+ throw RepackError.remoteProtocolInvalid(detail: "wrong Content-Range bounds \(range)")+ }+}++private func redact(_ url: URL) -> String {+ var components = URLComponents(url: url, resolvingAgainstBaseURL: false)+ components?.query = nil+ return components?.url?.absoluteString ?? url.absoluteString+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteChunkPolicy.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteChunkPolicy.swiftnew file mode 100644index 00000000..457b467f--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteChunkPolicy.swift@@ -0,0 +1,5 @@+import Foundation++public enum RemoteChunkPolicy {+ public static let defaultBytes = 64 * 1024 * 1024+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteRetry.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteRetry.swiftnew file mode 100644index 00000000..75d724da--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteRetry.swift@@ -0,0 +1,62 @@+import Foundation++public struct RemoteRetryPolicy: Sendable {+ public var attempts: Int+ public var baseDelayNs: UInt64+ public var maxDelayNs: UInt64++ public init(attempts: Int = 4,+ baseDelayNs: UInt64 = 1_000_000_000,+ maxDelayNs: UInt64 = 16_000_000_000) {+ self.attempts = attempts+ self.baseDelayNs = baseDelayNs+ self.maxDelayNs = maxDelayNs+ }++ public static func isRetryable(_ error: Error) -> Bool {+ if let e = error as? URLError {+ switch e.code {+ case .timedOut, .networkConnectionLost, .cannotConnectToHost,+ .dnsLookupFailed, .notConnectedToInternet, .resourceUnavailable:+ return true+ default:+ return false+ }+ }+ if case RepackError.remoteHTTPStatus(_, let status) = error {+ return status == 429 || (500...599).contains(status)+ }+ if case RepackError.remoteProtocolInvalid(let detail) = error,+ detail.contains("wrote") {+ return true+ }+ return false+ }+}++func withRemoteRetries<T>(_ policy: RemoteRetryPolicy,+ audit: RepackAudit?,+ op: () async throws -> T) async throws -> T {+ let attempts = max(policy.attempts, 1)+ var delay = policy.baseDelayNs+ var lastError: Error?+ for attempt in 1...attempts {+ try Task.checkCancellation()+ do {+ return try await op()+ } catch {+ lastError = error+ guard attempt < attempts,+ RemoteRetryPolicy.isRetryable(error) else {+ throw error+ }+ audit?.recordRemoteRetry()+ if delay > 0 {+ let jitter = UInt64.random(in: 0..<250_000_000)+ try await Task.sleep(nanoseconds: delay &+ jitter)+ }+ delay = min(delay &* 2, policy.maxDelayNs)+ }+ }+ throw lastError ?? RepackError.remoteProtocolInvalid(detail: "retry loop exited without an error")+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swiftnew file mode 100644index 00000000..4282d5f5--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift@@ -0,0 +1,102 @@+import Foundation++struct RemoteSnapshot {+ let metadata: IndexLoader.SourceMetadata+ let arch: ArchInfo+ let shardHeaders: [Safetensors.Header]+ let remoteFiles: [String: RemoteFileInfo]+ let resolvedCommit: String+ let metadataDirectory: String+}++enum RemoteSnapshotLoader {+ static func load(remote: HuggingFaceRemoteSource,+ requireKnownSource: Bool,+ metadataDirectory: String,+ audit: RepackAudit? = nil) async throws -> RemoteSnapshot {+ try Posix.mkdirP(metadataDirectory)++ let indexInfo = try await remote.resolveFileInfo(filename: "model.safetensors.index.json",+ audit: audit)+ let pinned = remote.pinned(commit: indexInfo.resolvedCommit)+ let configInfo = try await pinned.resolveFileInfo(filename: "config.json",+ audit: audit)+ guard configInfo.resolvedCommit == indexInfo.resolvedCommit else {+ throw RepackError.remoteProtocolInvalid(detail: "config commit differs from index commit")+ }++ try await pinned.fetchSmallFile(filename: "model.safetensors.index.json",+ info: indexInfo,+ capBytes: 4 * 1024 * 1024,+ outputPath: (metadataDirectory as NSString)+ .appendingPathComponent("model.safetensors.index.json"),+ audit: audit)+ try await pinned.fetchSmallFile(filename: "config.json",+ info: configInfo,+ capBytes: 1024 * 1024,+ outputPath: (metadataDirectory as NSString)+ .appendingPathComponent("config.json"),+ audit: audit)++ let metadata = try IndexLoader.load(snapshotDir: metadataDirectory)+ if requireKnownSource && SourceFingerprint.modelID(forIndexSha256: metadata.indexSha256Hex) == nil {+ throw RepackError.sourceFingerprintRejected(path: metadata.indexPath,+ sha256: metadata.indexSha256Hex)+ }+ let arch = try ArchInfo.load(configPath: metadata.configPath)++ var files: [String: RemoteFileInfo] = [+ indexInfo.filename: indexInfo,+ configInfo.filename: configInfo,+ ]+ var headers: [Safetensors.Header] = []+ headers.reserveCapacity(metadata.shardFilenames.count)+ for shard in metadata.shardFilenames {+ let info = try await pinned.resolveFileInfo(filename: shard, audit: audit)+ guard info.resolvedCommit == indexInfo.resolvedCommit else {+ throw RepackError.remoteProtocolInvalid(detail: "shard \(shard) commit differs from index commit")+ }+ guard info.acceptsRanges else {+ throw RepackError.remoteProtocolInvalid(detail: "shard \(shard) does not advertise byte ranges")+ }+ files[shard] = info+ let prefix = try await pinned.downloadRangeToTempFile(filename: shard,+ info: info,+ offset: 0,+ length: 8,+ audit: audit)+ defer { try? FileManager.default.removeItem(atPath: prefix.path) }+ let prefixData = try Data(contentsOf: URL(fileURLWithPath: prefix.path))+ guard prefixData.count == 8 else {+ throw RepackError.safetensorsHeaderInvalid(path: shard, detail: "short header prefix")+ }+ let headerSize = prefixData.withUnsafeBytes { raw -> UInt64 in+ var value: UInt64 = 0+ for i in 0..<8 {+ value |= UInt64(raw[i]) << UInt64(i * 8)+ }+ return value+ }+ if headerSize > Safetensors.maxHeaderBytes || headerSize > info.size - 8 {+ throw RepackError.safetensorsHeaderTooLarge(path: shard, size: headerSize)+ }+ let headerFile = try await pinned.downloadRangeToTempFile(filename: shard,+ info: info,+ offset: 8,+ length: Int(headerSize),+ audit: audit)+ defer { try? FileManager.default.removeItem(atPath: headerFile.path) }+ let headerData = try Data(contentsOf: URL(fileURLWithPath: headerFile.path))+ headers.append(try Safetensors.parseHeaderBytes(path: shard,+ fileSize: info.size,+ headerBytes: headerData))+ }++ return RemoteSnapshot(metadata: metadata,+ arch: arch,+ shardHeaders: headers,+ remoteFiles: files,+ resolvedCommit: indexInfo.resolvedCommit,+ metadataDirectory: metadataDirectory)+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swiftnew file mode 100644index 00000000..f88eaa22--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift@@ -0,0 +1,338 @@+import Foundation+import Darwin++public struct RemoteStreamingRepackOptions: Sendable {+ public let outputDir: String+ public let overwrite: Bool+ let repoID: String+ let revision: String+ let token: String?+ let requireKnownSource: Bool+ let rangeChunkBytes: Int+ let minFreeReserveBytes: UInt64+ let retainPartialOnFailure: Bool+ let session: URLSession+ let baseURL: URL+ let rangeRetryAttempts: Int+ let retryBaseDelayNs: UInt64++ init(outputDir: String,+ overwrite: Bool,+ repoID: String = SupportedModelSource.repoID,+ revision: String = SupportedModelSource.revision,+ token: String? = nil,+ requireKnownSource: Bool = true,+ rangeChunkBytes: Int = RemoteChunkPolicy.defaultBytes,+ minFreeReserveBytes: UInt64 = SupportedModelSource.reserveBytes,+ retainPartialOnFailure: Bool = true,+ session: URLSession = .shared,+ baseURL: URL = URL(string: "https://huggingface.co")!,+ rangeRetryAttempts: Int = 4,+ retryBaseDelayNs: UInt64 = 1_000_000_000) {+ self.outputDir = outputDir+ self.overwrite = overwrite+ self.repoID = repoID+ self.revision = revision+ self.token = token+ self.requireKnownSource = requireKnownSource+ self.rangeChunkBytes = rangeChunkBytes+ self.minFreeReserveBytes = minFreeReserveBytes+ self.retainPartialOnFailure = retainPartialOnFailure+ self.session = session+ self.baseURL = baseURL+ self.rangeRetryAttempts = rangeRetryAttempts+ self.retryBaseDelayNs = retryBaseDelayNs+ }+}++public struct RemoteStreamingRepackResult: Sendable {+ public let outputDir: String+ public let resolvedCommit: String+ public let remoteBytesToDownload: UInt64+}++public final class RemoteStreamingRepacker {+ private let options: RemoteStreamingRepackOptions+ private let audit: RepackAudit++ public init(options: RemoteStreamingRepackOptions,+ audit: RepackAudit = RepackAudit()) {+ self.options = options+ self.audit = audit+ }++ public func run(progress: @escaping @Sendable (ModelInstallProgress) -> Void = { _ in }) async throws+ -> RemoteStreamingRepackResult {+ try Self.sweepStalePartials(outputDir: options.outputDir, audit: audit)+ if FileManager.default.fileExists(atPath: options.outputDir), !options.overwrite {+ throw RepackError.configurationInvalid(detail:+ "output directory already exists: \(options.outputDir)")+ }++ let partialDir = options.outputDir + ".partial.\(getpid())"+ let metadataDir = (partialDir as NSString).appendingPathComponent(".remote-metadata")+ let tempDir = (partialDir as NSString).appendingPathComponent(".range-tmp")+ try? FileManager.default.removeItem(atPath: partialDir)++ do {+ return try await runPrepared(partialDir: partialDir,+ metadataDir: metadataDir,+ tempDir: tempDir,+ progress: progress)+ } catch {+ if error is CancellationError || !options.retainPartialOnFailure {+ try? FileManager.default.removeItem(atPath: partialDir)+ }+ throw error+ }+ }++ private func runPrepared(partialDir: String,+ metadataDir: String,+ tempDir: String,+ progress: @escaping @Sendable (ModelInstallProgress) -> Void) async throws+ -> RemoteStreamingRepackResult {+ try Task.checkCancellation()+ let retryPolicy = RemoteRetryPolicy(attempts: options.rangeRetryAttempts,+ baseDelayNs: options.retryBaseDelayNs)+ let remote = HuggingFaceRemoteSource(repoID: options.repoID,+ requestedRevision: options.revision,+ token: options.token,+ session: options.session,+ baseURL: options.baseURL,+ tempDirectory: tempDir,+ retryPolicy: retryPolicy)+ progress(.downloadingMetadata)+ let snapshot = try await RemoteSnapshotLoader.load(remote: remote,+ requireKnownSource: options.requireKnownSource,+ metadataDirectory: metadataDir,+ audit: audit)+ try Task.checkCancellation()+ let plan = try RepackPlanner.plan(meta: snapshot.metadata,+ arch: snapshot.arch,+ shardHeaders: snapshot.shardHeaders,+ outputDir: partialDir)+ let rangePlan = try RangeCopyPlanner.plan(repackPlan: plan,+ rangeChunkBytes: options.rangeChunkBytes)+ let outputBytes = plan.resident.totalSize+ + plan.layers.reduce(UInt64(0)) { $0 + $1.fileSize }+ progress(.planning(downloadBytes: rangePlan.remoteBytesToDownload,+ outputBytes: outputBytes))+ let diskRequirement = try DiskSpaceChecker.requireAvailable(+ path: partialDir,+ bytes: outputBytes + UInt64(options.rangeChunkBytes),+ reserveBytes: options.minFreeReserveBytes)+ progress(.checkingDisk(diskRequirement))+ try Task.checkCancellation()++ progress(.reservingOutput(bytes: outputBytes))+ try Task.checkCancellation()+ try Posix.mkdirP((partialDir as NSString).appendingPathComponent("packed_experts"))+ try Posix.mkdirP(tempDir)++ let residentFd = try ResidentWriter.createAndWriteIndex(plan: plan.resident, audit: audit)+ try Posix.fsync(residentFd, path: plan.resident.path)+ close(residentFd)+ for layer in plan.layers where layer.expertsPerLayer > 0 {+ try Task.checkCancellation()+ try Posix.mkdirP((layer.path as NSString).deletingLastPathComponent)+ let fd = try Posix.openCreateRW(layer.path)+ try Posix.ftruncate(fd, path: layer.path, size: layer.fileSize)+ try Posix.fsync(fd, path: layer.path)+ close(fd)+ }++ let provider = HTTPRangeSourceByteProvider(remote: remote.pinned(commit: snapshot.resolvedCommit),+ files: snapshot.remoteFiles,+ writeTileBytes: WriterCore.tileBytes)+ progress(.copyingPayload(downloadedBytes: 0,+ totalBytes: rangePlan.remoteBytesToDownload))+ try await provider.copyBatch(rangePlan.coalescedCopies, audit: audit) { downloadedBytes in+ progress(.copyingPayload(downloadedBytes: downloadedBytes,+ totalBytes: rangePlan.remoteBytesToDownload))+ }++ try recordOutputFile(relativePath: "model_weights.bin",+ path: plan.resident.path,+ progress: progress)+ for layer in plan.layers where layer.expertsPerLayer > 0 {+ try Task.checkCancellation()+ let rel = "packed_experts/" + (layer.path as NSString).lastPathComponent+ try recordOutputFile(relativePath: rel, path: layer.path, progress: progress)+ }++ let layoutPath = ((partialDir as NSString).appendingPathComponent("packed_experts") as NSString)+ .appendingPathComponent("layout.json")+ let expertStride = plan.layers.first(where: { $0.expertsPerLayer > 0 })?.expertStride ?? 0+ let layoutData = try GTurboJSON.encodeLayout(plan: plan, expertStride: expertStride)+ try writeSmall(path: layoutPath, data: layoutData)+ try GTurboLayoutValidator.validate(path: layoutPath, plan: plan)+ try recordOutputFile(relativePath: "packed_experts/layout.json",+ path: layoutPath,+ progress: progress)++ try Task.checkCancellation()+ try await copyRemoteMetadataSidecars(snapshot: snapshot,+ remote: remote,+ partialDir: partialDir,+ progress: progress)+ try? FileManager.default.removeItem(atPath: tempDir)+ try? FileManager.default.removeItem(atPath: metadataDir)+ progress(.finalizing)+ try Task.checkCancellation()+ try writeManifest(plan: plan,+ partialDir: partialDir,+ metadata: snapshot.metadata,+ expertStride: expertStride,+ resolvedCommit: snapshot.resolvedCommit)++ try Task.checkCancellation()+ if FileManager.default.fileExists(atPath: options.outputDir) {+ try FileManager.default.removeItem(atPath: options.outputDir)+ }+ try Posix.rename(from: partialDir, to: options.outputDir)++ return RemoteStreamingRepackResult(outputDir: options.outputDir,+ resolvedCommit: snapshot.resolvedCommit,+ remoteBytesToDownload: rangePlan.remoteBytesToDownload)+ }++ static func sweepStalePartials(outputDir: String, audit: RepackAudit? = nil) throws {+ let parent = (outputDir as NSString).deletingLastPathComponent+ let searchDir = parent.isEmpty ? "." : parent+ let prefix = (outputDir as NSString).lastPathComponent + ".partial."+ let fm = FileManager.default+ for entry in (try? fm.contentsOfDirectory(atPath: searchDir)) ?? []+ where entry.hasPrefix(prefix) {+ let path = (searchDir as NSString).appendingPathComponent(entry)+ let suffix = String(entry.dropFirst(prefix.count))+ if let pid = Int32(suffix),+ kill(pid, 0) == 0 {+ throw RepackError.configurationInvalid(detail:+ "another repack (pid \(pid)) appears to own \(path); " ++ "delete it manually if that process is not a repack")+ }+ try fm.removeItem(atPath: path)+ audit?.stalePartialsRemoved.append(path)+ }+ }++ private func recordOutputFile(relativePath: String,+ path: String,+ progress: @Sendable (ModelInstallProgress) -> Void) throws {+ progress(.hashingOutput(relativePath))+ try Task.checkCancellation()+ let fd = try Posix.openRead(path)+ defer { close(fd) }+ let size = try Posix.fileSize(fd: fd, path: path)+ let sha = try WriterCore.hashEntireFile(path: path,+ size: size,+ audit: audit,+ cancellationCheck: Task.checkCancellation)+ audit.outputFiles.append(.init(relativePath: relativePath, size: size, sha256: sha))+ }++ private func writeSmall(path: String, data: Data) throws {+ try Posix.mkdirP((path as NSString).deletingLastPathComponent)+ try data.write(to: URL(fileURLWithPath: path), options: [.atomic])+ audit.recordWrite(bytes: data.count)+ }++ private func copyRemoteMetadataSidecars(snapshot: RemoteSnapshot,+ remote: HuggingFaceRemoteSource,+ partialDir: String,+ progress: @Sendable (ModelInstallProgress) -> Void) async throws {+ let tokenizerDir = (partialDir as NSString).appendingPathComponent("tokenizer")+ for filename in ["config.json"] {+ try Task.checkCancellation()+ let src = (snapshot.metadataDirectory as NSString).appendingPathComponent(filename)+ guard FileManager.default.fileExists(atPath: src) else { continue }+ try Posix.mkdirP(tokenizerDir)+ let dst = (tokenizerDir as NSString).appendingPathComponent(filename)+ if FileManager.default.fileExists(atPath: dst) {+ try FileManager.default.removeItem(atPath: dst)+ }+ try FileManager.default.copyItem(atPath: src, toPath: dst)+ try recordOutputFile(relativePath: "tokenizer/\(filename)",+ path: dst,+ progress: progress)+ }++ let pinned = remote.pinned(commit: snapshot.resolvedCommit)+ let tokenizerFiles: [(name: String, cap: UInt64, required: Bool)] = [+ ("tokenizer.json", 64 * 1024 * 1024, true),+ ("tokenizer_config.json", 4 * 1024 * 1024, true),+ ("special_tokens_map.json", 1 * 1024 * 1024, false),+ ]+ for file in tokenizerFiles {+ try Task.checkCancellation()+ let info: RemoteFileInfo+ do {+ info = try await pinned.resolveFileInfo(filename: file.name, audit: audit)+ } catch {+ if file.required {+ throw error+ }+ continue+ }+ let dst = (tokenizerDir as NSString).appendingPathComponent(file.name)+ try await pinned.fetchSmallFile(filename: file.name,+ info: info,+ capBytes: file.cap,+ outputPath: dst,+ audit: audit)+ try recordOutputFile(relativePath: "tokenizer/\(file.name)",+ path: dst,+ progress: progress)+ }+ }++ private func writeManifest(plan: RepackPlan,+ partialDir: String,+ metadata: IndexLoader.SourceMetadata,+ expertStride: UInt64,+ resolvedCommit: String) throws {+ var bits = GTurboJSON.QuantBitWidths(embedding: 4,+ attention: 4,+ router: 8,+ sharedExpert: 8,+ routedExpert: 4)+ for e in plan.resident.entries {+ if e.name == "language_model.model.embed_tokens.weight", let s = e.quantSpec { bits.embedding = s.bits }+ if e.name.hasSuffix(".self_attn.q_proj.weight"), let s = e.quantSpec { bits.attention = s.bits }+ if e.name.hasSuffix(".router.proj.weight"), let s = e.quantSpec { bits.router = s.bits }+ if e.name.hasSuffix(".mlp.gate_proj.weight"), let s = e.quantSpec { bits.sharedExpert = s.bits }+ }+ if let layer = plan.layers.first(where: { !$0.subTensors.isEmpty }),+ let routedBits = layer.subTensors.first?.bitsForWeights {+ bits.routedExpert = routedBits+ }+ let files = audit.outputFiles.map {+ ($0.relativePath, GTurboJSON.FileEntry(size: $0.size, sha256: $0.sha256))+ }+ let data = try GTurboJSON.encodeManifest(+ plan: plan,+ modelID: plan.matchedModelID ?? "unknown/snapshot",+ sourceSnapshotHash: "sha256:" + metadata.indexSha256Hex,+ files: files,+ expertsPerLayer: plan.layers.first(where: { $0.expertsPerLayer > 0 })?.expertsPerLayer ?? 0,+ numLayers: plan.arch.numLayers,+ expertStride: expertStride,+ bitWidths: bits)+ let tmp = (partialDir as NSString).appendingPathComponent("manifest.json.tmp")+ let final = (partialDir as NSString).appendingPathComponent("manifest.json")+ try writeSmall(path: tmp, data: data)+ try Posix.rename(from: tmp, to: final)+ let manifestSha = try Sha256Stream.hashFile(path: final)+ let receipt = try VerifiedInstallReceiptWriter.encode(+ outputDir: options.outputDir,+ manifestSha256: manifestSha,+ manifestSize: UInt64(data.count),+ sourceRepoID: options.repoID,+ sourceRevision: resolvedCommit,+ files: audit.outputFiles)+ let receiptPath = (partialDir as NSString)+ .appendingPathComponent(VerifiedInstallReceiptWriter.fileName)+ try writeSmall(path: receiptPath, data: receipt)+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/SourceByteProvider.swift b/Sources/TurboFieldfareRepack/Core/Remote/SourceByteProvider.swiftnew file mode 100644index 00000000..80f43bb3--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/SourceByteProvider.swift@@ -0,0 +1,114 @@+import Foundation+import Darwin++final class HTTPRangeSourceByteProvider {+ private let remote: HuggingFaceRemoteSource+ private let files: [String: RemoteFileInfo]+ private let writeTileBytes: Int++ init(remote: HuggingFaceRemoteSource,+ files: [String: RemoteFileInfo],+ writeTileBytes: Int = WriterCore.tileBytes) {+ self.remote = remote+ self.files = files+ self.writeTileBytes = writeTileBytes+ }++ func copyBatch(_ copies: [CoalescedRangeCopy],+ audit: RepackAudit,+ progress: @Sendable (UInt64) -> Void) async throws {+ let scratch = UnsafeMutableRawBufferPointer.allocate(byteCount: writeTileBytes,+ alignment: 16_384)+ defer { scratch.deallocate() }+ audit.largestScratchBytes = max(audit.largestScratchBytes, scratch.count)++ var outputFDs: [String: Int32] = [:]+ defer {+ for fd in outputFDs.values { close(fd) }+ }++ var downloadedBytes: UInt64 = 0+ for copy in copies {+ try Task.checkCancellation()+ guard let info = files[copy.shardID] else {+ throw RepackError.configurationInvalid(detail: "missing remote info for \(copy.shardID)")+ }+ let temp = try await remote.downloadRangeToTempFile(filename: copy.shardID,+ info: info,+ offset: copy.sourceOffset,+ length: Int(copy.size),+ audit: audit)+ defer { try? FileManager.default.removeItem(atPath: temp.path) }+ audit.remoteRangeRequests += 1+ audit.remoteBytesDownloaded += temp.byteCount+ audit.largestRemoteTransferBytes = max(audit.largestRemoteTransferBytes, Int(temp.byteCount))+ audit.largestRemotePayloadHeapBytes = max(audit.largestRemotePayloadHeapBytes, scratch.count)+ downloadedBytes += temp.byteCount+ progress(downloadedBytes)++ let srcFd = try Posix.openRead(temp.path)+ defer { close(srcFd) }+ for destination in copy.destinations {+ try Task.checkCancellation()+ let dstFd: Int32+ if let cached = outputFDs[destination.destinationPath] {+ dstFd = cached+ } else {+ dstFd = open(destination.destinationPath, O_RDWR)+ if dstFd < 0 {+ throw RepackError.fileOpenFailed(path: destination.destinationPath, errno: errno)+ }+ outputFDs[destination.destinationPath] = dstFd+ }+ let tempOffset = destination.sourceOffset - copy.sourceOffset+ try copyTempRange(srcFd: srcFd,+ srcPath: temp.path,+ dstFd: dstFd,+ dstPath: destination.destinationPath,+ srcOffset: tempOffset,+ dstOffset: destination.destinationOffset,+ size: destination.size,+ scratch: scratch,+ audit: audit)+ }+ }+ for (path, fd) in outputFDs {+ try Task.checkCancellation()+ try Posix.fsync(fd, path: path)+ }+ }++ private func copyTempRange(srcFd: Int32,+ srcPath: String,+ dstFd: Int32,+ dstPath: String,+ srcOffset: UInt64,+ dstOffset: UInt64,+ size: UInt64,+ scratch: UnsafeMutableRawBufferPointer,+ audit: RepackAudit) throws {+ var remaining = size+ var src = srcOffset+ var dst = dstOffset+ while remaining > 0 {+ try Task.checkCancellation()+ let n = min(Int(remaining), scratch.count)+ try Posix.preadAll(fd: srcFd,+ path: srcPath,+ buf: scratch.baseAddress!,+ count: n,+ offset: src)+ try Posix.pwriteAll(fd: dstFd,+ path: dstPath,+ buf: scratch.baseAddress!,+ count: n,+ offset: dst)+ audit.recordTile(bytes: n)+ audit.recordRead(bytes: n)+ audit.recordWrite(bytes: n)+ remaining -= UInt64(n)+ src += UInt64(n)+ dst += UInt64(n)+ }+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift b/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swiftnew file mode 100644index 00000000..cde9f9e5--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift@@ -0,0 +1,22 @@+import Foundation++public enum SupportedModelSource {+ public static let displayName = "gemma-4-26B-A4B-TurboQuant-MLX-4bit"+ public static let repoID = "majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit"+ public static let revision = "cc499c86a958ea7f05cffaa91c7e7243240dabbe"+ public static let approximateDownloadBytes: UInt64 = 14_952_958_284+ public static let installedBytes: UInt64 = 14_527_372_034+ public static let reserveBytes: UInt64 = 1_073_741_824++ public static func installOptions(outputDirectory: URL,+ overwrite: Bool,+ token: String?,+ retainPartialOnFailure: Bool = false)+ -> RemoteStreamingRepackOptions {+ RemoteStreamingRepackOptions(+ outputDir: outputDirectory.path,+ overwrite: overwrite,+ token: token,+ retainPartialOnFailure: retainPartialOnFailure)+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/System/DiskSpaceChecker.swift b/Sources/TurboFieldfareRepack/Core/System/DiskSpaceChecker.swiftnew file mode 100644index 00000000..0b547101--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/System/DiskSpaceChecker.swift@@ -0,0 +1,80 @@+import Foundation+import Darwin++public struct DiskSpaceRequirement: Equatable, Sendable {+ public let path: String+ public let requiredBytes: UInt64+ public let availableBytes: UInt64++ public init(path: String, requiredBytes: UInt64, availableBytes: UInt64) {+ self.path = path+ self.requiredBytes = requiredBytes+ self.availableBytes = availableBytes+ }++ public var canInstall: Bool { availableBytes >= requiredBytes }++ public var shortfallBytes: UInt64 {+ requiredBytes > availableBytes ? requiredBytes - availableBytes : 0+ }+}++public enum DiskSpaceChecker {+ public static func assess(path: String,+ bytes: UInt64,+ reserveBytes: UInt64 = 1 * 1024 * 1024 * 1024) throws+ -> DiskSpaceRequirement {+ let requestedDirectory = directoryForProbe(path)+ let probeDirectory = nearestExistingDirectory(requestedDirectory)+ return try requirement(path: probeDirectory,+ bytes: bytes,+ reserveBytes: reserveBytes)+ }++ public static func requireAvailable(path: String,+ bytes: UInt64,+ reserveBytes: UInt64 = 1 * 1024 * 1024 * 1024) throws -> DiskSpaceRequirement {+ let dir = directoryForProbe(path)+ try Posix.mkdirP(dir)+ let result = try requirement(path: dir, bytes: bytes, reserveBytes: reserveBytes)+ guard result.canInstall else {+ throw RepackError.diskSpaceInsufficient(path: dir,+ required: result.requiredBytes,+ available: result.availableBytes)+ }+ return result+ }++ private static func requirement(path: String,+ bytes: UInt64,+ reserveBytes: UInt64) throws -> DiskSpaceRequirement {+ var st = statfs()+ if statfs(path, &st) != 0 {+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ let available = UInt64(st.f_bavail) * UInt64(st.f_bsize)+ let required = bytes + reserveBytes+ return DiskSpaceRequirement(path: path,+ requiredBytes: required,+ availableBytes: available)+ }++ private static func nearestExistingDirectory(_ path: String) -> String {+ var url = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL+ while !FileManager.default.fileExists(atPath: url.path) {+ let parent = url.deletingLastPathComponent()+ if parent.path == url.path { return url.path }+ url = parent+ }+ return url.path+ }++ private static func directoryForProbe(_ path: String) -> String {+ let ns = path as NSString+ let ext = ns.pathExtension+ if ext.isEmpty {+ return path+ }+ return ns.deletingLastPathComponent+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/System/Posix.swift b/Sources/TurboFieldfareRepack/Core/System/Posix.swiftnew file mode 100644index 00000000..452f3da7--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/System/Posix.swift@@ -0,0 +1,87 @@+import Foundation+import Darwin++/// Thin POSIX helpers used by the writer hot path. The shapes here are picked+/// so callers can stay inside tile-bounded scratch budgets without a+/// Foundation `FileHandle` allocation per write.+enum Posix {+ static func openRead(_ path: String) throws -> Int32 {+ let fd = open(path, O_RDONLY)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ return fd+ }++ static func openCreateRW(_ path: String) throws -> Int32 {+ let fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0o644)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ return fd+ }++ static func ftruncate(_ fd: Int32, path: String, size: UInt64) throws {+ if Darwin.ftruncate(fd, off_t(size)) != 0 {+ throw RepackError.ftruncateFailed(path: path, errno: errno)+ }+ }++ static func pwriteAll(fd: Int32, path: String,+ buf: UnsafeRawPointer, count: Int,+ offset: UInt64) throws {+ var remaining = count+ var off = off_t(offset)+ var ptr = buf+ while remaining > 0 {+ let n = pwrite(fd, ptr, remaining, off)+ if n <= 0 {+ throw RepackError.pwriteShort(path: path, expected: count,+ wrote: count - remaining, errno: errno)+ }+ remaining -= n+ off += off_t(n)+ ptr = ptr.advanced(by: n)+ }+ }++ static func preadAll(fd: Int32, path: String,+ buf: UnsafeMutableRawPointer, count: Int,+ offset: UInt64) throws {+ var remaining = count+ var off = off_t(offset)+ var ptr = buf+ while remaining > 0 {+ let n = pread(fd, ptr, remaining, off)+ if n <= 0 {+ throw RepackError.preadShort(path: path, expected: count,+ got: count - remaining, errno: errno)+ }+ remaining -= n+ off += off_t(n)+ ptr = ptr.advanced(by: n)+ }+ }++ static func fsync(_ fd: Int32, path: String) throws {+ if Darwin.fsync(fd) != 0 {+ throw RepackError.fsyncFailed(path: path, errno: errno)+ }+ }++ static func rename(from src: String, to dst: String) throws {+ if Darwin.rename(src, dst) != 0 {+ throw RepackError.renameFailed(from: src, to: dst, errno: errno)+ }+ }++ static func mkdirP(_ path: String) throws {+ let url = URL(fileURLWithPath: path)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ }++ static func fileSize(fd: Int32, path: String) throws -> UInt64 {+ var st = stat()+ if fstat(fd, &st) != 0 {+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ return UInt64(st.st_size)+ }++}diff --git a/Sources/TurboFieldfareRepack/Core/Verification/RepackAudit.swift b/Sources/TurboFieldfareRepack/Core/Verification/RepackAudit.swiftnew file mode 100644index 00000000..7c7554d1--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Verification/RepackAudit.swift@@ -0,0 +1,43 @@+import Foundation++/// Bounded-copy counters and file hashes used while creating a verified install.+public final class RepackAudit {+ public var sourceBytesRead: UInt64 = 0+ public var outputBytesWritten: UInt64 = 0+ public var intentionalCopyBytes: UInt64 = 0+ public var byteCopyTiles: UInt64 = 0+ public var largestScratchBytes: Int = 0+ public var outputFiles: [OutputFile] = []+ public var remoteBytesDownloaded: UInt64 = 0+ public var remoteRangeRequests: UInt64 = 0+ public var remoteRangeRetries: UInt64 = 0+ public var largestRemoteTransferBytes: Int = 0+ public var largestRemotePayloadHeapBytes: Int = 0+ public var stalePartialsRemoved: [String] = []++ public init() {}++ public struct OutputFile {+ public let relativePath: String+ public let size: UInt64+ public let sha256: String+ }++ public func recordTile(bytes: Int) {+ byteCopyTiles &+= 1+ intentionalCopyBytes &+= UInt64(bytes)+ }++ public func recordWrite(bytes: Int) {+ outputBytesWritten &+= UInt64(bytes)+ }++ public func recordRead(bytes: Int) {+ sourceBytesRead &+= UInt64(bytes)+ }++ public func recordRemoteRetry() {+ remoteRangeRetries &+= 1+ }++}diff --git a/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift b/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swiftnew file mode 100644index 00000000..9b5187df--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift@@ -0,0 +1,45 @@+import Foundation+import CryptoKit++/// Streaming SHA-256 hasher. Wraps CryptoKit's incremental API so we can hash+/// a file as we walk it (mmap'd source pages + zero-filled gaps) without+/// allocating a Swift heap buffer for the whole file.+struct Sha256Stream {+ private var hasher: SHA256++ init() { self.hasher = SHA256() }++ mutating func update(_ ptr: UnsafeRawBufferPointer) {+ hasher.update(bufferPointer: ptr)+ }++ func finalizeHexString() -> String {+ let digest = self.hasher.finalize()+ return digest.map { String(format: "%02x", $0) }.joined()+ }++ /// One-shot helper to hash a file from disk in tile-bounded chunks. Used+ /// for fingerprinting `model.safetensors.index.json`.+ static func hashFile(path: String,+ tileBytes: Int = 65_536,+ noCache: Bool = false) throws -> String {+ let fd = open(path, O_RDONLY)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ defer { close(fd) }+ if noCache {+ _ = fcntl(fd, F_NOCACHE, 1)+ }+ var hasher = Sha256Stream()+ let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: tileBytes, alignment: 16_384)+ defer { buf.deallocate() }+ var off: off_t = 0+ while true {+ let got = pread(fd, buf.baseAddress, tileBytes, off)+ if got < 0 { throw RepackError.preadShort(path: path, expected: tileBytes, got: 0, errno: errno) }+ if got == 0 { break }+ hasher.update(UnsafeRawBufferPointer(start: buf.baseAddress, count: got))+ off += off_t(got)+ }+ return hasher.finalizeHexString()+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Verification/SourceFingerprint.swift b/Sources/TurboFieldfareRepack/Core/Verification/SourceFingerprint.swiftnew file mode 100644index 00000000..85dc9da3--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Verification/SourceFingerprint.swift@@ -0,0 +1,16 @@+import Foundation++/// Snapshot fingerprints pinned by the project. Adding a new entry means the+/// importer has been validated against a fresh upload of the source.+enum SourceFingerprint {+ static let knownFingerprints: [String: String] = [+ "majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit":+ "5455e83705bbdd4e3702c7d4f9d49d4900e84533036628f74500538075dd5c80"+ ]++ /// Returns the recognised model ID for a given index.json SHA-256, or nil.+ static func modelID(forIndexSha256 sha256Hex: String) -> String? {+ for (id, sha) in knownFingerprints where sha == sha256Hex { return id }+ return nil+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallReceiptWriter.swift b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallReceiptWriter.swiftnew file mode 100644index 00000000..b0c17b33--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallReceiptWriter.swift@@ -0,0 +1,42 @@+import Foundation++enum VerifiedInstallReceiptWriter {+ static let fileName = "verified-install.json"++ static func encode(outputDir: String,+ manifestSha256: String,+ manifestSize: UInt64,+ sourceRepoID: String?,+ sourceRevision: String?,+ toolVersion: String = "TurboFieldfareRepack",+ files: [RepackAudit.OutputFile]) throws -> Data {+ var filesDict: [String: Any] = [:]+ for file in files {+ filesDict[file.relativePath] = [+ "size": file.size,+ "sha256": file.sha256+ ]+ }+ filesDict["manifest.json"] = [+ "size": manifestSize,+ "sha256": manifestSha256+ ]++ var receipt: [String: Any] = [+ "schemaVersion": 1,+ "manifestSha256": manifestSha256,+ "modelDirectoryPath": URL(fileURLWithPath: outputDir).standardizedFileURL.path,+ "verificationTimestamp": ISO8601DateFormatter().string(from: Date()),+ "toolVersion": toolVersion,+ "files": filesDict+ ]+ if let sourceRepoID {+ receipt["sourceRepoID"] = sourceRepoID+ }+ if let sourceRevision {+ receipt["sourceRevision"] = sourceRevision+ }+ return try JSONSerialization.data(withJSONObject: receipt,+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swiftnew file mode 100644index 00000000..b548ee0d--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift@@ -0,0 +1,247 @@+import Foundation+import Darwin++public struct VerifyInstallOptions: Sendable {+ public let inputGTurbo: String++ public init(inputGTurbo: String) {+ self.inputGTurbo = inputGTurbo+ }+}++public struct VerifyInstallResult: Sendable {+ public let receiptPath: String+ public let fileCount: Int+ public let bytesVerified: UInt64+ public let unexpectedEntries: [String]+}++public enum VerifiedInstallTool {+ public static let metadataMaxBytes: UInt64 = 16 * 1024 * 1024++ public static func run(options: VerifyInstallOptions) throws -> VerifyInstallResult {+ let root = URL(fileURLWithPath: options.inputGTurbo).standardizedFileURL+ let manifestPath = root.appendingPathComponent("manifest.json").path+ let manifestSize = try fileSize(path: manifestPath, relativePath: "manifest.json")+ let manifestSha = try Sha256Stream.hashFile(path: manifestPath, noCache: true)+ let manifest = try loadManifest(path: manifestPath)+ try validatePackedExpertLayout(root: root, manifest: manifest)++ var files: [RepackAudit.OutputFile] = []+ files.reserveCapacity(manifest.files.count)+ var bytesVerified = manifestSize+ for relativePath in manifest.files.keys.sorted() {+ guard let entry = manifest.files[relativePath] else { continue }+ let path = root.appendingPathComponent(relativePath).path+ let actualSize = try fileSize(path: path, relativePath: relativePath)+ guard actualSize == entry.size else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) size \(actualSize) != manifest \(entry.size)")+ }+ let actualSha = try Sha256Stream.hashFile(path: path, noCache: true)+ guard actualSha.lowercased() == entry.sha256.lowercased() else {+ throw RepackError.configurationInvalid(detail: "\(relativePath) SHA mismatch")+ }+ bytesVerified &+= actualSize+ files.append(RepackAudit.OutputFile(relativePath: relativePath,+ size: actualSize,+ sha256: actualSha))+ }+ let unexpectedEntries = try findUnexpectedEntries(root: root, manifest: manifest)++ let receiptData = try VerifiedInstallReceiptWriter.encode(+ outputDir: root.path,+ manifestSha256: manifestSha,+ manifestSize: manifestSize,+ sourceRepoID: nil,+ sourceRevision: manifest.sourceSnapshotHash,+ toolVersion: "TurboFieldfareRepack verify-install",+ files: files)+ let receiptPath = root.appendingPathComponent(VerifiedInstallReceiptWriter.fileName).path+ try receiptData.write(to: URL(fileURLWithPath: receiptPath), options: .atomic)+ return VerifyInstallResult(receiptPath: receiptPath,+ fileCount: files.count + 1,+ bytesVerified: bytesVerified,+ unexpectedEntries: unexpectedEntries)+ }++ private struct ManifestFileEntry: Decodable {+ let size: UInt64+ let sha256: String+ }++ private struct Manifest: Decodable {+ let files: [String: ManifestFileEntry]+ let expertsPerLayer: Int+ let numLayers: Int+ let expertStride: UInt64+ let sourceSnapshotHash: String?+ }++ private struct PackedExpertsLayout: Decodable {+ let expertStride: UInt64+ let numLayers: Int+ let expertsPerLayer: Int+ let layers: [Layer]+ }++ private struct Layer: Decodable {+ let layer: Int+ let file: String+ let experts: [Expert]+ }++ private struct Expert: Decodable {+ let expert: Int?+ let offset: UInt64+ let size: UInt64+ }++ private static func loadManifest(path: String) throws -> Manifest {+ do {+ let data = try loadMetadataJSON(path: path, relativePath: "manifest.json")+ return try JSONDecoder().decode(Manifest.self, from: data)+ } catch {+ throw RepackError.configurationInvalid(detail: "manifest.json invalid: \(error)")+ }+ }++ private static func loadLayout(path: String) throws -> PackedExpertsLayout {+ do {+ let data = try loadMetadataJSON(path: path, relativePath: "packed_experts/layout.json")+ return try JSONDecoder().decode(PackedExpertsLayout.self, from: data)+ } catch {+ throw RepackError.configurationInvalid(detail: "packed_experts/layout.json invalid: \(error)")+ }+ }++ private static func loadMetadataJSON(path: String, relativePath: String) throws -> Data {+ let size = try fileSize(path: path, relativePath: relativePath)+ guard size <= metadataMaxBytes else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) size \(size) exceeds metadata cap \(metadataMaxBytes)")+ }+ return try Data(contentsOf: URL(fileURLWithPath: path))+ }++ private static func validatePackedExpertLayout(root: URL, manifest: Manifest) throws {+ let layoutRelativePath = "packed_experts/layout.json"+ guard manifest.files[layoutRelativePath] != nil else {+ throw RepackError.configurationInvalid(detail: "manifest missing \(layoutRelativePath)")+ }+ let layout = try loadLayout(path: root.appendingPathComponent(layoutRelativePath).path)+ let pageSize = UInt64(getpagesize())+ guard layout.expertStride == manifest.expertStride,+ layout.numLayers == manifest.numLayers,+ layout.expertsPerLayer == manifest.expertsPerLayer else {+ throw RepackError.configurationInvalid(detail: "packed expert layout dimensions mismatch manifest")+ }+ guard layout.expertStride % pageSize == 0 else {+ throw RepackError.configurationInvalid(+ detail: "expertStride \(layout.expertStride) is not page-aligned")+ }+ guard layout.layers.count == layout.numLayers else {+ throw RepackError.configurationInvalid(detail: "packed expert layout layer count mismatch")+ }+ let expectedLayerSize = UInt64(layout.expertsPerLayer) * layout.expertStride+ for layer in layout.layers {+ guard layer.layer >= 0 && layer.layer < layout.numLayers else {+ throw RepackError.configurationInvalid(detail: "packed expert layer index out of range")+ }+ guard layer.experts.count == layout.expertsPerLayer else {+ throw RepackError.configurationInvalid(+ detail: "packed_experts/\(layer.file) expert count mismatch")+ }+ let relativePath = "packed_experts/\(layer.file)"+ guard let manifestEntry = manifest.files[relativePath] else {+ throw RepackError.configurationInvalid(detail: "manifest missing \(relativePath)")+ }+ guard manifestEntry.size == expectedLayerSize else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) manifest size \(manifestEntry.size) != \(expectedLayerSize)")+ }+ let actualSize = try fileSize(path: root.appendingPathComponent(relativePath).path,+ relativePath: relativePath)+ guard actualSize == expectedLayerSize else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) size \(actualSize) != \(expectedLayerSize)")+ }+ var seenExperts = Set<Int>()+ for (index, expert) in layer.experts.enumerated() {+ let expertID = expert.expert ?? index+ guard expertID >= 0 && expertID < layout.expertsPerLayer else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) expert id out of range")+ }+ guard seenExperts.insert(expertID).inserted else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) duplicate expert \(expertID)")+ }+ guard expert.size == layout.expertStride else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) expert \(expertID) size mismatch")+ }+ guard expert.offset % pageSize == 0 else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) expert \(expertID) offset is not page-aligned")+ }+ guard expert.offset <= actualSize,+ expert.size <= actualSize - expert.offset else {+ throw RepackError.configurationInvalid(+ detail: "\(relativePath) expert \(expertID) range exceeds file size")+ }+ }+ }+ }++ private static func fileSize(path: String, relativePath: String) throws -> UInt64 {+ var st = stat()+ guard stat(path, &st) == 0 else {+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ guard st.st_size >= 0 else {+ throw RepackError.configurationInvalid(detail: "\(relativePath) has negative file size")+ }+ return UInt64(st.st_size)+ }++ private static func findUnexpectedEntries(root: URL, manifest: Manifest) throws -> [String] {+ let declaredFiles = Set(manifest.files.keys)+ .union(["manifest.json", VerifiedInstallReceiptWriter.fileName])+ var allowed = declaredFiles+ for path in declaredFiles {+ var parts = path.split(separator: "/").map(String.init)+ while parts.count > 1 {+ _ = parts.removeLast()+ allowed.insert(parts.joined(separator: "/"))+ }+ }+ allowed.insert("tokenizer")++ guard let enumerator = FileManager.default.enumerator(+ at: root,+ includingPropertiesForKeys: [.isDirectoryKey],+ options: [.skipsPackageDescendants]) else {+ return []+ }++ var unexpected: [String] = []+ for case let url as URL in enumerator {+ let rel = relativePath(for: url, root: root)+ if rel == ".DS_Store" { continue }+ if rel == "tokenizer" || rel.hasPrefix("tokenizer/") { continue }+ if !allowed.contains(rel) {+ unexpected.append(rel)+ }+ }+ return unexpected.sorted()+ }++ private static func relativePath(for url: URL, root: URL) -> String {+ let rootPathRaw = root.standardizedFileURL.path+ let rootPath = rootPathRaw.hasSuffix("/") ? rootPathRaw : rootPathRaw + "/"+ let path = url.standardizedFileURL.path+ guard path.hasPrefix(rootPath) else { return url.lastPathComponent }+ return String(path.dropFirst(rootPath.count))+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift b/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swiftnew file mode 100644index 00000000..e52a5646--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift@@ -0,0 +1,88 @@+import Foundation++public enum RepackError: Error, CustomStringConvertible {+ case fileOpenFailed(path: String, errno: Int32)+ case fileStatFailed(path: String, errno: Int32)+ case ftruncateFailed(path: String, errno: Int32)+ case pwriteShort(path: String, expected: Int, wrote: Int, errno: Int32)+ case preadShort(path: String, expected: Int, got: Int, errno: Int32)+ case mmapFailed(path: String, errno: Int32)+ case renameFailed(from: String, to: String, errno: Int32)+ case fsyncFailed(path: String, errno: Int32)+ case mkdirFailed(path: String, errno: Int32)++ case safetensorsHeaderTooLarge(path: String, size: UInt64)+ case safetensorsHeaderInvalid(path: String, detail: String)+ case safetensorsUnknownDtype(path: String, dtype: String)+ case safetensorsTensorOutOfRange(path: String, name: String, end: UInt64, fileSize: UInt64)++ case indexJsonInvalid(path: String, detail: String)+ case configJsonInvalid(path: String, detail: String)+ case quantOverrideCountMismatch(expected: Int, actual: Int, sample: [String])++ case missingTensor(name: String)+ case unknownTensorPrefix(name: String)+ case missingScalesCompanion(name: String)+ case missingBiasesCompanion(name: String)+ case shapeMismatch(name: String, detail: String)+ case dtypeMismatch(name: String, detail: String)++ case sourceFingerprintRejected(path: String, sha256: String)++ case remoteProtocolInvalid(detail: String)+ case remoteHTTPStatus(url: String, status: Int)+ case remoteFileTooLarge(path: String, size: UInt64, cap: UInt64)+ case diskSpaceInsufficient(path: String, required: UInt64, available: UInt64)++ case scratchExceeded(requested: Int, limit: Int)+ case testHookStop(stage: String)+ case configurationInvalid(detail: String)++ public var description: String {+ switch self {+ case .fileOpenFailed(let p, let e): return "open(\(p)) failed: errno \(e)"+ case .fileStatFailed(let p, let e): return "fstat(\(p)) failed: errno \(e)"+ case .ftruncateFailed(let p, let e): return "ftruncate(\(p)) failed: errno \(e)"+ case .pwriteShort(let p, let exp, let got, let e):+ return "pwrite(\(p)) short: expected \(exp), wrote \(got), errno \(e)"+ case .preadShort(let p, let exp, let got, let e):+ return "pread(\(p)) short: expected \(exp), got \(got), errno \(e)"+ case .mmapFailed(let p, let e): return "mmap(\(p)) failed: errno \(e)"+ case .renameFailed(let a, let b, let e):return "rename(\(a) -> \(b)) failed: errno \(e)"+ case .fsyncFailed(let p, let e): return "fsync(\(p)) failed: errno \(e)"+ case .mkdirFailed(let p, let e): return "mkdir(\(p)) failed: errno \(e)"+ case .safetensorsHeaderTooLarge(let p, let s):+ return "safetensors header at \(p) size \(s) exceeds bound"+ case .safetensorsHeaderInvalid(let p, let d):+ return "safetensors header at \(p) invalid: \(d)"+ case .safetensorsUnknownDtype(let p, let d):+ return "safetensors at \(p) has unsupported dtype \(d)"+ case .safetensorsTensorOutOfRange(let p, let n, let end, let sz):+ return "safetensors \(p): tensor \(n) ends at \(end), file size \(sz)"+ case .indexJsonInvalid(let p, let d): return "index.json \(p) invalid: \(d)"+ case .configJsonInvalid(let p, let d): return "config.json \(p) invalid: \(d)"+ case .quantOverrideCountMismatch(let exp, let got, let sample):+ return "config.json quantization overrides: expected \(exp), got \(got); sample=\(sample.prefix(5))"+ case .missingTensor(let n): return "expected tensor missing: \(n)"+ case .unknownTensorPrefix(let n): return "unknown tensor prefix: \(n)"+ case .missingScalesCompanion(let n): return "quantized tensor \(n) missing .scales companion"+ case .missingBiasesCompanion(let n): return "quantized tensor \(n) missing .biases companion"+ case .shapeMismatch(let n, let d): return "shape mismatch for \(n): \(d)"+ case .dtypeMismatch(let n, let d): return "dtype mismatch for \(n): \(d)"+ case .sourceFingerprintRejected(let p, let s):+ return "source fingerprint \(s) for \(p) is not in known set"+ case .remoteProtocolInvalid(let d):+ return "remote protocol invalid: \(d)"+ case .remoteHTTPStatus(let u, let s):+ return "remote HTTP \(s): \(u)"+ case .remoteFileTooLarge(let p, let s, let c):+ return "remote file \(p) size \(s) exceeds cap \(c)"+ case .diskSpaceInsufficient(let p, let r, let a):+ return "insufficient disk space for \(p): required \(r), available \(a)"+ case .scratchExceeded(let r, let l):+ return "resident index size \(r) exceeds limit \(l)"+ case .testHookStop(let s): return "test hook stop at stage \(s)"+ case .configurationInvalid(let d): return "configuration invalid: \(d)"+ }+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Workflow/ModelInstallProgress.swift b/Sources/TurboFieldfareRepack/Core/Workflow/ModelInstallProgress.swiftnew file mode 100644index 00000000..98a5d908--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Workflow/ModelInstallProgress.swift@@ -0,0 +1,11 @@+import Foundation++public enum ModelInstallProgress: Equatable, Sendable {+ case downloadingMetadata+ case planning(downloadBytes: UInt64, outputBytes: UInt64)+ case checkingDisk(DiskSpaceRequirement)+ case reservingOutput(bytes: UInt64)+ case copyingPayload(downloadedBytes: UInt64, totalBytes: UInt64)+ case hashingOutput(String)+ case finalizing+}diff --git a/Sources/TurboFieldfareRepack/Core/Writing/ResidentWriter.swift b/Sources/TurboFieldfareRepack/Core/Writing/ResidentWriter.swiftnew file mode 100644index 00000000..a478352f--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Writing/ResidentWriter.swift@@ -0,0 +1,61 @@+import Foundation+import Darwin++/// Creates the resident LM `.bin` file and writes its bounded binary index.+enum ResidentWriter {+ private static let maxIndexBytes = 1_048_575++ static func createAndWriteIndex(plan: ResidentFilePlan,+ audit: RepackAudit) throws -> Int32 {+ try Posix.mkdirP(((plan.path as NSString).deletingLastPathComponent))+ let fd = try Posix.openCreateRW(plan.path)+ do {+ try Posix.ftruncate(fd, path: plan.path, size: plan.totalSize)+ try writeIndex(plan: plan, fd: fd, audit: audit)+ return fd+ } catch {+ close(fd)+ throw error+ }+ }++ private static func writeIndex(plan: ResidentFilePlan,+ fd: Int32,+ audit: RepackAudit) throws {+ // The header region size is bounded by indexSize (a few KB); allocate+ // it once on the heap and pwrite once. Well under any reasonable budget.+ let idxBytes = Int(plan.indexSize)+ let idxBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: idxBytes,+ alignment: 16_384)+ defer { idxBuf.deallocate() }+ idxBuf.initializeMemory(as: UInt8.self, repeating: 0)+ if idxBytes > audit.largestScratchBytes {+ // The index page is bounded by the planner; fail instead of+ // allowing this one-shot allocation to reach 1 MiB.+ if idxBytes > maxIndexBytes {+ throw RepackError.scratchExceeded(requested: idxBytes,+ limit: maxIndexBytes)+ }+ audit.largestScratchBytes = idxBytes+ }+ GTurboBinary.writeIndexHeader(into: idxBuf.baseAddress!,+ indexSize: plan.indexSize,+ residentSize: plan.residentSize,+ entryCount: UInt64(plan.entries.count))+ let entriesBase = GTurboBinary.indexHeaderBytes+ let stringTableBase = entriesBase + plan.entries.count * GTurboBinary.indexEntryBytes+ for i in 0..<plan.entries.count {+ let dst = idxBuf.baseAddress!.advanced(by: entriesBase + i * GTurboBinary.indexEntryBytes)+ let nameOff = UInt32(stringTableBase) + plan.stringTableOffsets[i]+ GTurboBinary.writeIndexEntry(into: dst, entry: plan.entries[i], nameOffset: nameOff)+ }+ plan.stringTable.withUnsafeBufferPointer { src in+ let dst = idxBuf.baseAddress!.advanced(by: stringTableBase)+ memcpy(dst, src.baseAddress!, src.count)+ }+ try Posix.pwriteAll(fd: fd, path: plan.path,+ buf: idxBuf.baseAddress!, count: idxBytes, offset: 0)+ audit.recordWrite(bytes: idxBytes)+ }++}diff --git a/Sources/TurboFieldfareRepack/Core/Writing/WriterCore.swift b/Sources/TurboFieldfareRepack/Core/Writing/WriterCore.swiftnew file mode 100644index 00000000..09dcf566--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Writing/WriterCore.swift@@ -0,0 +1,49 @@+import Foundation+import Darwin++/// Shared building blocks for the resident LM and routed-expert layer writers.+enum WriterCore {++ /// Tile size for pwrite (and the subsequent SHA-256 hashing pass). Chosen+ /// so per-worker scratch and per-syscall payload both stay well under 1 MB.+ static let tileBytes: Int = 512 * 1024++ /// Compute SHA-256 of an entire (presumed-written) file by streaming it+ /// through `tileBytes` pread chunks. Drops pages with `F_NOCACHE` style+ /// behaviour via fcntl. Allocates one bounded scratch buffer.+ static func hashEntireFile(path: String, size: UInt64,+ audit: RepackAudit,+ cancellationCheck: () throws -> Void = {}) throws -> String {+ let fd = try Posix.openRead(path)+ defer { close(fd) }+ // Hint the kernel that we will read this file sequentially and then+ // drop it from cache — keeps the post-write working set from blowing+ // up the dev box.+ _ = fcntl(fd, F_NOCACHE, 1)++ let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: WriterCore.tileBytes,+ alignment: 16_384)+ defer { buf.deallocate() }+ if buf.count > audit.largestScratchBytes {+ audit.largestScratchBytes = buf.count+ }++ var hasher = Sha256Stream()+ var off: UInt64 = 0+ let total = Int(size)+ var remaining = total+ while remaining > 0 {+ try cancellationCheck()+ let want = min(remaining, WriterCore.tileBytes)+ let got = pread(fd, buf.baseAddress, want, off_t(off))+ if got <= 0 {+ throw RepackError.preadShort(path: path, expected: want, got: 0, errno: errno)+ }+ hasher.update(UnsafeRawBufferPointer(start: buf.baseAddress, count: got))+ audit.byteCopyTiles &+= 1+ off += UInt64(got)+ remaining -= got+ }+ return hasher.finalizeHexString()+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Buffers/Fp16Buffer.swift b/Sources/TurboFieldfareValidation/Support/Buffers/Fp16Buffer.swiftnew file mode 100644index 00000000..950a62f8--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Buffers/Fp16Buffer.swift@@ -0,0 +1,58 @@+import Metal++/// Make-/read- helpers for FP16 MTLBuffers. Replaces the byte-identical+/// inline copies that lived in 12+ test files.+public enum Fp16Buffer {+ public static func make(_ device: MTLDevice, values: [Float]) -> MTLBuffer? {+ let halves = values.map { Float16($0) }+ return halves.withUnsafeBufferPointer { ptr in+ device.makeBuffer(+ bytes: ptr.baseAddress!,+ length: halves.count * MemoryLayout<Float16>.size,+ options: .storageModeShared+ )+ }+ }++ public static func make(_ device: MTLDevice, halves: [Float16]) -> MTLBuffer? {+ halves.withUnsafeBufferPointer { ptr in+ device.makeBuffer(+ bytes: ptr.baseAddress!,+ length: halves.count * MemoryLayout<Float16>.size,+ options: .storageModeShared+ )+ }+ }++ public static func make(_ device: MTLDevice, count: Int) -> MTLBuffer? {+ device.makeBuffer(+ length: count * MemoryLayout<Float16>.size,+ options: .storageModeShared+ )+ }++ public static func read(_ buf: MTLBuffer, count: Int) -> [Float] {+ var out = [Float](repeating: 0, count: count)+ let base = buf.contents()+ for i in 0..<count {+ let h = base.load(+ fromByteOffset: i * MemoryLayout<Float16>.size,+ as: Float16.self+ )+ out[i] = Float(h)+ }+ return out+ }++ public static func readHalf(_ buf: MTLBuffer, count: Int) -> [Float16] {+ var out = [Float16](repeating: 0, count: count)+ let base = buf.contents()+ for i in 0..<count {+ out[i] = base.load(+ fromByteOffset: i * MemoryLayout<Float16>.size,+ as: Float16.self+ )+ }+ return out+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Fixtures/OffByMultiples.swift b/Sources/TurboFieldfareValidation/Support/Fixtures/OffByMultiples.swiftnew file mode 100644index 00000000..c17d2359--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Fixtures/OffByMultiples.swift@@ -0,0 +1,13 @@+/// Deliberate-pathology shape sweeps modeled on MLX `test_qmm:213`.+///+/// The kernels' threadgroup sizes and SIMD widths are typically multiples+/// of 32; many bugs only surface when the dispatched extent is just past or+/// just shy of those boundaries. New parameterized tests pull shapes from+/// these vectors to ensure we test the edges, not just the nice numbers.+public enum OffByMultiples {+ /// Multiples of the INT4 group size 64. Useful when the kernel+ /// preconditions `N % 64 == 0`.+ public static let multiplesOfGroup: [Int] = [+ 64, 128, 192, 256, 320, 512, 704, 1024, 2816+ ]+}diff --git a/Sources/TurboFieldfareValidation/Support/Fixtures/ScriptedLogitProducer.swift b/Sources/TurboFieldfareValidation/Support/Fixtures/ScriptedLogitProducer.swiftnew file mode 100644index 00000000..d4235f86--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Fixtures/ScriptedLogitProducer.swift@@ -0,0 +1,38 @@+import Foundation+import Metal+import TurboFieldfare++/// Test `LogitProducer` that writes scripted logits, independent of the kernel+/// stack. The `step` closure maps `(inputToken, callIndex)` to a logit spec, so+/// token-keyed automata can script deterministic greedy sequences regardless of+/// how many tokens the prompt prefilled.+public final class ScriptedLogitProducer: LogitProducer, @unchecked Sendable {+ public enum Step: Sendable {+ case argmax(Int32)+ case vector([Float])+ }++ public let vocabSize: Int+ private let step: @Sendable (Int32, Int) -> Step+ private var calls = 0++ public init(vocabSize: Int, step: @escaping @Sendable (Int32, Int) -> Step) {+ self.vocabSize = vocabSize+ self.step = step+ }++ public func reset() { calls = 0 }++ public func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws {+ let spec = step(token, calls)+ calls += 1+ let ptr = logits.contents().bindMemory(to: Float16.self, capacity: vocabSize)+ switch spec {+ case .argmax(let token):+ for i in 0..<vocabSize { ptr[i] = Float16(-30.0) }+ if Int(token) >= 0 && Int(token) < vocabSize { ptr[Int(token)] = Float16(30.0) }+ case .vector(let values):+ for i in 0..<vocabSize { ptr[i] = Float16(i < values.count ? values[i] : -30.0) }+ }+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/PRNG/SeedTree.swift b/Sources/TurboFieldfareValidation/Support/PRNG/SeedTree.swiftnew file mode 100644index 00000000..f80b14ce--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/PRNG/SeedTree.swift@@ -0,0 +1,20 @@+/// One-root-many-streams pattern, modeled on `mx.random.key` + `mx.random.split`.+/// A test seeds a `SeedTree` once at the top, then derives independent+/// `SplitMix64` streams for each input it generates.+public struct SeedTree {+ public let root: UInt64++ public init(_ root: UInt64) {+ self.root = root+ }++ /// Derive a child PRNG by mixing the root with an FNV-1a hash of the label.+ public func key(_ label: String) -> SplitMix64 {+ var h: UInt64 = 0xCBF29CE484222325+ for byte in label.utf8 {+ h ^= UInt64(byte)+ h &*= 0x100000001B3+ }+ return SplitMix64(seed: root ^ h)+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/PRNG/SplitMix64.swift b/Sources/TurboFieldfareValidation/Support/PRNG/SplitMix64.swiftnew file mode 100644index 00000000..3c0e79a1--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/PRNG/SplitMix64.swift@@ -0,0 +1,25 @@+/// Deterministic 64-bit PRNG. Same algorithm as the inline copies in the+/// pre-refactor tests — but conforms to `RandomNumberGenerator` so it+/// composes with stdlib random APIs.+public struct SplitMix64: RandomNumberGenerator {+ private var state: UInt64++ public init(seed: UInt64) {+ self.state = seed+ }++ public mutating func next() -> UInt64 {+ state &+= 0x9E3779B97F4A7C15+ var z = state+ z = (z ^ (z &>> 30)) &* 0xBF58476D1CE4E5B9+ z = (z ^ (z &>> 27)) &* 0x94D049BB133111EB+ return z ^ (z &>> 31)+ }++ /// Uniform float in [lo, hi). 24-bit mantissa precision.+ public mutating func uniform(_ lo: Float, _ hi: Float) -> Float {+ let u = Float(next() >> 40) / Float(1 << 24)+ return lo + (hi - lo) * u+ }++}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Attention/Attention.swift b/Sources/TurboFieldfareValidation/Support/Reference/Attention/Attention.swiftnew file mode 100644index 00000000..9ecc9ce2--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Attention/Attention.swift@@ -0,0 +1,105 @@+import Foundation+import Accelerate++/// FP32 attention reference. Materializes the full attention matrix per Q+/// head: compute all `seqLen` scores via `vDSP_dotpr`, apply the optional+/// SWA window mask, softmax, then output via per-dim `vDSP_dotpr` against+/// the V columns. The kernel runs FlashAttention-style tiled online+/// softmax; this reference does no online merging at all.+public enum AttentionRef {+ /// Q layout: `[numQHeads, headDim]`.+ /// K, V layout: `[seqLen, numKVHeads, headDim]`. (V may alias K when+ /// the caller passes the same array — the math is unchanged.)+ /// Output: `[numQHeads, headDim]`.+ public static func apply(+ q: [Float],+ k: [Float],+ v: [Float],+ headDim: Int,+ numQHeads: Int,+ numKVHeads: Int,+ seqLen: Int,+ window: Int? = nil,+ scale: Float? = nil+ ) -> [Float] {+ precondition(numQHeads % numKVHeads == 0,+ "numQHeads must be a multiple of numKVHeads")+ precondition(q.count == numQHeads * headDim)+ precondition(k.count == seqLen * numKVHeads * headDim)+ precondition(v.count == seqLen * numKVHeads * headDim)++ let groupSize = numQHeads / numKVHeads+ let scale = scale ?? (1.0 / Float(headDim).squareRoot())++ let kvStart: Int+ if let w = window, seqLen > w {+ kvStart = seqLen - w+ } else {+ kvStart = 0+ }++ var out = [Float](repeating: 0, count: numQHeads * headDim)++ // Per-Q-head: build score row via vDSP_dotpr (one dot per key+ // position), softmax via the per-element reference path, output+ // column-wise via vDSP_dotpr against V's per-dim stride.+ for qh in 0..<numQHeads {+ let kvHead = qh / groupSize+ let qBase = qh * headDim++ var scores = [Float](repeating: 0, count: seqLen - kvStart)+ q.withUnsafeBufferPointer { pq in+ for p in kvStart..<seqLen {+ let kBase = (p * numKVHeads + kvHead) * headDim+ var dot: Float = 0+ k.withUnsafeBufferPointer { pk in+ vDSP_dotpr(+ pq.baseAddress! + qBase, 1,+ pk.baseAddress! + kBase, 1,+ &dot, vDSP_Length(headDim)+ )+ }+ scores[p - kvStart] = dot * scale+ }+ }++ // Softmax (numerically stable).+ var mx = scores[0]+ for s in scores { if s > mx { mx = s } }+ var negMax = -mx+ scores.withUnsafeMutableBufferPointer { ps in+ vDSP_vsadd(ps.baseAddress!, 1, &negMax,+ ps.baseAddress!, 1, vDSP_Length(ps.count))+ }+ scores = vForce.exp(scores)+ var sum: Float = 0+ scores.withUnsafeBufferPointer { ps in+ vDSP_sve(ps.baseAddress!, 1, &sum, vDSP_Length(ps.count))+ }+ var invSum = 1.0 / sum+ scores.withUnsafeMutableBufferPointer { ps in+ vDSP_vsmul(ps.baseAddress!, 1, &invSum,+ ps.baseAddress!, 1, vDSP_Length(ps.count))+ }++ // Output[qh, d] = sum_p probs[p] * V[p, kvHead, d]+ // = dot of probs against V's column d (strided by numKVHeads*headDim).+ for d in 0..<headDim {+ var acc: Float = 0+ scores.withUnsafeBufferPointer { ps in+ v.withUnsafeBufferPointer { pv in+ let vColumnStart = (kvStart * numKVHeads + kvHead) * headDim + d+ let stride = numKVHeads * headDim+ vDSP_dotpr(+ ps.baseAddress!, 1,+ pv.baseAddress! + vColumnStart, vDSP_Stride(stride),+ &acc, vDSP_Length(ps.count)+ )+ }+ }+ out[qh * headDim + d] = acc+ }+ }+ return out+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Attention/RoPE.swift b/Sources/TurboFieldfareValidation/Support/Reference/Attention/RoPE.swiftnew file mode 100644index 00000000..ae2aebbc--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Attention/RoPE.swift@@ -0,0 +1,110 @@+import Foundation+import Accelerate++/// FP32 RoPE reference. Precomputes `(cos, sin)` tables for every rotation+/// pair via `vForce.cos`/`vForce.sin`, then applies the rotation per+/// `(token, head)` slice. The kernel walks pair-by-pair recomputing `cosf` /+/// `sinf` inside the inner loop; the reference computes them once in a+/// bulk vector call before any input is touched. Different precision chain+/// (vForce uses extended precision trig in some configurations) and+/// different operation order — kernel bugs that depend on per-pair+/// rounding won't be replicated here.+public enum RopeRef {+ /// Paired-convention RoPE. Pairs in `[0, rotaryDim/2)` rotate; pairs+ /// from `rotaryDim/2` to `headDim/2` pass through unchanged.+ /// Setting `rotaryDim == headDim` recovers full rotation.+ public static func apply(+ input: [Float],+ numTokens: Int,+ numHeads: Int,+ headDim: Int,+ rotaryDim: Int,+ position: Int,+ theta: Float+ ) -> [Float] {+ precondition(input.count == numTokens * numHeads * headDim,+ "input must be numTokens * numHeads * headDim")+ precondition(rotaryDim % 2 == 0, "rotaryDim must be even")+ precondition(rotaryDim <= headDim, "rotaryDim cannot exceed headDim")++ let pairs = rotaryDim / 2++ // 1. Build angle table: angle[k] = position * theta^(-2k / rotaryDim)+ var angles = [Float](repeating: 0, count: pairs)+ let logTheta = Foundation.log(theta)+ let positionF = Float(position)+ for k in 0..<pairs {+ let exponent = -Float(2 * k) / Float(rotaryDim)+ angles[k] = positionF * Foundation.exp(exponent * logTheta)+ }++ // 2. Bulk-compute cos / sin once for all pairs.+ let cosTable = vForce.cos(angles)+ let sinTable = vForce.sin(angles)++ // 3. Apply rotation. Pass-through region copies input unchanged.+ var out = input+ for t in 0..<numTokens {+ for h in 0..<numHeads {+ let base = (t * numHeads + h) * headDim+ for k in 0..<pairs {+ let i0 = base + 2 * k+ let i1 = i0 + 1+ let x0 = input[i0]+ let x1 = input[i1]+ let c = cosTable[k]+ let s = sinTable[k]+ out[i0] = x0 * c - x1 * s+ out[i1] = x0 * s + x1 * c+ }+ }+ }+ return out+ }++ /// NeoX-convention RoPE. Pairs `(x[i], x[i+headDim/2])` for `i ∈ [0, rotatedPairs)`.+ /// Frequencies divide by `headDim` (not `2 * rotatedPairs`) — matching HF+ /// Gemma 4's proportional-RoPE init. Setting `rotatedPairs == headDim/2`+ /// recovers full NeoX rotation.+ public static func applyNeox(+ input: [Float],+ numTokens: Int,+ numHeads: Int,+ headDim: Int,+ rotatedPairs: Int,+ position: Int,+ theta: Float+ ) -> [Float] {+ precondition(input.count == numTokens * numHeads * headDim,+ "input size mismatch")+ precondition(rotatedPairs * 2 <= headDim, "rotatedPairs * 2 must not exceed headDim")+ let halfDim = headDim / 2+ var angles = [Float](repeating: 0, count: rotatedPairs)+ let logTheta = Foundation.log(theta)+ let positionF = Float(position)+ for i in 0..<rotatedPairs {+ let exponent = -Float(2 * i) / Float(headDim)+ angles[i] = positionF * Foundation.exp(exponent * logTheta)+ }+ let cosTable = vForce.cos(angles)+ let sinTable = vForce.sin(angles)++ var out = input+ for t in 0..<numTokens {+ for h in 0..<numHeads {+ let base = (t * numHeads + h) * headDim+ for i in 0..<rotatedPairs {+ let i0 = base + i+ let i1 = base + halfDim + i+ let x0 = input[i0]+ let x1 = input[i1]+ let c = cosTable[i]+ let s = sinTable[i]+ out[i0] = x0 * c - x1 * s+ out[i1] = x0 * s + x1 * c+ }+ }+ }+ return out+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/KVCache/TurboQuantWht.swift b/Sources/TurboFieldfareValidation/Support/Reference/KVCache/TurboQuantWht.swiftnew file mode 100644index 00000000..0f0ce80c--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/KVCache/TurboQuantWht.swift@@ -0,0 +1,106 @@+import Foundation++/// Recursive Walsh-Hadamard transform (`/sqrt(2)` per stage). Implemented+/// divide-and-conquer style — splits the input into halves, recurses, then+/// combines. The kernel uses an iterative stride-doubling butterfly inside+/// SIMD threadgroups. Different control flow, different summation order.+public enum WhtRef {+ public static func apply(_ x: [Float]) -> [Float] {+ let d = x.count+ precondition(d > 0 && (d & (d - 1)) == 0, "D must be a power of two")+ if d == 1 { return x }+ return walsh(x)+ }++ private static func walsh(_ x: [Float]) -> [Float] {+ let n = x.count+ if n == 1 { return x }+ let half = n / 2+ // Split into low / high halves, recurse, then combine.+ let lo = walsh(Array(x[0..<half]))+ let hi = walsh(Array(x[half..<n]))+ let invSqrt2: Float = 1.0 / Float(2.0).squareRoot()+ var y = [Float](repeating: 0, count: n)+ for i in 0..<half {+ y[i] = (lo[i] + hi[i]) * invSqrt2+ y[half + i] = (lo[i] - hi[i]) * invSqrt2+ }+ return y+ }+}++public enum TurboQuantRef {+ private static let codebook: [Float] = [+ -2.7326, -2.0690, -1.6181, -1.2562,+ -0.9424, -0.6568, -0.3881, -0.1284,+ 0.1284, 0.3881, 0.6568, 0.9424,+ 1.2562, 1.6181, 2.0690, 2.7326,+ ]++ public static func materializePackedCache(+ _ cache: [UInt8],+ tokenCount: Int,+ headDim: Int,+ numHeads: Int,+ bytesPerHead: Int,+ bytesPerToken: Int,+ packedOffset: Int,+ scaleOffset: Int,+ layer: UInt32 = 0,+ rotationSeed: UInt32 = 0,+ applyRotation: Bool = false+ ) -> [Float] {+ precondition(tokenCount >= 0 && headDim > 0 && numHeads > 0)+ precondition(cache.count >= tokenCount * bytesPerToken)+ var output = [Float](repeating: 0, count: tokenCount * numHeads * headDim)++ for token in 0..<tokenCount {+ for head in 0..<numHeads {+ let cacheBase = token * bytesPerToken + head * bytesPerHead+ let scaleBits = UInt16(cache[cacheBase + scaleOffset])+ | (UInt16(cache[cacheBase + scaleOffset + 1]) << 8)+ let scale = Float(Float16(bitPattern: scaleBits))+ var transformed = [Float](repeating: 0, count: headDim)+ for dimension in 0..<headDim {+ let byte = cache[cacheBase + packedOffset + dimension / 2]+ let index = dimension.isMultiple(of: 2)+ ? Int(byte & 0x0F)+ : Int(byte >> 4)+ transformed[dimension] = Float(Float16(codebook[index] * scale))+ }++ let restored = WhtRef.apply(transformed)+ let outputBase = (token * numHeads + head) * headDim+ for dimension in 0..<headDim {+ let value = applyRotation+ && rotationSign(layer: layer,+ head: UInt32(head),+ dimension: UInt32(dimension),+ seed: rotationSeed)+ ? -restored[dimension]+ : restored[dimension]+ output[outputBase + dimension] = Float(Float16(value))+ }+ }+ }+ return output+ }++ private static func rotationSign(layer: UInt32,+ head: UInt32,+ dimension: UInt32,+ seed: UInt32) -> Bool {+ var value = UInt64(seed)+ value ^= UInt64(layer) &* 0x9E37_79B9_7F4A_7C15+ value ^= UInt64(head) &* 0xBF58_476D_1CE4_E5B9+ value ^= UInt64(dimension) &* 0x94D0_49BB_1331_11EB+ return mix64(value) >> 63 != 0+ }++ private static func mix64(_ input: UInt64) -> UInt64 {+ var value = input+ value = (value ^ (value >> 30)) &* 0xBF58_476D_1CE4_E5B9+ value = (value ^ (value >> 27)) &* 0x94D0_49BB_1331_11EB+ return value ^ (value >> 31)+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/MoE/Moe.swift b/Sources/TurboFieldfareValidation/Support/Reference/MoE/Moe.swiftnew file mode 100644index 00000000..bb07e751--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/MoE/Moe.swift@@ -0,0 +1,90 @@+import Foundation+import Accelerate+import TurboFieldfare++/// FP32 reference for the fused MoE FFN: top-k routed experts + 1 shared+/// expert, each with gate / up / down projections, GeGLU activation, and a+/// weighted combine into the residual stream.+///+/// Composed from `DequantInt4GemvRef` (vDSP_dotpr after bulk affine dequant)+/// + a vForce-based `gelu_pytorch_tanh`. The kernel inlines the dequant ++/// gate*up*down chain in one threadgroup per output element; this reference+/// materializes the F-dim intermediate per expert and uses Accelerate+/// primitives for the inner products. Different code shape, different+/// summation order — bugs that depend on the in-flight dequant pattern won't+/// replicate here.+public enum MoeRef {+ public static let geluCoeff: Float = 0.7978845608028654 // sqrt(2/π)+ public static let geluCubic: Float = 0.044715++ /// Per-element `gelu_pytorch_tanh(x) = 0.5 * x * (1 + tanh(c * (x + k * x^3)))`.+ public static func geluTanh(_ x: [Float]) -> [Float] {+ var y = [Float](repeating: 0, count: x.count)+ for i in 0..<x.count {+ let xv = x[i]+ let inner = geluCoeff * (xv + geluCubic * xv * xv * xv)+ y[i] = 0.5 * xv * (1.0 + Foundation.tanh(inner))+ }+ return y+ }++ /// Runs one FFN block: `down(gelu(gate(x)) * up(x))`.+ /// `gateRows` / `upRows` are F-by-D affine INT4. `downRows` is D-by-F.+ public static func runFFN(+ gateRows: [Quantization.Int4AffineRow],+ upRows: [Quantization.Int4AffineRow],+ downRows: [Quantization.Int4AffineRow],+ x: [Float],+ d: Int,+ f: Int+ ) -> [Float] {+ precondition(gateRows.count == f, "gateRows must be F=\(f)")+ precondition(upRows.count == f, "upRows must be F=\(f)")+ precondition(downRows.count == d, "downRows must be D=\(d)")+ precondition(x.count == d)++ let gateOut = DequantInt4GemvRef.apply(weightRows: gateRows, x: x, n: d)+ let upOut = DequantInt4GemvRef.apply(weightRows: upRows, x: x, n: d)+ let gated = geluTanh(gateOut)+ var act = [Float](repeating: 0, count: f)+ vDSP_vmul(gated, 1, upOut, 1, &act, 1, vDSP_Length(f))+ return DequantInt4GemvRef.apply(weightRows: downRows, x: act, n: f)+ }++ /// Routed-only sibling of `applyStreamed`. Gemma 4's parallel-MoE block+ /// computes dense MLP and routed branches separately, then sums; this is+ /// the routed-only half.+ /// `y = residual + Σ wₑ · routed_e(x)`.+ public static func applyStreamedRouted(+ x: [Float],+ residual: [Float],+ routedGate: [[Quantization.Int4AffineRow]],+ routedUp: [[Quantization.Int4AffineRow]],+ routedDown: [[Quantization.Int4AffineRow]],+ indices: [Int],+ routingWeights: [Float],+ d: Int,+ f: Int+ ) -> [Float] {+ precondition(indices.count == routingWeights.count)+ precondition(residual.count == d)++ var y = residual+ for slot in 0..<indices.count {+ let e = indices[slot]+ let w = routingWeights[slot]+ let out = runFFN(+ gateRows: routedGate[e],+ upRows: routedUp[e],+ downRows: routedDown[e],+ x: x, d: d, f: f+ )+ var scale = w+ var scaled = [Float](repeating: 0, count: d)+ vDSP_vsmul(out, 1, &scale, &scaled, 1, vDSP_Length(d))+ vDSP_vadd(y, 1, scaled, 1, &y, 1, vDSP_Length(d))+ }+ return y+ }++}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Primitives/RmsNorm.swift b/Sources/TurboFieldfareValidation/Support/Reference/Primitives/RmsNorm.swiftnew file mode 100644index 00000000..1b03bbfc--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Primitives/RmsNorm.swift@@ -0,0 +1,46 @@+import Foundation+import Accelerate++/// FP32 RMSNorm reference computed with Accelerate vectorized primitives.+///+/// Deliberately reaches the same answer via a *different* sequence of+/// operations than the Metal kernel: `vDSP_svesq` for the sum-of-squares,+/// `vDSP_vmul` + `vDSP_vsmul` for the per-element scale. The kernel uses a+/// per-thread block reduction with `simd_sum`; this reference uses+/// Accelerate's pipeline. Different summation tree, different rounding chain,+/// same math — which is what makes this a useful comparator.+public enum RmsNormRef {+ /// y[i] = x[i] * weight[i] * 1 / sqrt(mean(x^2) + eps)+ public static func apply(x: [Float], weight: [Float], eps: Float) -> [Float] {+ precondition(x.count == weight.count, "x and weight must match length")+ let d = x.count++ var sumSq: Float = 0+ x.withUnsafeBufferPointer { p in+ vDSP_svesq(p.baseAddress!, 1, &sumSq, vDSP_Length(d))+ }+ let invRms = 1.0 / (sumSq / Float(d) + eps).squareRoot()++ var y = [Float](repeating: 0, count: d)+ x.withUnsafeBufferPointer { px in+ weight.withUnsafeBufferPointer { pw in+ y.withUnsafeMutableBufferPointer { py in+ vDSP_vmul(+ px.baseAddress!, 1,+ pw.baseAddress!, 1,+ py.baseAddress!, 1,+ vDSP_Length(d)+ )+ var s = invRms+ vDSP_vsmul(+ py.baseAddress!, 1,+ &s,+ py.baseAddress!, 1,+ vDSP_Length(d)+ )+ }+ }+ }+ return y+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Quant/DequantInt4Gemv.swift b/Sources/TurboFieldfareValidation/Support/Reference/Quant/DequantInt4Gemv.swiftnew file mode 100644index 00000000..be3f3f32--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Quant/DequantInt4Gemv.swift@@ -0,0 +1,43 @@+import Foundation+import Accelerate+import TurboFieldfare++/// FP32 reference for the INT4-affine groupwise GEMV `y = W * x`.+///+/// Bulk-dequantizes each row to FP32 via `Quantization.dequantizeInt4Affine`,+/// then dots with `vDSP_dotpr`. The kernel interleaves nibble unpack + scale ++/// bias + FMA inside one inner loop per thread — different staging, different+/// summation order. Bugs that depend on the in-flight dequant pattern won't+/// replicate here.+public enum DequantInt4GemvRef {+ public static func apply(+ weightRows: [Quantization.Int4AffineRow],+ x: [Float],+ n: Int+ ) -> [Float] {+ precondition(!weightRows.isEmpty)+ precondition(x.count == n)+ precondition(n % Quantization.groupSize == 0,+ "N must be a multiple of \(Quantization.groupSize)")++ let m = weightRows.count+ var y = [Float](repeating: 0, count: m)++ for row in 0..<m {+ let wRow = Quantization.dequantizeInt4Affine(weightRows[row], n: n)+ var dot: Float = 0+ wRow.withUnsafeBufferPointer { pw in+ x.withUnsafeBufferPointer { px in+ vDSP_dotpr(+ pw.baseAddress!, 1,+ px.baseAddress!, 1,+ &dot,+ vDSP_Length(n)+ )+ }+ }+ y[row] = dot+ }+ return y+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Quant/DequantInt8Gemv.swift b/Sources/TurboFieldfareValidation/Support/Reference/Quant/DequantInt8Gemv.swiftnew file mode 100644index 00000000..9eabc13c--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Quant/DequantInt8Gemv.swift@@ -0,0 +1,41 @@+import Foundation+import Accelerate+import TurboFieldfare++/// FP32 reference for the INT8-affine groupwise GEMV `y = W * x`.+///+/// Bulk-dequantizes each row to FP32 via `Quantization.dequantizeInt8Affine`,+/// then computes the inner product with `vDSP_dotpr`. The kernel interleaves+/// byte unpack + per-group scale + bias + FMA in the inner loop per thread;+/// this reference splits dequant from accumulation. Different staging,+/// different summation order.+public enum DequantInt8GemvRef {+ public static func apply(+ weightRows: [Quantization.Int8AffineRow],+ x: [Float],+ n: Int+ ) -> [Float] {+ precondition(!weightRows.isEmpty)+ precondition(x.count == n)+ precondition(n % Quantization.groupSize == 0)++ let m = weightRows.count+ var y = [Float](repeating: 0, count: m)+ for row in 0..<m {+ let wRow = Quantization.dequantizeInt8Affine(weightRows[row], n: n)+ var dot: Float = 0+ wRow.withUnsafeBufferPointer { pw in+ x.withUnsafeBufferPointer { px in+ vDSP_dotpr(+ pw.baseAddress!, 1,+ px.baseAddress!, 1,+ &dot,+ vDSP_Length(n)+ )+ }+ }+ y[row] = dot+ }+ return y+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Quant/EmbedLookup.swift b/Sources/TurboFieldfareValidation/Support/Reference/Quant/EmbedLookup.swiftnew file mode 100644index 00000000..b52c273f--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Quant/EmbedLookup.swift@@ -0,0 +1,78 @@+import Foundation+import TurboFieldfare++/// FP32 reference for the INT8-affine embedding lookup+/// `out = dequantize(table[tokenId])`.+///+/// `tablePacked` is `[V * D]` unsigned bytes; `tableScales` is+/// `[V * (D/groupSize)]` BF16 (stored as `UInt16` bit patterns).+/// `tableBiases` follows the same shape. Returns the FP32 row for the given+/// token.+public enum EmbedLookupRef {+ public static func apply(+ tablePacked: [UInt8],+ tableScales: [UInt16],+ tableBiases: [UInt16],+ tokenId: Int,+ d: Int+ ) -> [Float] {+ precondition(d % Quantization.groupSize == 0,+ "D must be a multiple of \(Quantization.groupSize)")+ let groupsPerRow = d / Quantization.groupSize+ let packBase = tokenId * d+ let scaleBase = tokenId * groupsPerRow++ precondition(packBase + d <= tablePacked.count, "token out of range")+ precondition(scaleBase + groupsPerRow <= tableScales.count, "scales out of range")+ precondition(scaleBase + groupsPerRow <= tableBiases.count, "biases out of range")++ var out = [Float](repeating: 0, count: d)+ for g in 0..<groupsPerRow {+ let scale = Quantization.bf16ToFloat(tableScales[scaleBase + g])+ let bias = Quantization.bf16ToFloat(tableBiases[scaleBase + g])+ let groupBase = packBase + g * Quantization.groupSize+ for k in 0..<Quantization.groupSize {+ out[g * Quantization.groupSize + k] =+ Float(tablePacked[groupBase + k]) * scale + bias+ }+ }+ return out+ }++ /// FP32 reference for `embed_lookup_int4`.+ ///+ /// `tablePacked` carries `V * D/2` bytes (low nibble = even index inside a+ /// row, high nibble = odd index). Output is multiplied by `outScale` —+ /// pass `sqrt(hidden_size)` to match Gemma 4's post-embedding scale, or+ /// `1.0` for the raw dequant.+ public static func applyInt4(+ tablePacked: [UInt8],+ tableScales: [UInt16],+ tableBiases: [UInt16],+ tokenId: Int,+ d: Int,+ outScale: Float+ ) -> [Float] {+ precondition(d % Quantization.groupSize == 0,+ "D must be a multiple of \(Quantization.groupSize)")+ let groupsPerRow = d / Quantization.groupSize+ let rowBytes = d / 2+ let packBase = tokenId * rowBytes+ let scaleBase = tokenId * groupsPerRow++ precondition(packBase + rowBytes <= tablePacked.count, "token out of range")+ precondition(scaleBase + groupsPerRow <= tableScales.count, "scales out of range")+ precondition(scaleBase + groupsPerRow <= tableBiases.count, "biases out of range")++ var out = [Float](repeating: 0, count: d)+ for i in 0..<d {+ let byte = tablePacked[packBase + (i >> 1)]+ let q = (i & 1) == 0 ? Int(byte & 0x0F) : Int(byte >> 4)+ let g = i / Quantization.groupSize+ let scale = Quantization.bf16ToFloat(tableScales[scaleBase + g])+ let bias = Quantization.bf16ToFloat(tableBiases[scaleBase + g])+ out[i] = (Float(q) * scale + bias) * outScale+ }+ return out+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Sampling/LogitSoftcapSoftmax.swift b/Sources/TurboFieldfareValidation/Support/Reference/Sampling/LogitSoftcapSoftmax.swiftnew file mode 100644index 00000000..a6a1dc84--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Sampling/LogitSoftcapSoftmax.swift@@ -0,0 +1,55 @@+import Foundation+import Accelerate++/// FP32 reference for `softmax(softcap * tanh(x / softcap))`.+///+/// The kernel runs a single-pass online safe softmax with the softcap+/// fused into the running-max update. This reference is deliberately+/// *two-pass*: apply the softcap to a temp buffer, find the max, subtract,+/// exp via `vForce.exp`, sum via `vDSP_sve`, divide. Different staging,+/// different summation order — any bug that depends on the kernel's online+/// (m, d) merge logic won't replicate here.+///+/// Softcap is `c * tanh(x / c)` with c=30.0 by default for Gemma 4.+public enum LogitSoftcapSoftmaxRef {+ public static func apply(x: [Float], softcap: Float) -> [Float] {+ let v = x.count+ let invC = 1.0 / softcap++ // 1. Apply softcap: y = softcap * tanh(x / softcap)+ // Two-step: y = x * invC; y = tanh(y); y = y * softcap.+ var y = [Float](repeating: 0, count: v)+ var s = invC+ x.withUnsafeBufferPointer { px in+ y.withUnsafeMutableBufferPointer { py in+ vDSP_vsmul(px.baseAddress!, 1, &s, py.baseAddress!, 1, vDSP_Length(v))+ }+ }+ y = vForce.tanh(y)+ var c = softcap+ y.withUnsafeMutableBufferPointer { py in+ vDSP_vsmul(py.baseAddress!, 1, &c, py.baseAddress!, 1, vDSP_Length(v))+ }++ // 2. Numerically stable softmax: subtract max, exp, divide by sum.+ var mx: Float = -.infinity+ y.withUnsafeBufferPointer { py in+ vDSP_maxv(py.baseAddress!, 1, &mx, vDSP_Length(v))+ }+ var negMax = -mx+ y.withUnsafeMutableBufferPointer { py in+ vDSP_vsadd(py.baseAddress!, 1, &negMax, py.baseAddress!, 1, vDSP_Length(v))+ }+ y = vForce.exp(y)++ var sum: Float = 0+ y.withUnsafeBufferPointer { py in+ vDSP_sve(py.baseAddress!, 1, &sum, vDSP_Length(v))+ }+ var invSum = 1.0 / sum+ y.withUnsafeMutableBufferPointer { py in+ vDSP_vsmul(py.baseAddress!, 1, &invSum, py.baseAddress!, 1, vDSP_Length(v))+ }+ return y+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Tolerance/RelError.swift b/Sources/TurboFieldfareValidation/Support/Tolerance/RelError.swiftnew file mode 100644index 00000000..3028c20d--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Tolerance/RelError.swift@@ -0,0 +1,44 @@+import Foundation++/// Error-measurement helpers. Every test computed these inline; centralize.+public enum RelError {+ /// Standard relative error used across the test suite:+ /// max_i |actual[i] - reference[i]| / max(max_i |reference[i]|, 1e-6)+ public static func compute(actual: [Float], reference: [Float]) -> Float {+ precondition(actual.count == reference.count, "length mismatch")+ var maxAbsDiff: Float = 0+ var refNorm: Float = 0+ for i in 0..<actual.count {+ maxAbsDiff = max(maxAbsDiff, abs(actual[i] - reference[i]))+ refNorm = max(refNorm, abs(reference[i]))+ }+ return maxAbsDiff / max(refNorm, 1e-6)+ }++ public static func maxAbsDiff(_ a: [Float], _ b: [Float]) -> Float {+ precondition(a.count == b.count, "length mismatch")+ var m: Float = 0+ for i in 0..<a.count {+ m = max(m, abs(a[i] - b[i]))+ }+ return m+ }++ /// Refines `compute` with both a relative and an absolute floor.+ /// Used when very small reference values would inflate relative error+ /// past the meaningful FP16 noise floor.+ public static func boundedRel(+ actual: [Float],+ reference: [Float],+ absFloor: Float+ ) -> Float {+ precondition(actual.count == reference.count, "length mismatch")+ var worst: Float = 0+ for i in 0..<actual.count {+ let diff = abs(actual[i] - reference[i])+ let denom = max(abs(reference[i]), absFloor)+ worst = max(worst, diff / denom)+ }+ return worst+ }+}diff --git a/Sources/TurboFieldfareValidation/Support/Tolerance/Tolerances.swift b/Sources/TurboFieldfareValidation/Support/Tolerance/Tolerances.swiftnew file mode 100644index 00000000..4ff70ca6--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Tolerance/Tolerances.swift@@ -0,0 +1,21 @@+/// Tolerance dictionary modeled on MLX (`test_fast.py:80`). Each constant is+/// a *relative* error bar against an FP32 reference, sized to the accumulation+/// depth and dtype of the kernel under test.+public enum Tolerance {+ /// FP32 identity / pass-through. Bit-exact-ish.+ public static let identity: Float = 1e-5++ /// FP16 single-reduction kernels (RMSNorm, one GEMV, short-axis softmax).+ /// Comfortably above the FP16-accumulation-in-FP32 ULP floor.+ public static let fp16Reduction: Float = 5e-3++ /// FP16 chained reductions: multi-stage MoE, attention's softmax + matmul+ /// composition, every block-level fusion. Absorbs FP16 round-tripping at+ /// each intermediate.+ public static let fp16ChainedReduction: Float = 1e-2++ /// Quantization-aware comparisons. Callers usually override with a+ /// mathematically derived bound (e.g. `|w - w_hat| <= |scales|`).+ public static let quantInt4: Float = 1.5e-3+ public static let quantInt8: Float = 1e-3+}diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 00000000..15cacd51--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,49 @@+# Third-party software and model terms++TurboFieldfare repository source is licensed under the+[Apache License 2.0](LICENSE). That license applies to TurboFieldfare's own source+and documentation. It does not relicense model weights or third-party+packages.++This file records the dependency review performed on 2026-07-15. It is an+attribution aid, not legal advice. Anyone distributing a compiled product must+also preserve the license and NOTICE material required by the exact dependency+versions included in that product.++## Model weights++Model weights are not included in this repository. The installer downloads a+pinned revision of+[`majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit`](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit)+and repacks it locally. The model card labels that checkpoint Apache-2.0 and+identifies `google/gemma-4-26B-A4B` as its base model. Google publishes Gemma 4+under the+[Apache License 2.0](https://ai.google.dev/gemma/apache_2).++Downloaded weights remain a separate work governed by their source terms. Do+not redistribute weights as part of TurboFieldfare releases.++## Swift package graph++The following table covers the complete graph reported by+`swift package show-dependencies` from the checked-in+[`Package.resolved`](Package.resolved). Exact revisions are recorded there.++| Package | Version | License in locked checkout |+| --- | --- | --- |+| [swift-transformers](https://github.com/huggingface/swift-transformers) | 1.3.3 | Apache-2.0 |+| [swift-jinja](https://github.com/huggingface/swift-jinja) | 2.3.6 | Apache-2.0 |+| [swift-huggingface](https://github.com/huggingface/swift-huggingface) | 0.9.0 | Apache-2.0 |+| [EventSource](https://github.com/mattt/EventSource) | 1.4.1 | MIT |+| [swift-nio](https://github.com/apple/swift-nio) | 2.99.0 | Apache-2.0; upstream NOTICE applies |+| [swift-atomics](https://github.com/apple/swift-atomics) | 1.3.0 | Apache-2.0 with Runtime Library Exception |+| [swift-collections](https://github.com/apple/swift-collections) | 1.5.1 | Apache-2.0 with Runtime Library Exception |+| [swift-system](https://github.com/apple/swift-system) | 1.6.4 | Apache-2.0 with Runtime Library Exception |+| [swift-crypto](https://github.com/apple/swift-crypto) | 4.5.0 | Apache-2.0; upstream NOTICE applies |+| [swift-asn1](https://github.com/apple/swift-asn1) | 1.7.0 | Apache-2.0; upstream NOTICE applies |+| [yyjson](https://github.com/ibireme/yyjson) | 0.12.0 | MIT |++No copyleft or custom non-commercial license was found in this resolved graph.+The dependency license files remain authoritative. For binary distribution,+collect their license and NOTICE files from the exact revisions in+`Package.resolved`; do not treat this summary as a substitute for that bundle.diff --git a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swiftnew file mode 100644index 00000000..282a64e3--- /dev/null+++ b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift@@ -0,0 +1,89 @@+import Testing+@testable import TurboFieldfareCLICore++@Suite struct CLIArgumentsTests {+ @Test func defaultsUseProductionGenerationValues() throws {+ let arguments = try Args.parse(["--model", "m.gturbo", "--prompt", "hi"])+ #expect(arguments.model == "m.gturbo")+ #expect(arguments.prompt == "hi")+ #expect(arguments.maxNew == 1_024)+ #expect(arguments.maxContext == 4096)+ #expect(arguments.temperature == 0.1)+ #expect(arguments.topK == 64)+ #expect(arguments.topP == 0.95)+ #expect(arguments.repetitionPenalty == 1)+ #expect(arguments.seed == nil)+ #expect(arguments.stops.isEmpty)+ #expect(!arguments.quiet)+ }++ @Test func generationOptionsParseAndStopsRepeat() throws {+ let arguments = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi",+ "--max-new", "32", "--max-context", "512",+ "--temperature", "0", "--top-k", "40", "--top-p", "0.95",+ "--repetition-penalty", "1.1", "--seed", "42",+ "--stop", "A", "--stop", "B", "--quiet",+ ])+ #expect(arguments.maxNew == 32)+ #expect(arguments.maxContext == 512)+ #expect(arguments.temperature == 0)+ #expect(arguments.topK == 40)+ #expect(arguments.topP == 0.95)+ #expect(arguments.repetitionPenalty == 1.1)+ #expect(arguments.seed == 42)+ #expect(arguments.stops == ["A", "B"])+ #expect(arguments.quiet)+ }++ @Test func topKZeroRequiresTopPToBeDisabled() throws {+ let disabled = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi",+ "--top-k", "0", "--top-p", "1",+ ])+ #expect(disabled.topK == nil)+ #expect(disabled.topP == 1)++ #expect(throws: ArgsError.self) {+ _ = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi", "--top-k", "0",+ ])+ }+ }++ @Test func topKAboveKernelLimitRejected() {+ #expect(throws: ArgsError.invalidValue(flag: "--top-k", value: "257")) {+ _ = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi", "--top-k", "257",+ ])+ }+ }++ @Test func helpListsExactlyThePublicOptions() {+ let expected: Set<String> = [+ "--model", "--prompt", "--max-new", "--max-context",+ "--temperature", "--top-k", "--top-p", "--repetition-penalty",+ "--seed", "--stop", "--quiet", "--help",+ ]+ let words = Args.usage.split { $0.isWhitespace || $0 == "(" || $0 == ")" }+ let options = Set(words.map(String.init).filter { $0.hasPrefix("--") })+ #expect(options == expected)+ }++ @Test func unsupportedSelectorsAreRejected() {+ for flag in ["--messages-file", "--runtime-profile", "--experiment-id", "-h"] {+ #expect(throws: ArgsError.unknownFlag(flag)) {+ _ = try Args.parse(["--model", "m.gturbo", "--prompt", "hi", flag])+ }+ }+ }++ @Test func modelAndPromptAreRequired() {+ #expect(throws: ArgsError.requiredMissing("--model")) {+ _ = try Args.parse(["--prompt", "hi"])+ }+ #expect(throws: ArgsError.requiredMissing("--prompt")) {+ _ = try Args.parse(["--model", "m.gturbo"])+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ManifestReaderTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ManifestReaderTests.swiftnew file mode 100644index 00000000..1a55d0ff--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ManifestReaderTests.swift@@ -0,0 +1,234 @@+import Testing+import Foundation+@testable import TurboFieldfare++@Suite struct ManifestReaderTests {++ /// Build a manifest dictionary for a 2-layer toy ArchConfig and write it+ /// into a temp directory. Returns the directory URL and the toy config.+ static func writeToyManifest(_ overrides: [String: Any] = [:],+ flags: [String: Bool] = ["streamingPresent": true,+ "turboQuantKV": false,+ "aneSharedExpert": false],+ archOverrides: [String: Any] = [:],+ filesOverride: [String: [String: Any]]? = nil) throws+ -> (URL, ArchConfig) {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-manifest-test-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: dir.appendingPathComponent("packed_experts"),+ withIntermediateDirectories: true)++ let toy = ArchConfig.gemma4Toy()+ var archDict: [String: Any] = [+ "hiddenSize": toy.hiddenSize,+ "ffnIntermediate": toy.intermediateSize,+ "moeIntermediateSize": toy.moeIntermediateSize,+ "numHeads": toy.numHeads,+ "numKVHeads": toy.numKVHeads,+ "numFullKVHeads": toy.numFullKVHeads,+ "headDim": toy.headDim,+ "fullHeadDim": toy.fullHeadDim,+ "vocabSize": toy.vocabSize,+ "slidingWindow": toy.slidingWindow,+ "finalLogitSoftcap": toy.finalLogitSoftcap,+ "ropeTheta": toy.ropeTheta,+ "fullRopeTheta": toy.fullRopeTheta,+ "partialRotaryFactor": toy.partialRotaryFactor,+ "numLayers": toy.numLayers,+ "numExperts": toy.numExperts,+ "topKExperts": toy.topKExperts,+ "tieWordEmbeddings": toy.tieWordEmbeddings,+ "attentionKEqV": toy.attentionKEqV,+ "hiddenActivation": toy.hiddenActivation,+ "fullAttentionLayerMask": toy.fullAttentionLayerMask.map { Int($0) },+ ]+ for (k, v) in archOverrides { archDict[k] = v }++ var files: [String: [String: Any]]+ if let f = filesOverride {+ files = f+ } else {+ files = [+ "model_weights.bin": ["size": 1024, "sha256": String(repeating: "0", count: 64)],+ "packed_experts/layout.json": ["size": 1024, "sha256": String(repeating: "0", count: 64)],+ ]+ for L in 0..<toy.numLayers {+ files["packed_experts/layer_\(L).bin"] = ["size": 16384, "sha256": String(repeating: "0", count: 64)]+ }+ }++ var root: [String: Any] = [+ "magic": "GTURBO",+ "versionMajor": 1,+ "versionMinor": 0,+ "flags": flags,+ "modelID": "toy",+ "arch": archDict,+ "files": files,+ "expertsPerLayer": toy.numExperts,+ "numLayers": toy.numLayers,+ "expertStride": 16384,+ ]+ for (k, v) in overrides { root[k] = v }++ let data = try JSONSerialization.data(withJSONObject: root,+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])+ try data.write(to: dir.appendingPathComponent("manifest.json"))+ return (dir, toy)+ }++ @Test func loadsValidManifest() throws {+ let (dir, toy) = try Self.writeToyManifest()+ defer { try? FileManager.default.removeItem(at: dir) }+ let m = try ManifestReader.load(directoryURL: dir, expecting: toy)+ #expect(m.magic == "GTURBO")+ #expect(m.numLayers == toy.numLayers)+ #expect(m.expertStride == 16384)+ }++ @Test func missingManifestThrowsPartialInstall() throws {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-empty-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: .gemma4Toy())+ } throws: { error in+ if case ModelError.partialInstall = error { return true }+ return false+ }+ }++ @Test func oversizedManifestRejectsBeforeDecode() throws {+ let (dir, toy) = try Self.writeToyManifest()+ defer { try? FileManager.default.removeItem(at: dir) }+ let manifestURL = dir.appendingPathComponent("manifest.json")+ try Data(repeating: 0x20, count: 64).write(to: manifestURL)++ #expect {+ _ = try ManifestReader.load(directoryURL: dir,+ expecting: toy,+ maxBytes: 16)+ } throws: { error in+ if case ModelError.indexCorrupt(let detail) = error {+ return detail.contains("metadata cap")+ }+ return false+ }+ }++ @Test func wrongMagicThrowsNotAGTurboDirectory() throws {+ let (dir, toy) = try Self.writeToyManifest(["magic": "NOT_GTURBO"])+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect(throws: ModelError.notAGTurboDirectory) {+ _ = try ManifestReader.load(directoryURL: dir, expecting: toy)+ }+ }++ @Test func versionTwoThrowsUnsupportedVersion() throws {+ let (dir, toy) = try Self.writeToyManifest(["versionMajor": 2])+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: toy)+ } throws: { error in+ if case ModelError.unsupportedVersion(let maj, _) = error { return maj == 2 }+ return false+ }+ }++ @Test func unknownFlagThrowsUnknownFlag() throws {+ let (dir, toy) = try Self.writeToyManifest(flags: ["streamingPresent": true,+ "newFangledOption": true])+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: toy)+ } throws: { error in+ if case ModelError.unknownFlag(let n) = error { return n == "newFangledOption" }+ return false+ }+ }++ @Test func archMismatchThrowsArchMismatch() throws {+ let (dir, toy) = try Self.writeToyManifest(archOverrides: ["hiddenSize": 4096])+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: toy)+ } throws: { error in+ guard case let ModelError.archMismatch(field, _, _) = error else { return false }+ return field == "hiddenSize"+ }+ }++ @Test func nonPageAlignedExpertStrideThrows() throws {+ let (dir, toy) = try Self.writeToyManifest(["expertStride": 1024])+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: toy)+ } throws: { error in+ if case ModelError.expertStrideNotPageAligned = error { return true }+ return false+ }+ }++ @Test func missingLayerFileThrowsMissingFile() throws {+ let files: [String: [String: Any]] = [+ "model_weights.bin": ["size": 1024, "sha256": String(repeating: "0", count: 64)],+ "packed_experts/layout.json": ["size": 1024, "sha256": String(repeating: "0", count: 64)],+ // intentionally do not list layer_0.bin or layer_1.bin+ ]+ let (dir, toy) = try Self.writeToyManifest(filesOverride: files)+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: toy)+ } throws: { error in+ if case ModelError.missingFile = error { return true }+ return false+ }+ }++ @Test func acceptsZeroPaddedLayerFilenames() throws {+ // Writer emits packed_experts/layer_%02d.bin; loader should accept either form.+ let files: [String: [String: Any]] = [+ "model_weights.bin": ["size": 1024, "sha256": String(repeating: "0", count: 64)],+ "packed_experts/layout.json": ["size": 1024, "sha256": String(repeating: "0", count: 64)],+ "packed_experts/layer_00.bin": ["size": 16384, "sha256": String(repeating: "0", count: 64)],+ "packed_experts/layer_01.bin": ["size": 16384, "sha256": String(repeating: "0", count: 64)],+ ]+ let (dir, toy) = try Self.writeToyManifest(filesOverride: files)+ defer { try? FileManager.default.removeItem(at: dir) }+ let m = try ManifestReader.load(directoryURL: dir, expecting: toy)+ #expect(m.numLayers == toy.numLayers)+ }+}++extension ArchConfig {+ /// Tiny baseline used across the loader tests. 2 layers (both full), hidden 64,+ /// vocab 1024, 8 experts. Numbers are intentionally toy.+ static func gemma4Toy() -> ArchConfig {+ ArchConfig(+ hiddenSize: 64,+ intermediateSize: 256,+ moeIntermediateSize: 128,+ numHeads: 4,+ numKVHeads: 2,+ numFullKVHeads: 1,+ headDim: 16,+ fullHeadDim: 32,+ vocabSize: 1024,+ slidingWindow: 256,+ finalLogitSoftcap: 30.0,+ ropeTheta: 10_000.0,+ fullRopeTheta: 1_000_000.0,+ partialRotaryFactor: 0.25,+ numLayers: 2,+ numExperts: 8,+ topKExperts: 2,+ tieWordEmbeddings: true,+ attentionKEqV: true,+ fullAttentionLayerMask: [0, 1],+ hiddenActivation: "gelu_pytorch_tanh"+ )+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderPreadTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderPreadTests.swiftnew file mode 100644index 00000000..1e57fdbc--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderPreadTests.swift@@ -0,0 +1,67 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare++/// `Model.load(streamingMode:)` integration for the bounded pread cache.+@Suite struct ModelLoaderPreadTests {++ private static func readBytes(_ view: TensorView) -> [UInt8] {+ let base = view.buffer.contents().advanced(by: Int(view.offset))+ return [UInt8](UnsafeRawBufferPointer(start: base, count: Int(view.length)))+ }++ @Test func loadsUnderPread_routedExpertBytesAndLazyOpen() throws {+ let dir = try ModelLoaderTests.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(directoryURL: dir, device: device,+ expecting: .gemma4Toy(),+ streamingMode: .pread(slotCount: 2))++ #expect(model.openLayerFileCount() == 0)+ let view = try model.routedExpert(layer: 1, expert: 4)+ #expect(model.openLayerFileCount() == 1)++ // pread returns the scratch slot: offset is 0, not exp.offset.+ #expect(view.offset == 0)++ // Same tagged-byte contract as ModelLoaderTests.routedExpertBytesRoundTrip.+ let b = Self.readBytes(view)+ #expect(b[0] == 1) // layer 1+ #expect(b[1] == 4) // expert 4+ #expect(b[2] == 0xC1)+ #expect(b[3] == 0xC2)+ }++ @Test func routedExpertCacheSlotCountDoesNotOpenLayerFile() throws {+ let dir = try ModelLoaderTests.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(directoryURL: dir, device: device,+ expecting: .gemma4Toy(),+ streamingMode: .pread(slotCount: 2))++ #expect(model.openLayerFileCount() == 0)+ #expect(model.routedExpertCacheSlotCount(layer: 1) == 2)+ #expect(model.openLayerFileCount() == 0)+ }++ @Test func beginOpeningRoutedExpertStreamerIsCompatibleWithLazyFetch() throws {+ let dir = try ModelLoaderTests.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(directoryURL: dir, device: device,+ expecting: .gemma4Toy(),+ streamingMode: .pread(slotCount: 2))++ model.beginOpeningRoutedExpertStreamer(layer: 1)+ let view = try model.routedExpert(layer: 1, expert: 4)++ #expect(model.openLayerFileCount() == 1)+ let b = Self.readBytes(view)+ #expect(b[0] == 1)+ #expect(b[1] == 4)+ }++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+LazyStreaming.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+LazyStreaming.swiftnew file mode 100644index 00000000..63811d5a--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+LazyStreaming.swift@@ -0,0 +1,71 @@+import Foundation+import Metal+import Testing++@testable import TurboFieldfare++extension ModelLoaderTests {+ @Test func touchingOneLayerOpensExactlyOneStreamer() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())+ #expect(model.openLayerFileCount() == 0)+ _ = try model.routedExpert(layer: 0, expert: 3)+ #expect(model.openLayerFileCount() == 1)+ // Touch layer 0 again — no new open.+ _ = try model.routedExpert(layer: 0, expert: 5)+ #expect(model.openLayerFileCount() == 1)+ // Touch layer 1 — second open.+ _ = try model.routedExpert(layer: 1, expert: 0)+ #expect(model.openLayerFileCount() == 2)+ }++ @Test func routedExpertBytesRoundTrip() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())+ let view = try model.routedExpert(layer: 1, expert: 4)+ let bufContents = view.buffer.contents()+ let b0 = bufContents.load(fromByteOffset: Int(view.offset), as: UInt8.self)+ let b1 = bufContents.load(fromByteOffset: Int(view.offset) + 1, as: UInt8.self)+ let b2 = bufContents.load(fromByteOffset: Int(view.offset) + 2, as: UInt8.self)+ let b3 = bufContents.load(fromByteOffset: Int(view.offset) + 3, as: UInt8.self)+ #expect(b0 == 1) // layer 1+ #expect(b1 == 4) // expert 4+ #expect(b2 == 0xC1)+ #expect(b3 == 0xC2)+ }++ @Test func tamperedLayerFileFailsOnFirstTouch() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())++ // Flip one byte inside layer_01.bin AFTER the manifest is written.+ let url = dir.appendingPathComponent("packed_experts/layer_01.bin")+ var data = try Data(contentsOf: url)+ data[100] ^= 0xFF+ try data.write(to: url)++ // Layer 0 still loads.+ _ = try model.routedExpert(layer: 0, expert: 0)+ // Layer 1 first touch fails with checksumMismatch.+ #expect {+ _ = try model.routedExpert(layer: 1, expert: 0)+ } throws: { error in+ if case ModelError.checksumMismatch(let f) = error {+ return f == "packed_experts/layer_01.bin"+ }+ return false+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+Loading.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+Loading.swiftnew file mode 100644index 00000000..67656577--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+Loading.swift@@ -0,0 +1,128 @@+import Foundation+import Metal+import Testing++@testable import TurboFieldfare++extension ModelLoaderTests {+ @Test func loadsValidDirectory() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())+ let embed = model.embedding+ #expect(embed.length == UInt64(1024 * 64))+ #expect(embed.shape.0 == 1024 && embed.shape.1 == 64)+ let norm = model.finalNorm+ #expect(norm.length == UInt64(64 * 2))+ // Tied lm_head returns the same view as embedding.+ #expect(model.lmHead.offset == model.embedding.offset)+ #expect(model.lmHead.length == model.embedding.length)+ }++ @Test func residentBytesAreReadableFromBuffer() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())+ let norm = model.finalNorm+ let contents = norm.buffer.contents()+ // Norm region was patterned 0xC0 | (i & 0x3F).+ for i in 0..<Int(norm.length) {+ let got = contents.load(fromByteOffset: Int(norm.offset) + i, as: UInt8.self)+ #expect(got == UInt8(0xC0 | (i & 0x3F)), "norm byte \(i)")+ }+ }++ @Test func missingManifestFailsPartialInstall() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try FileManager.default.removeItem(at: dir.appendingPathComponent("manifest.json"))+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())+ } throws: { error in+ if case ModelError.partialInstall = error { return true }+ return false+ }+ }++ @Test func mismatchedShaFailsChecksumMismatch() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ // Flip one byte at the very end of the resident region (not inside+ // the index, which the loader reads earlier and would error+ // differently). Manifest sha was computed before this corruption.+ let url = dir.appendingPathComponent("model_weights.bin")+ var data = try Data(contentsOf: url)+ data[data.count - 1] ^= 0xFF+ try data.write(to: url)+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())+ } throws: { error in+ if case ModelError.checksumMismatch = error { return true }+ return false+ }+ }++ @Test func integrityPoliciesExposeIdenticalResidentAndRoutedBytes() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ let device = try #require(MTLCreateSystemDefaultDevice())+ let full = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .fullSha256)+ let trusted = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)++ #expect(full.embedding.length == trusted.embedding.length)+ let fullEmbedding = full.embedding.buffer.contents().advanced(by: Int(full.embedding.offset))+ let trustedEmbedding = trusted.embedding.buffer.contents().advanced(+ by: Int(trusted.embedding.offset))+ #expect(memcmp(fullEmbedding, trustedEmbedding, Int(full.embedding.length)) == 0)++ let fullExpert = try full.routedExpert(layer: 0, expert: 0)+ let trustedExpert = try trusted.routedExpert(layer: 0, expert: 0)+ #expect(fullExpert.length == trustedExpert.length)+ let fullExpertBytes = fullExpert.buffer.contents().advanced(by: Int(fullExpert.offset))+ let trustedExpertBytes = trustedExpert.buffer.contents().advanced(by: Int(trustedExpert.offset))+ #expect(memcmp(fullExpertBytes, trustedExpertBytes, Int(fullExpert.length)) == 0)+ }++ @Test func nonPageAlignedExpertStrideFailsAtManifest() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let manifestURL = dir.appendingPathComponent("manifest.json")+ var root =+ try JSONSerialization.jsonObject(+ with: Data(contentsOf: manifestURL)) as! [String: Any]+ root["expertStride"] = 1024+ let data = try JSONSerialization.data(withJSONObject: root)+ try data.write(to: manifestURL)+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir, device: device,+ expecting: .gemma4Toy())+ } throws: { error in+ if case ModelError.expertStrideNotPageAligned = error { return true }+ return false+ }+ }++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+TrustedReceipt.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+TrustedReceipt.swiftnew file mode 100644index 00000000..f5e53a71--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests+TrustedReceipt.swift@@ -0,0 +1,213 @@+import Foundation+import Metal+import Testing++@testable import TurboFieldfare++extension ModelLoaderTests {+ @Test func trustedReceiptModeRequiresReceipt() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)+ } throws: { error in+ if case ModelError.trustedReceiptInvalid = error { return true }+ return false+ }+ }++ @Test func trustedReceiptReaderRejectsOversizedMetadataBeforeDecode() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)++ #expect {+ _ = try VerifiedInstallReceiptReader.load(directoryURL: dir, maxBytes: 16)+ } throws: { error in+ if case ModelError.trustedReceiptInvalid(let detail) = error {+ return detail.contains("metadata cap")+ }+ return false+ }+ }++ @Test func trustedReceiptModeSkipsSameSizeLayerShaMismatch() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ let layerURL =+ dir+ .appendingPathComponent("packed_experts")+ .appendingPathComponent("layer_00.bin")+ try Self.flipByte(in: layerURL, at: 64)+ let device = try #require(MTLCreateSystemDefaultDevice())++ #expect {+ let defaultModel = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy())+ _ = try defaultModel.routedExpert(layer: 0, expert: 0)+ } throws: { error in+ if case ModelError.checksumMismatch = error { return true }+ return false+ }++ let trustedModel = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)+ _ = try trustedModel.routedExpert(layer: 0, expert: 0)+ }++ @Test func trustedReceiptModeRejectsWrongSizedLayerFile() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ let layerURL =+ dir+ .appendingPathComponent("packed_experts")+ .appendingPathComponent("layer_00.bin")+ let handle = try FileHandle(forWritingTo: layerURL)+ try handle.truncate(atOffset: 1024)+ try handle.close()++ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)+ } throws: { error in+ if case ModelError.trustedReceiptInvalid = error { return true }+ return false+ }+ }++ @Test func trustedReceiptModeReportsReceiptValidationTiming() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ let device = try #require(MTLCreateSystemDefaultDevice())+ var stats = ModelLoadStats()+ _ = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt,+ loadStats: &stats)+ #expect(stats.manifestSha256Nanos > 0)+ #expect(stats.receiptValidationNanos > 0)+ #expect(stats.eagerSha256Nanos > 0)+ }++ @Test func trustedReceiptModeRejectsExtraReceiptFileEntry() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ try Self.mutateReceipt(directoryURL: dir) { root in+ var files = root["files"] as! [String: Any]+ files["unexpected.bin"] = ["size": 0, "sha256": String(repeating: "0", count: 64)]+ root["files"] = files+ }+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)+ } throws: { error in+ if case ModelError.trustedReceiptInvalid = error { return true }+ return false+ }+ }++ @Test func trustedReceiptModeRejectsMissingReceiptFileEntry() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ try Self.mutateReceipt(directoryURL: dir) { root in+ var files = root["files"] as! [String: Any]+ files.removeValue(forKey: "packed_experts/layer_00.bin")+ root["files"] = files+ }+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)+ } throws: { error in+ if case ModelError.trustedReceiptInvalid(let detail) = error {+ return detail.contains("file set mismatch")+ && detail.contains("packed_experts/layer_00.bin")+ }+ return false+ }+ }++ @Test func trustedReceiptModeRejectsStaleManifestBindingBeforeManifestTrust() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ try Self.mutateReceipt(directoryURL: dir) { root in+ root["manifestSha256"] = String(repeating: "0", count: 64)+ var files = root["files"] as! [String: Any]+ files["manifest.json"] = [+ "size": (files["manifest.json"] as! [String: Any])["size"]!,+ "sha256": String(repeating: "0", count: 64),+ ]+ root["files"] = files+ }+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)+ } throws: { error in+ if case ModelError.trustedReceiptInvalid(let detail) = error {+ return detail.contains("manifest SHA mismatch")+ }+ return false+ }+ }++ @Test func trustedReceiptModeRejectsDifferentModelDirectoryBinding() throws {+ let dir = try Self.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ try Self.writeVerifiedInstallReceipt(directoryURL: dir)+ try Self.mutateReceipt(directoryURL: dir) { root in+ root["modelDirectoryPath"] =+ dir+ .deletingLastPathComponent()+ .appendingPathComponent("other.gturbo")+ .standardizedFileURL+ .path+ }+ let device = try #require(MTLCreateSystemDefaultDevice())+ #expect {+ _ = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ integrityPolicy: .sizeCheckTrustedReceipt)+ } throws: { error in+ if case ModelError.trustedReceiptInvalid(let detail) = error {+ return detail.contains("model directory mismatch")+ }+ return false+ }+ }++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests.swiftnew file mode 100644index 00000000..5f041e41--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderTests.swift@@ -0,0 +1,496 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+@testable import TurboFieldfareRepackCore++@Suite struct ModelLoaderTests {+ static func dummySource(_ name: String) -> SourceTensor {+ SourceTensor(name: name, shardPath: "/dev/null", dtype: .u32,+ shape: [1024, 64], absoluteOffset: 0, sizeBytes: 0)+ }++ /// Build a minimal valid `model.gturbo/` directory in a temp dir and+ /// return the URL. Uses the toy ArchConfig `gemma4Toy()`: 2 layers,+ /// 8 experts, hidden 64, vocab 1024. Resident contains the embedding+ /// (alias: lmHead), final norm, and the tiny layer-resident tensors needed+ /// to construct `RealForwardRunner` in unit tests.+ static func writeToySynthetic() throws -> URL {+ let toy = ArchConfig.gemma4Toy()+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-toy-\(UUID().uuidString)")+ let exp = dir.appendingPathComponent("packed_experts")+ try FileManager.default.createDirectory(at: exp, withIntermediateDirectories: true)++ // 1. Resident region: embedding + final norm + runner-init tensors.+ struct ResidentSpec {+ let name: String+ let dtype: UInt8+ let shape: [UInt32]+ let weightBytes: UInt64+ let scaleBytes: UInt64+ let biasBytes: UInt64+ }++ let d = toy.hiddenSize+ let f = toy.intermediateSize+ let embedSize = UInt64(toy.vocabSize * toy.hiddenSize)+ let bf16DBytes = UInt64(d * MemoryLayout<UInt16>.stride)++ func int4AffineSpec(_ name: String, rows: Int, cols: Int) -> ResidentSpec {+ let groups = (cols + Quantization.groupSize - 1) / Quantization.groupSize+ let auxBytes = UInt64(rows * groups * MemoryLayout<UInt16>.stride)+ return ResidentSpec(name: name,+ dtype: 0,+ shape: [UInt32(rows), UInt32(cols), 0, 0],+ weightBytes: UInt64(rows * cols),+ scaleBytes: auxBytes,+ biasBytes: auxBytes)+ }++ func appendU16(_ values: [UInt16], to bytes: inout [UInt8]) {+ for value in values {+ bytes.append(UInt8(truncatingIfNeeded: value))+ bytes.append(UInt8(truncatingIfNeeded: value >> 8))+ }+ }++ func toyExpertRows(rows: Int, cols: Int, expert: Int, role: Int) -> [[Float]] {+ (0..<rows).map { row in+ (0..<cols).map { col in+ Float(expert + 1) * 0.001+ + Float(role + 1) * 0.003+ + Float((row % 7) - 3) * 0.0004+ + Float((col % 11) - 5) * 0.0002+ }+ }+ }++ func appendProjection(rows: [[Float]], to bytes: inout [UInt8], component: String) {+ let quantized = rows.map { Quantization.quantizeInt4Affine($0) }+ switch component {+ case "packed":+ for row in quantized { bytes.append(contentsOf: row.packed) }+ case "scales":+ for row in quantized { appendU16(row.scales, to: &bytes) }+ case "biases":+ for row in quantized { appendU16(row.biases, to: &bytes) }+ default:+ preconditionFailure("unknown projection component \(component)")+ }+ }++ func toyExpertBlob(expert: Int) -> (bytes: [UInt8], tensors: [String: [String: Any]]) {+ var bytes: [UInt8] = []+ var tensors: [String: [String: Any]] = [:]++ func addProjection(prefix: String, rows: Int, cols: Int, role: Int) {+ let projectionRows = toyExpertRows(rows: rows, cols: cols, expert: expert, role: role)+ let packedOffset = bytes.count+ appendProjection(rows: projectionRows, to: &bytes, component: "packed")+ tensors[prefix] = [+ "offset": packedOffset, "size": bytes.count - packedOffset,+ "dtype": "U32", "shape": [rows, cols],+ "bits": 4,+ ]+ let scalesOffset = bytes.count+ appendProjection(rows: projectionRows, to: &bytes, component: "scales")+ tensors["\(prefix)_scales"] = [+ "offset": scalesOffset, "size": bytes.count - scalesOffset,+ "dtype": "BF16", "shape": [rows, cols / Quantization.groupSize],+ ]+ let biasesOffset = bytes.count+ appendProjection(rows: projectionRows, to: &bytes, component: "biases")+ tensors["\(prefix)_biases"] = [+ "offset": biasesOffset, "size": bytes.count - biasesOffset,+ "dtype": "BF16", "shape": [rows, cols / Quantization.groupSize],+ ]+ }++ addProjection(prefix: "gate", rows: toy.moeIntermediateSize, cols: d, role: 0)+ addProjection(prefix: "up", rows: toy.moeIntermediateSize, cols: d, role: 1)+ addProjection(prefix: "down", rows: d, cols: toy.moeIntermediateSize, role: 2)+ return (bytes, tensors)+ }++ var specs: [ResidentSpec] = [+ ResidentSpec(name: "language_model.model.embed_tokens.weight",+ dtype: 0,+ shape: [UInt32(toy.vocabSize), UInt32(toy.hiddenSize), 0, 0],+ weightBytes: embedSize,+ scaleBytes: UInt64(toy.vocabSize * (d / Quantization.groupSize) * MemoryLayout<UInt16>.stride),+ biasBytes: UInt64(toy.vocabSize * (d / Quantization.groupSize) * MemoryLayout<UInt16>.stride)),+ ResidentSpec(name: "language_model.model.norm.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0),+ ]+ for L in 0..<toy.numLayers {+ let isFull = toy.fullAttentionLayerMask[L] != 0+ let headDim = isFull ? toy.fullHeadDim : toy.headDim+ let numKVHeads = isFull ? toy.numFullKVHeads : toy.numKVHeads+ let qDim = toy.numHeads * headDim+ let kvDim = numKVHeads * headDim+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).input_layernorm.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).self_attn.q_proj.weight",+ rows: qDim,+ cols: d))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).self_attn.k_proj.weight",+ rows: kvDim,+ cols: d))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).self_attn.v_proj.weight",+ rows: kvDim,+ cols: d))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).self_attn.o_proj.weight",+ rows: d,+ cols: qDim))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).post_attention_layernorm.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).pre_feedforward_layernorm.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).pre_feedforward_layernorm_2.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).self_attn.q_norm.weight",+ dtype: 1,+ shape: [UInt32(headDim), 0, 0, 0],+ weightBytes: UInt64(headDim * MemoryLayout<UInt16>.stride),+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).self_attn.k_norm.weight",+ dtype: 1,+ shape: [UInt32(headDim), 0, 0, 0],+ weightBytes: UInt64(headDim * MemoryLayout<UInt16>.stride),+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).mlp.gate_proj.weight",+ rows: f,+ cols: d))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).mlp.up_proj.weight",+ rows: f,+ cols: d))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).mlp.down_proj.weight",+ rows: d,+ cols: f))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).post_feedforward_layernorm_1.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).post_feedforward_layernorm_2.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).post_feedforward_layernorm.weight",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).layer_scalar",+ dtype: 1,+ shape: [1, 0, 0, 0],+ weightBytes: UInt64(MemoryLayout<UInt16>.stride),+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).router.scale",+ dtype: 1,+ shape: [UInt32(toy.hiddenSize), 0, 0, 0],+ weightBytes: bf16DBytes,+ scaleBytes: 0,+ biasBytes: 0))+ specs.append(int4AffineSpec(+ "language_model.model.layers.\(L).router.proj.weight",+ rows: toy.numExperts,+ cols: d))+ specs.append(ResidentSpec(+ name: "language_model.model.layers.\(L).router.per_expert_scale",+ dtype: 1,+ shape: [UInt32(toy.numExperts), 0, 0, 0],+ weightBytes: UInt64(toy.numExperts * MemoryLayout<UInt16>.stride),+ scaleBytes: 0,+ biasBytes: 0))+ }++ let names = specs.map(\.name)+ let stringTable = names.joined().data(using: .utf8)!+ let headerBytes = GTurboBinary.indexHeaderBytes+ let entryBytes = GTurboBinary.indexEntryBytes+ let entriesBase = headerBytes+ let stringTableBase = entriesBase + names.count * entryBytes+ var nameAbsOffsets: [UInt32] = []+ var cursor = 0+ for n in names {+ nameAbsOffsets.append(UInt32(stringTableBase + cursor))+ cursor += n.utf8.count+ }+ let indexBytes = UInt64(stringTableBase + stringTable.count)++ var entries: [ResidentEntry] = []+ entries.reserveCapacity(specs.count)+ var payloadCursor = indexBytes+ for spec in specs {+ let weightOffset = payloadCursor+ let scaleOffset = spec.scaleBytes > 0 ? weightOffset + spec.weightBytes : 0+ let biasOffset = spec.biasBytes > 0 ? scaleOffset + spec.scaleBytes : 0+ entries.append(ResidentEntry(+ name: spec.name,+ dtype: spec.dtype,+ logicalShape4: spec.shape,+ fileOffset: weightOffset,+ sizeBytes: spec.weightBytes,+ scaleOffset: scaleOffset,+ scaleSize: spec.scaleBytes,+ biasOffset: biasOffset,+ biasSize: spec.biasBytes,+ quantSpec: nil,+ sourceWeight: Self.dummySource(spec.name),+ sourceScales: nil,+ sourceBiases: nil))+ payloadCursor += spec.weightBytes + spec.scaleBytes + spec.biasBytes+ }+ let residentSize = payloadCursor - indexBytes++ let totalBytes = Int(indexBytes + residentSize)+ var fileBuf = [UInt8](repeating: 0, count: totalBytes)+ fileBuf.withUnsafeMutableBytes { raw in+ let base = raw.baseAddress!+ GTurboBinary.writeIndexHeader(into: base,+ indexSize: indexBytes,+ residentSize: residentSize,+ entryCount: UInt64(entries.count))+ for (i, e) in entries.enumerated() {+ let dst = base.advanced(by: entriesBase + i * entryBytes)+ GTurboBinary.writeIndexEntry(into: dst, entry: e,+ nameOffset: nameAbsOffsets[i])+ }+ _ = stringTable.withUnsafeBytes { sb in+ memcpy(base.advanced(by: stringTableBase), sb.baseAddress!, stringTable.count)+ }+ // Recognizable resident payload pattern in the norm region only;+ // other payload bytes stay zero except router.scale unit BF16s.+ let normStart = Int(entries[1].fileOffset)+ for i in 0..<Int(entries[1].sizeBytes) {+ base.advanced(by: normStart + i)+ .assumingMemoryBound(to: UInt8.self)[0] = UInt8(0xC0 | (i & 0x3F))+ }+ for entry in entries where entry.dtype == 0 {+ memset(base.advanced(by: Int(entry.fileOffset)), 0x11, Int(entry.sizeBytes))+ if entry.scaleSize > 0 {+ let scales = base.advanced(by: Int(entry.scaleOffset))+ .assumingMemoryBound(to: UInt16.self)+ for i in 0..<(Int(entry.scaleSize) / MemoryLayout<UInt16>.stride) {+ scales[i] = Quantization.bf16Bits(0.01)+ }+ }+ }+ for entry in entries where entry.dtype == 1 && entry.name != "language_model.model.norm.weight" {+ let dst = base.advanced(by: Int(entry.fileOffset))+ .assumingMemoryBound(to: UInt16.self)+ for i in 0..<(Int(entry.sizeBytes) / MemoryLayout<UInt16>.stride) {+ dst[i] = Quantization.bf16Bits(1.0)+ }+ }+ }+ let weightsURL = dir.appendingPathComponent("model_weights.bin")+ try Data(fileBuf).write(to: weightsURL)+ let weightsSha = try Sha256Verifier.hashFile(at: weightsURL)++ // 2. packed_experts: 2 layer files, each `expertsPerLayer * expertStride`+ // bytes. expertStride must be a multiple of getpagesize() (16 KB).+ let expertStride: UInt64 = 16384+ let layerBytes = Int(expertStride) * toy.numExperts+ for L in 0..<toy.numLayers {+ var payload = Data(count: layerBytes)+ for E in 0..<toy.numExperts {+ let blob = toyExpertBlob(expert: E).bytes+ let baseB = E * Int(expertStride)+ precondition(blob.count <= Int(expertStride),+ "toy expert blob exceeds stride")+ for (i, byte) in blob.enumerated() {+ payload[baseB + i] = byte+ }+ // Tag bytes outside the projection region so the round-trip+ // test can identify which blob is being read.+ payload[baseB + 0] = UInt8(L)+ payload[baseB + 1] = UInt8(E)+ payload[baseB + 2] = 0xC1+ payload[baseB + 3] = 0xC2+ }+ let url = exp.appendingPathComponent(String(format: "layer_%02d.bin", L))+ try payload.write(to: url)+ }+ var layerShaByName: [String: String] = [:]+ for L in 0..<toy.numLayers {+ let basename = String(format: "layer_%02d.bin", L)+ let url = exp.appendingPathComponent(basename)+ layerShaByName["packed_experts/\(basename)"] = try Sha256Verifier.hashFile(at: url)+ }++ // 3. layout.json+ var layersArr: [[String: Any]] = []+ for L in 0..<toy.numLayers {+ var experts: [[String: Any]] = []+ for E in 0..<toy.numExperts {+ let blob = toyExpertBlob(expert: E)+ experts.append([+ "expert": E,+ "offset": UInt64(E) * expertStride,+ "size": expertStride,+ "tensors": blob.tensors,+ ])+ }+ layersArr.append([+ "layer": L,+ "file": String(format: "layer_%02d.bin", L),+ "experts": experts,+ ])+ }+ let layoutRoot: [String: Any] = [+ "expertStride": expertStride,+ "numLayers": toy.numLayers,+ "expertsPerLayer": toy.numExperts,+ "layers": layersArr,+ ]+ let layoutData = try JSONSerialization.data(+ withJSONObject: layoutRoot, options: [.sortedKeys])+ let layoutURL = exp.appendingPathComponent("layout.json")+ try layoutData.write(to: layoutURL)+ let layoutSha = try Sha256Verifier.hashFile(at: layoutURL)++ // 4. manifest.json+ var files: [String: [String: Any]] = [+ "model_weights.bin": ["size": Int(totalBytes), "sha256": weightsSha],+ "packed_experts/layout.json": ["size": layoutData.count, "sha256": layoutSha],+ ]+ for (rel, sha) in layerShaByName {+ files[rel] = ["size": layerBytes, "sha256": sha]+ }++ let archDict: [String: Any] = [+ "hiddenSize": toy.hiddenSize, "ffnIntermediate": toy.intermediateSize,+ "moeIntermediateSize": toy.moeIntermediateSize,+ "numHeads": toy.numHeads, "numKVHeads": toy.numKVHeads,+ "numFullKVHeads": toy.numFullKVHeads,+ "headDim": toy.headDim, "fullHeadDim": toy.fullHeadDim,+ "vocabSize": toy.vocabSize, "slidingWindow": toy.slidingWindow,+ "finalLogitSoftcap": toy.finalLogitSoftcap,+ "ropeTheta": toy.ropeTheta, "fullRopeTheta": toy.fullRopeTheta,+ "partialRotaryFactor": toy.partialRotaryFactor,+ "numLayers": toy.numLayers, "numExperts": toy.numExperts,+ "topKExperts": toy.topKExperts,+ "tieWordEmbeddings": toy.tieWordEmbeddings,+ "attentionKEqV": toy.attentionKEqV,+ "hiddenActivation": toy.hiddenActivation,+ "fullAttentionLayerMask": toy.fullAttentionLayerMask.map { Int($0) },+ ]+ let manifestRoot: [String: Any] = [+ "magic": "GTURBO",+ "versionMajor": 1,+ "versionMinor": 0,+ "flags": ["streamingPresent": true, "turboQuantKV": false, "aneSharedExpert": false],+ "modelID": "toy",+ "arch": archDict,+ "files": files,+ "expertsPerLayer": toy.numExperts,+ "numLayers": toy.numLayers,+ "expertStride": expertStride,+ ]+ let manifestData = try JSONSerialization.data(withJSONObject: manifestRoot,+ options: [.sortedKeys, .withoutEscapingSlashes])+ try manifestData.write(to: dir.appendingPathComponent("manifest.json"))+ return dir+ }++ static func writeVerifiedInstallReceipt(directoryURL dir: URL) throws {+ let manifest = try ManifestReader.load(directoryURL: dir, expecting: .gemma4Toy())+ let manifestURL = dir.appendingPathComponent("manifest.json")+ let manifestSha = try Sha256Verifier.hashFile(at: manifestURL)+ let manifestSize = try FileManager.default+ .attributesOfItem(atPath: manifestURL.path)[.size] as! NSNumber+ var receiptFiles = manifest.files.mapValues {+ VerifiedInstallReceipt.FileEntry(size: $0.size, sha256: $0.sha256)+ }+ receiptFiles["manifest.json"] = VerifiedInstallReceipt.FileEntry(+ size: manifestSize.uint64Value,+ sha256: manifestSha)+ let receipt = VerifiedInstallReceipt(+ manifestSha256: manifestSha,+ modelDirectoryPath: dir.standardizedFileURL.path,+ sourceRepoID: "toy",+ sourceRevision: "test",+ verificationTimestamp: "2026-07-01T00:00:00Z",+ toolVersion: "test",+ files: receiptFiles)+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]+ let data = try encoder.encode(receipt)+ try data.write(to: dir.appendingPathComponent(VerifiedInstallReceiptReader.fileName))+ }++ static func mutateReceipt(directoryURL dir: URL,+ transform: (inout [String: Any]) throws -> Void) throws {+ let receiptURL = dir.appendingPathComponent(VerifiedInstallReceiptReader.fileName)+ var root = try JSONSerialization.jsonObject(+ with: Data(contentsOf: receiptURL)) as! [String: Any]+ try transform(&root)+ let data = try JSONSerialization.data(withJSONObject: root,+ options: [.sortedKeys, .withoutEscapingSlashes])+ try data.write(to: receiptURL)+ }++ static func flipByte(in url: URL, at offset: UInt64) throws {+ let handle = try FileHandle(forUpdating: url)+ try handle.seek(toOffset: offset)+ let byte = try #require(try handle.read(upToCount: 1)?.first)+ try handle.seek(toOffset: offset)+ try handle.write(contentsOf: [byte ^ 0xFF])+ try handle.close()+ }++ // MARK: - Positive++ // MARK: - Negative++ // MARK: - Lazy fd / SHA++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelTypesTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelTypesTests.swiftnew file mode 100644index 00000000..62ed8369--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelTypesTests.swift@@ -0,0 +1,35 @@+import Testing+import Foundation+@testable import TurboFieldfare++@Suite struct ModelTypesTests {++ @Test func archConfigGemma4BaselineMatchesDocs() {+ let a = ArchConfig.gemma4_26B_A4B+ #expect(a.hiddenSize == 2816)+ #expect(a.intermediateSize == 2112)+ #expect(a.moeIntermediateSize == 704)+ #expect(a.numLayers == 30)+ #expect(a.numExperts == 128)+ #expect(a.topKExperts == 8)+ #expect(a.vocabSize == 262144)+ #expect(a.tieWordEmbeddings == true)+ #expect(a.finalLogitSoftcap == 30.0)+ #expect(a.fullAttentionLayerMask.count == 30)+ let fullCount = a.fullAttentionLayerMask.reduce(0) { $0 + Int($1) }+ #expect(fullCount == 5, "Gemma 4 has 5 full-attention layers, got \(fullCount)")+ // Mask flags layers 5, 11, 17, 23, 29.+ for L in [5, 11, 17, 23, 29] {+ #expect(a.fullAttentionLayerMask[L] == 1, "layer \(L) should be full-attention")+ }+ }++ @Test func modelErrorDescriptionsContainKeyFacts() {+ let e1 = ModelError.archMismatch(field: "hiddenSize", expected: "2816", actual: "4096")+ #expect(e1.description.contains("2816") && e1.description.contains("4096"))+ let e2 = ModelError.unsupportedVersion(major: 2, minor: 0)+ #expect(e2.description.contains("2"))+ let e3 = ModelError.checksumMismatch(file: "model_weights.bin")+ #expect(e3.description.contains("model_weights.bin"))+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/PackedExpertsLayoutTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/PackedExpertsLayoutTests.swiftnew file mode 100644index 00000000..bcef18d3--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/PackedExpertsLayoutTests.swift@@ -0,0 +1,127 @@+import Testing+import Foundation+@testable import TurboFieldfare++@Suite struct PackedExpertsLayoutTests {++ /// Hand-write a tiny layout.json with one layer, two experts, two+ /// sub-tensors each. Returns the directory URL.+ static func writeToyLayout() throws -> URL {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-layout-test-\(UUID().uuidString)")+ let exp = dir.appendingPathComponent("packed_experts")+ try FileManager.default.createDirectory(at: exp, withIntermediateDirectories: true)++ let root: [String: Any] = [+ "expertStride": 16384,+ "numLayers": 1,+ "expertsPerLayer": 2,+ "layers": [+ [+ "layer": 0,+ "file": "layer_00.bin",+ "experts": [+ [+ "expert": 0,+ "offset": 0,+ "size": 16384,+ "tensors": [+ "gate": [+ "offset": 0,+ "size": 4096,+ "dtype": "U32",+ "shape": [64, 64],+ "bits": 4+ ],+ "gate_scales": [+ "offset": 4096,+ "size": 256,+ "dtype": "BF16",+ "shape": [64, 1]+ ],+ ],+ ],+ [+ "expert": 1,+ "physicalRank": 1,+ "offset": 16384,+ "size": 16384,+ "tensors": [+ "gate": [+ "offset": 0,+ "size": 4096,+ "dtype": "U32",+ "shape": [64, 64],+ "bits": 4+ ],+ "gate_scales": [+ "offset": 4096,+ "size": 256,+ "dtype": "BF16",+ "shape": [64, 1]+ ],+ ],+ ],+ ],+ ],+ ],+ ]+ let data = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])+ try data.write(to: exp.appendingPathComponent("layout.json"))+ return dir+ }++ @Test func decodesToyLayout() throws {+ let dir = try Self.writeToyLayout()+ defer { try? FileManager.default.removeItem(at: dir) }+ let layout = try PackedExpertsLayoutReader.load(directoryURL: dir)+ #expect(layout.expertStride == 16384)+ #expect(layout.numLayers == 1)+ #expect(layout.expertsPerLayer == 2)+ #expect(layout.layers.count == 1)+ let exp0 = layout.expert(layer: 0, expert: 0)+ #expect(exp0.offset == 0)+ #expect(exp0.size == 16384)+ let gate = try #require(exp0.subTensors["gate"])+ #expect(gate.offset == 0)+ #expect(exp0.subTensors["gate_scales"]?.offset == 4096)+ let exp1 = layout.expert(layer: 0, expert: 1)+ #expect(exp1.offset == 16384)+ #expect(exp1.expert == 1)+ }++ @Test func missingLayoutJsonThrowsMissingFile() throws {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-no-layout-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: dir.appendingPathComponent("packed_experts"),+ withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try PackedExpertsLayoutReader.load(directoryURL: dir)+ } throws: { error in+ if case ModelError.missingFile = error { return true }+ return false+ }+ }++ @Test func oversizedLayoutRejectsBeforeDecode() throws {+ let dir = try Self.writeToyLayout()+ defer { try? FileManager.default.removeItem(at: dir) }+ let layoutURL = dir+ .appendingPathComponent("packed_experts")+ .appendingPathComponent("layout.json")+ try Data(repeating: 0x20, count: 64).write(to: layoutURL)++ #expect {+ _ = try PackedExpertsLayoutReader.load(directoryURL: dir,+ maxBytes: 16)+ } throws: { error in+ if case ModelError.indexCorrupt(let detail) = error {+ return detail.contains("metadata cap")+ }+ return false+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/QuantizationAffineTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/QuantizationAffineTests.swiftnew file mode 100644index 00000000..5c2f773a--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/QuantizationAffineTests.swift@@ -0,0 +1,89 @@+import Testing+import Foundation+import TurboFieldfare++@Suite struct QuantizationAffineTests {++ @Test func quantizeDequantizeInt4Affine_roundtrip() {+ var row = [Float]()+ row.reserveCapacity(128)+ for k in 0..<64 { row.append(0.10 + Float(k) * 0.01) } // 0.10 .. 0.73 (positive-only, bias > 0)+ for k in 0..<64 { row.append(-0.50 - Float(k) * 0.005) } // -0.50 .. -0.815 (negative-only, bias < 0)++ let q = Quantization.quantizeInt4Affine(row)+ #expect(q.packed.count == 64)+ #expect(q.scales.count == 2)+ #expect(q.biases.count == 2)++ let r = Quantization.dequantizeInt4Affine(q, n: 128)+ // 4-bit affine, group-0 scale ≈ (0.73 - 0.10) / 15 ≈ 0.042; group-1 scale+ // ≈ 0.315/15 ≈ 0.021. Worst-case rounding ≤ scale/2 plus BF16 rounding+ // of the scale (rel ≤ 2^-7) — bound under 0.025.+ for i in 0..<128 {+ #expect(abs(r[i] - row[i]) < 0.025,+ "i=\(i) ref=\(row[i]) got=\(r[i])")+ }+ }++ @Test func quantizeDequantizeInt8Affine_roundtrip() {+ var row = [Float]()+ row.reserveCapacity(64)+ for k in 0..<64 { row.append(-0.3 + Float(k) * 0.02) } // -0.30 .. +0.96++ let q = Quantization.quantizeInt8Affine(row)+ #expect(q.packed.count == 64)+ #expect(q.scales.count == 1)+ #expect(q.biases.count == 1)++ let r = Quantization.dequantizeInt8Affine(q, n: 64)+ // 8-bit affine, scale ≈ 1.26/255 ≈ 0.005 → rounding ≤ scale/2 ≈ 0.0025;+ // BF16 rounding of scale ≤ 2^-7 → extra ≤ 0.005 * 255/2 * 2^-7 ≈ 0.005.+ // Bound under 0.008 absorbs both contributions.+ for i in 0..<64 {+ #expect(abs(r[i] - row[i]) < 0.008,+ "i=\(i) ref=\(row[i]) got=\(r[i])")+ }+ }++ @Test func bf16Roundtrip_isLossyButPredictable() {+ let values: [Float] = [0.0, 1.0, -1.0, 0.5, -0.5, 1.0 / 3.0, 12345.0]+ for v in values {+ let bits = Quantization.bf16Bits(v)+ let back = Quantization.bf16ToFloat(bits)+ // BF16 has 7 mantissa bits; rel error ≤ 2^-7 = 7.8e-3.+ let denom = max(abs(v), 1e-6)+ #expect(abs(back - v) / denom < 8e-3,+ "v=\(v) back=\(back)")+ }+ }++ /// Constant-group sanity: a flat group reproduces exactly.+ @Test func quantizeInt4Affine_constantGroupRoundtripsExact() {+ let row = [Float](repeating: 0.42, count: 64)+ let q = Quantization.quantizeInt4Affine(row)+ let r = Quantization.dequantizeInt4Affine(q, n: 64)+ // Constant-group path stores bias = value, scale = 1; the only error is+ // the BF16 rounding of the bias.+ let bf16Rounded = Quantization.bf16ToFloat(Quantization.bf16Bits(0.42))+ for i in 0..<64 {+ #expect(abs(r[i] - bf16Rounded) < 1e-6,+ "i=\(i) got=\(r[i]) ref=\(bf16Rounded)")+ }+ }++ /// Asymmetric range (positive-only with non-zero bias) — the failure mode+ /// the symmetric scheme cannot represent without wasted dynamic range.+ @Test func quantizeInt4Affine_positiveOnlyUsesFullCodebook() {+ let row = (0..<64).map { Float($0) / 63.0 + 1.0 } // 1.0 .. 2.0+ let q = Quantization.quantizeInt4Affine(row)+ var seenLow = false, seenHigh = false+ for b in q.packed {+ let lo = b & 0x0F+ let hi = b >> 4+ if lo == 0 || hi == 0 { seenLow = true }+ if lo == 15 || hi == 15 { seenHigh = true }+ }+ #expect(seenLow, "affine 4-bit on positive-only range should hit q=0")+ #expect(seenHigh, "affine 4-bit on positive-only range should hit q=15")+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/QuantizationTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/QuantizationTests.swiftnew file mode 100644index 00000000..16b49789--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/QuantizationTests.swift@@ -0,0 +1,51 @@+import Testing+import Foundation+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct QuantizationTests {++ @Test func roundTripIsBoundedByAffineInt4Step() {+ var rng = SeedTree(0x51A7_1001).key("int4-affine-round-trip")+ var row = [Float](repeating: 0, count: 256)+ for i in 0..<row.count {+ row[i] = rng.uniform(-1.0, 1.0)+ }+ let q = Quantization.quantizeInt4Affine(row)+ let r = Quantization.dequantizeInt4Affine(q, n: row.count)++ // MLX affine 4-bit (16 levels covering [min, max]) gives a worst-case+ // per-sample error of half the quant step = (max - min) / 30 in the+ // worst group. We bound by amax * 2 / 14 + 1e-3 to absorb BF16+ // scale / bias rounding (rel ≤ 2^-7).+ for g in 0..<(row.count / Quantization.groupSize) {+ var amax: Float = 0+ for k in 0..<Quantization.groupSize {+ amax = max(amax, abs(row[g * Quantization.groupSize + k]))+ }+ let bound = amax / 7.0 + 1e-3+ for k in 0..<Quantization.groupSize {+ let i = g * Quantization.groupSize + k+ #expect(abs(r[i] - row[i]) <= bound,+ "i=\(i) orig=\(row[i]) rec=\(r[i]) bound=\(bound)")+ }+ }+ }++ @Test func nibbleLayoutIsLowEvenHighOdd() {+ // Construct a row that exercises both nibble positions.+ let row: [Float] = (0..<64).map { Float($0) - 31.5 } // 64 values++ let q = Quantization.quantizeInt4Affine(row)+ // Verify even-index weight comes from low nibble of byte 0.+ let b0 = q.packed[0]+ let lo = Int(b0 & 0x0F)+ let hi = Int(b0 >> 4)+ let scale = Quantization.bf16ToFloat(q.scales[0])+ let bias = Quantization.bf16ToFloat(q.biases[0])+ let recon0 = Float(lo) * scale + bias+ let recon1 = Float(hi) * scale + bias+ #expect(abs(recon0 - row[0]) <= scale + 1e-3)+ #expect(abs(recon1 - row[1]) <= scale + 1e-3)+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ResidentBufferTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ResidentBufferTests.swiftnew file mode 100644index 00000000..9f753329--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ResidentBufferTests.swift@@ -0,0 +1,56 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare++@Suite struct ResidentBufferTests {++ @Test func wrapsResidentRegionAndReadsBytes() throws {+ let device = try #require(MTLCreateSystemDefaultDevice())+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-resident-\(UUID().uuidString).bin")+ defer { try? FileManager.default.removeItem(at: url) }++ // 24-byte fake header (zeros) followed by 16-byte fake index region+ // followed by 1 KB of resident payload with a recognizable pattern.+ let preamble = Data(repeating: 0, count: 24 + 16)+ var payload = Data(count: 1024)+ for i in 0..<payload.count { payload[i] = UInt8(i & 0xFF) }+ try (preamble + payload).write(to: url)++ let resident = try ResidentBuffer(+ fileURL: url,+ fileOffset: UInt64(preamble.count),+ residentSize: UInt64(payload.count),+ device: device)+ #expect(resident.buffer.length == payload.count)+ for i in 0..<payload.count {+ let got = resident.buffer.contents().load(+ fromByteOffset: i, as: UInt8.self)+ #expect(got == UInt8(i & 0xFF), "byte \(i)")+ }+ }++ @Test func unalignedFileOffsetStillExposesPayloadAtOffsetZero() throws {+ let device = try #require(MTLCreateSystemDefaultDevice())+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-resident-unaligned-\(UUID().uuidString).bin")+ defer { try? FileManager.default.removeItem(at: url) }++ // Offset that is not a multiple of getpagesize() — say 137.+ let preLen = 137+ let preamble = Data(repeating: 0x55, count: preLen)+ var payload = Data(count: 64)+ for i in 0..<payload.count { payload[i] = UInt8(0x80 | (i & 0x7F)) }+ try (preamble + payload).write(to: url)++ let resident = try ResidentBuffer(+ fileURL: url, fileOffset: UInt64(preLen),+ residentSize: UInt64(payload.count), device: device)+ for i in 0..<payload.count {+ let got = resident.buffer.contents().load(+ fromByteOffset: i, as: UInt8.self)+ #expect(got == UInt8(0x80 | (i & 0x7F)), "byte \(i)")+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ResidentIndexTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ResidentIndexTests.swiftnew file mode 100644index 00000000..1d031c50--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ResidentIndexTests.swift@@ -0,0 +1,109 @@+import Testing+import Foundation+@testable import TurboFieldfare+@testable import TurboFieldfareRepackCore++@Suite struct ResidentIndexTests {++ static func dummySource(_ name: String) -> SourceTensor {+ SourceTensor(name: name, shardPath: "/dev/null", dtype: .u32,+ shape: [1024, 64], absoluteOffset: 0, sizeBytes: 0)+ }++ @Test func roundtripsWriterEncodedBytes() throws {+ // Two entries with distinct shapes / sizes / bias offsets so we+ // exercise every field of the 72-byte record. Encoding mirrors+ // ResidentWriter.write: header at byte 0, entries starting at byte 24,+ // string table after the entries, and nameOffset = absolute file+ // offset to the name inside the index region.+ let names = ["embedding.weight", "layer.0.q_proj.weight"]+ let stringTable = names.joined().data(using: .utf8)!+ let headerBytes = GTurboBinary.indexHeaderBytes+ let entryBytes = GTurboBinary.indexEntryBytes+ let entriesBase = headerBytes+ let stringTableBase = entriesBase + names.count * entryBytes+ var nameOffsets: [UInt32] = []+ var cursor = 0+ for n in names {+ nameOffsets.append(UInt32(stringTableBase + cursor))+ cursor += n.utf8.count+ }+ let rawIndexBytes = stringTableBase + stringTable.count+ // Writer rounds the index region up to 16 KB; we keep the test snug+ // (no padding) since the parser only needs indexSize ≥ that minimum.+ let indexBytes = rawIndexBytes+ let residentBytes = 64++ let entries: [ResidentEntry] = [+ ResidentEntry(+ name: names[0], dtype: 0,+ logicalShape4: [1024, 64, 0, 0],+ fileOffset: UInt64(indexBytes), sizeBytes: 32,+ scaleOffset: UInt64(indexBytes) + 32, scaleSize: 16,+ biasOffset: UInt64(indexBytes) + 48, biasSize: 16,+ quantSpec: nil,+ sourceWeight: Self.dummySource(names[0]),+ sourceScales: nil, sourceBiases: nil),+ ResidentEntry(+ name: names[1], dtype: 0,+ logicalShape4: [256, 64, 0, 0],+ fileOffset: UInt64(indexBytes) + 64, sizeBytes: 0,+ scaleOffset: 0, scaleSize: 0,+ biasOffset: 0, biasSize: 0,+ quantSpec: nil,+ sourceWeight: Self.dummySource(names[1]),+ sourceScales: nil, sourceBiases: nil),+ ]++ var fileBuf = [UInt8](repeating: 0, count: indexBytes + residentBytes)+ fileBuf.withUnsafeMutableBytes { raw in+ let base = raw.baseAddress!+ GTurboBinary.writeIndexHeader(into: base,+ indexSize: UInt64(indexBytes),+ residentSize: UInt64(residentBytes),+ entryCount: UInt64(entries.count))+ for (i, e) in entries.enumerated() {+ let dst = base.advanced(by: entriesBase + i * entryBytes)+ GTurboBinary.writeIndexEntry(into: dst, entry: e,+ nameOffset: nameOffsets[i])+ }+ stringTable.withUnsafeBytes { sb in+ _ = memcpy(base.advanced(by: stringTableBase), sb.baseAddress!, stringTable.count)+ }+ }++ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-index-roundtrip-\(UUID().uuidString).bin")+ defer { try? FileManager.default.removeItem(at: url) }+ try Data(fileBuf).write(to: url)++ let parsed = try ResidentIndexReader.load(fileURL: url)+ #expect(parsed.header.entryCount == UInt64(entries.count))+ #expect(parsed.header.indexSize == UInt64(indexBytes))+ #expect(parsed.header.residentSize == UInt64(residentBytes))+ let e0 = try #require(parsed.entries[names[0]])+ #expect(e0.shape.0 == 1024 && e0.shape.1 == 64)+ #expect(e0.fileOffset == UInt64(indexBytes))+ #expect(e0.sizeBytes == 32)+ #expect(e0.scaleOffset == UInt64(indexBytes) + 32 && e0.scaleSize == 16)+ #expect(e0.biasOffset == UInt64(indexBytes) + 48 && e0.biasSize == 16)+ let e1 = try #require(parsed.entries[names[1]])+ #expect(e1.shape.0 == 256 && e1.shape.1 == 64)+ #expect(e1.fileOffset == UInt64(indexBytes) + 64)+ #expect(e1.scaleSize == 0 && e1.biasSize == 0)+ }++ @Test func shortFileThrowsIndexCorrupt() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-short-\(UUID().uuidString).bin")+ defer { try? FileManager.default.removeItem(at: url) }+ try Data(repeating: 0, count: 8).write(to: url)+ #expect {+ _ = try ResidentIndexReader.load(fileURL: url)+ } throws: { error in+ if case ModelError.indexCorrupt = error { return true }+ return false+ }+ }++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/Sha256VerifierTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/Sha256VerifierTests.swiftnew file mode 100644index 00000000..ba3ac168--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/Sha256VerifierTests.swift@@ -0,0 +1,51 @@+import Testing+import Foundation+@testable import TurboFieldfare++@Suite struct Sha256VerifierTests {++ /// SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+ @Test func hashesEmptyFile() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-sha-empty-\(UUID().uuidString).bin")+ try Data().write(to: url)+ defer { try? FileManager.default.removeItem(at: url) }+ let h = try Sha256Verifier.hashFile(at: url)+ #expect(h == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")+ }++ @Test func chunkSizeDoesNotAffectDigest() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-sha-2m-\(UUID().uuidString).bin")+ // Two chunks at the default 1 MB chunkBytes — exercises the loop.+ var data = Data(count: 2 << 20)+ for i in 0..<data.count { data[i] = UInt8(i & 0xFF) }+ try data.write(to: url)+ defer { try? FileManager.default.removeItem(at: url) }++ let small = try Sha256Verifier.hashFile(at: url, chunkBytes: 64 << 10)+ let big = try Sha256Verifier.hashFile(at: url)+ #expect(small == big, "chunk size must not affect digest")+ }++ @Test func verifyMatches() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-sha-match-\(UUID().uuidString).bin")+ let payload = Data("hello world".utf8)+ try payload.write(to: url)+ defer { try? FileManager.default.removeItem(at: url) }+ let hex = try Sha256Verifier.hashFile(at: url)+ try Sha256Verifier.verifyFile(at: url, named: "hello", expectedHex: hex)+ }++ @Test func verifyMismatchThrowsChecksumMismatch() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-sha-bad-\(UUID().uuidString).bin")+ try Data("hello world".utf8).write(to: url)+ defer { try? FileManager.default.removeItem(at: url) }+ let wrong = String(repeating: "0", count: 64)+ #expect(throws: ModelError.checksumMismatch(file: "hello")) {+ try Sha256Verifier.verifyFile(at: url, named: "hello", expectedHex: wrong)+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests+CachePlanning.swift b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests+CachePlanning.swiftnew file mode 100644index 00000000..dac49b9b--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests+CachePlanning.swift@@ -0,0 +1,151 @@+import Darwin+import Foundation+import Metal+import Testing++@testable import TurboFieldfare++extension PreadExpertStreamerTests {+ @Test func cachedBatchWithoutExecutorLoadsTaggedBytes() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 4)++ let results = try streamer.loadExpertsCached(experts: [3, 1, 2])+ for (index, result) in results.enumerated() {+ let expert = [3, 1, 2][index]+ let got = Self.bytes(of: result.buffer, offset: 0, count: Self.expertStride)+ #expect(got.allSatisfy { $0 == Self.tagByte(expert) })+ }+ }++ @Test func adviseExpertsDoesNotChangeLoadedBytes() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 4)+ let experts = [0, 2, 3]++ let advice = streamer.adviseExperts(experts: experts)+ #expect(advice.requested == experts.count)+ #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)+ #expect(advice.failed == 0)+ #else+ #expect(advice.failed == experts.count)+ #endif++ let results = try streamer.loadExpertsCached(experts: experts)+ for (index, result) in results.enumerated() {+ let got = Self.bytes(of: result.buffer, offset: 0, count: Self.expertStride)+ #expect(got.allSatisfy { $0 == Self.tagByte(experts[index]) })+ }+ }++ @Test func adviseExpertMissesSkipsResidentSlots() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 4)++ _ = try streamer.loadExpertsCached(experts: [0])+ let advice = streamer.adviseExpertMisses(experts: [0, 1, 2])++ #expect(advice.requested == 2)+ #expect(advice.calls == 1)+ #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)+ #expect(advice.failed == 0)+ #else+ #expect(advice.failed == 1)+ #endif+ }++ @Test func plannedCacheLoadExecutesSameMisses() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 4)++ _ = try streamer.loadExpertsCached(experts: [0])+ let experts = [0, 1, 2]+ let plan = streamer.planExpertsCached(experts: experts)++ #expect(plan.hits == 1)+ #expect(plan.misses.map { experts[$0] } == [1, 2])++ let results = try streamer.executeExpertCachePlan(plan)+ for (index, result) in results.enumerated() {+ let got = Self.bytes(of: result.buffer, offset: 0, count: Self.expertStride)+ #expect(got.allSatisfy { $0 == Self.tagByte(experts[index]) })+ }+ }++ @Test func plannedCacheBuffersExposeReservedSlotsBeforeExecute() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 4)++ _ = try streamer.loadExpertsCached(experts: [0])+ let experts = [0, 1, 2]+ let plan = streamer.planExpertsCached(experts: experts)+ let reserved = streamer.expertCachePlanBuffers(plan)++ let hitBytes = Self.bytes(of: reserved[0].buffer, offset: 0, count: Self.expertStride)+ #expect(hitBytes.allSatisfy { $0 == Self.tagByte(0) })++ let executed = try streamer.executeExpertCachePlan(plan)+ for i in 0..<experts.count {+ #expect(reserved[i].buffer === executed[i].buffer)+ let got = Self.bytes(of: executed[i].buffer, offset: 0, count: Self.expertStride)+ #expect(got.allSatisfy { $0 == Self.tagByte(experts[i]) })+ }+ }++ @Test func plannedCacheAvoidsInFlightSlotsForHitsAndMisses() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 4)++ let warmed = try streamer.loadExpertsCached(experts: [0, 1])+ let plan = streamer.planExpertsCached(+ experts: [0, 2],+ avoidingSlots: [0, 1])++ #expect(plan.assignedSlots == [0, 2])+ #expect(plan.hits == 1)+ #expect(plan.misses == [1])++ let executed = try streamer.executeExpertCachePlan(plan)+ for (index, expert) in plan.experts.enumerated() {+ let got = Self.bytes(of: executed[index].buffer, offset: 0, count: Self.expertStride)+ #expect(got.allSatisfy { $0 == Self.tagByte(expert) })+ }++ let avoidedBytes = Self.bytes(of: warmed[0].buffer, offset: 0, count: Self.expertStride)+ #expect(avoidedBytes.allSatisfy { $0 == Self.tagByte(0) })+ }++ @Test func plannedCacheReturnsNilWhenMissesCannotAvoidInFlightSlots() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 4)++ _ = try streamer.loadExpertsCached(experts: [0, 1])+ let plan = streamer.planExpertsCachedIfPossible(+ experts: [0, 2, 3, 4],+ avoidingSlots: [0, 1])++ #expect(plan == nil)+ }++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests+Reading.swift b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests+Reading.swiftnew file mode 100644index 00000000..20c3cd0c--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests+Reading.swift@@ -0,0 +1,70 @@+import Darwin+import Foundation+import Metal+import Testing++@testable import TurboFieldfare++extension PreadExpertStreamerTests {+ @Test func preadRoundTrip_matchesTaggedBytes() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 2)++ for e in 0..<Self.numExperts {+ let r = try streamer.loadExpert(layer: 0, expert: e)+ #expect(r.offset == 0)+ #expect(r.size == UInt64(Self.expertStride))+ let got = Self.bytes(of: r.buffer, offset: 0, count: Self.expertStride)+ #expect(+ got.allSatisfy { $0 == Self.tagByte(e) },+ "expert \(e) slot not uniformly tagged")+ }+ }++ @Test func shortRead_throwsSizeMismatch() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 1)++ // Truncate the file on disk to just past expert 0; the already-open fd+ // now hits EOF mid-read for any later expert.+ let truncatedLen = off_t(Self.streamOffset) + off_t(Self.expertStride)+ #expect(truncate(url.path, truncatedLen) == 0)++ #expect(throws: StreamerError.self) {+ _ = try streamer.loadExpert(layer: 0, expert: Self.numExperts - 1)+ }+ }++ @Test func slotReuse_roundRobinOverwrites() throws {+ let url = try Self.writeSyntheticLayer()+ defer { try? FileManager.default.removeItem(at: url) }+ let device = try MetalContext().device+ let streamer = try PreadExpertStreamer(+ layout: Self.makeLayout(path: url.path), device: device, slotCount: 2)++ // With slotCount=2, experts 0,1,2,3 land in slots 0,1,0,1. Capture the+ // first buffer (slot 0, expert 0), then load expert 2 which reuses+ // slot 0 — the same MTLBuffer must now hold expert 2's tag.+ let r0 = try streamer.loadExpert(layer: 0, expert: 0)+ let r1 = try streamer.loadExpert(layer: 0, expert: 1)+ let r2 = try streamer.loadExpert(layer: 0, expert: 2)+ let r3 = try streamer.loadExpert(layer: 0, expert: 3)++ #expect(r0.buffer === r2.buffer, "expert 0 and 2 should share slot 0's buffer")+ #expect(r1.buffer === r3.buffer, "expert 1 and 3 should share slot 1's buffer")+ #expect(r0.buffer !== r1.buffer, "slots 0 and 1 must be distinct buffers")++ // r0 was overwritten by r2; reading slot 0 now yields expert 2's tag.+ let slot0 = Self.bytes(of: r2.buffer, offset: 0, count: Self.expertStride)+ #expect(slot0.allSatisfy { $0 == Self.tagByte(2) })+ let slot1 = Self.bytes(of: r3.buffer, offset: 0, count: Self.expertStride)+ #expect(slot1.allSatisfy { $0 == Self.tagByte(3) })+ }++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests.swiftnew file mode 100644index 00000000..038ae12a--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/PreadExpertStreamerTests.swift@@ -0,0 +1,54 @@+import Testing+import Foundation+import Darwin+import Metal+@testable import TurboFieldfare++/// Unit tests for the synchronous `pread` backend: round-trip correctness,+/// exact file-byte reads, the short-read failure path,+/// and round-robin slot reuse. No real Gemma weights — a synthetic layer file+/// of tagged expert blobs.+@Suite struct PreadExpertStreamerTests {++ static let pageSize = Int(getpagesize())++ /// One expert blob = 2 pages, every byte tagged with `tagByte(expert)` so+ /// a readback uniquely identifies which expert landed in a slot.+ static let expertStride = 2 * pageSize+ static let numExperts = 4+ /// A non-zero stream offset exercises `streamOffset` in the file-offset math.+ static let headerPages = 1+ static var streamOffset: UInt64 { UInt64(headerPages * pageSize) }+ static var streamSize: UInt64 { UInt64(numExperts * expertStride) }++ static func tagByte(_ expert: Int) -> UInt8 { UInt8(0xA0 + expert) }++ /// Write a synthetic layer file: `headerPages` of zeros, then `numExperts`+ /// blobs each filled with their tag byte. Returns the file URL.+ static func writeSyntheticLayer() throws -> URL {+ let total = Int(streamOffset) + Int(streamSize)+ var bytes = [UInt8](repeating: 0, count: total)+ for e in 0..<numExperts {+ let start = Int(streamOffset) + e * expertStride+ for i in 0..<expertStride { bytes[start + i] = tagByte(e) }+ }+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("pread-streamer-\(UUID().uuidString).bin")+ try Data(bytes).write(to: url)+ return url+ }++ static func makeLayout(path: String) -> StreamLayout {+ StreamLayout(path: path,+ streamOffset: streamOffset,+ streamSize: streamSize,+ expertsPerLayer: numExperts,+ expertStride: UInt64(expertStride))+ }++ static func bytes(of buffer: MTLBuffer, offset: UInt64, count: Int) -> [UInt8] {+ let base = buffer.contents().advanced(by: Int(offset))+ return [UInt8](UnsafeRawBufferPointer(start: base, count: count))+ }++}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/Streaming/RDAdvicePolicyTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/RDAdvicePolicyTests.swiftnew file mode 100644index 00000000..63511d7f--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/RDAdvicePolicyTests.swift@@ -0,0 +1,64 @@+import Testing+@testable import TurboFieldfare++@Suite struct RDAdvicePolicyTests {+ @Test func parsesAdaptiveSeparatelyFromBounded() {+ #expect(RDAdvicePolicyMode.parse("default") == .default)+ #expect(RDAdvicePolicyMode.parse("off") == .off)+ #expect(RDAdvicePolicyMode.parse("bounded") == .bounded)+ #expect(RDAdvicePolicyMode.parse("adaptive") == .adaptive)+ }++ @Test func adaptiveSkipsLargeMissFanout() {+ let state = RDAdviceAdaptivePolicyState()+ #expect(state.shouldSkip(position: 128,+ requestedMisses: 16,+ estimatedBytes: 16 * 3_358_720,+ canOverlapUsefulGPUWork: true))+ }++ @Test func adaptiveAllowsModerateFanoutBeforeSlowCall() {+ let state = RDAdviceAdaptivePolicyState()+ #expect(!state.shouldSkip(position: 128,+ requestedMisses: 8,+ estimatedBytes: 8 * 3_358_720,+ canOverlapUsefulGPUWork: true))+ }++ @Test func adaptiveSkipsRemainderOfCurrentProducedTokenAfterSlowCall() {+ var state = RDAdviceAdaptivePolicyState()+ state.update(after: ExpertIOAdviceResult(requested: 8,+ failed: 0,+ calls: 8,+ bytes: 8 * 3_358_720,+ maxCallNanos: 1_500_000),+ position: 128)+ #expect(state.shouldSkip(position: 128,+ requestedMisses: 8,+ estimatedBytes: 8 * 3_358_720,+ canOverlapUsefulGPUWork: true))+ #expect(!state.shouldSkip(position: 129,+ requestedMisses: 8,+ estimatedBytes: 8 * 3_358_720,+ canOverlapUsefulGPUWork: true))+ }++ @Test func adaptiveSkipsWhenAdviceCannotOverlapUsefulWork() {+ let state = RDAdviceAdaptivePolicyState()+ #expect(state.shouldSkip(position: 128,+ requestedMisses: 8,+ estimatedBytes: 8 * 3_358_720,+ canOverlapUsefulGPUWork: false))+ }++ @Test func adaptiveSkipsLargeByteFanout() {+ let state = RDAdviceAdaptivePolicyState(+ config: RDAdviceAdaptivePolicyConfig(missCap: 128,+ byteCap: 32 * 1_048_576,+ slowCallNanos: 1_000_000))+ #expect(state.shouldSkip(position: 128,+ requestedMisses: 16,+ estimatedBytes: 16 * 3_358_720,+ canOverlapUsefulGPUWork: true))+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/Streaming/RDAdviceProbeTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/RDAdviceProbeTests.swiftnew file mode 100644index 00000000..7452cbad--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/RDAdviceProbeTests.swift@@ -0,0 +1,26 @@+import Darwin+import Testing+@testable import TurboFieldfare++@Suite struct RDAdviceProbeTests {+ @Test func clipsByteCountToRadvisoryIntLimit() {+ #expect(RDAdvice.clippedByteCount(0) == 0)+ #expect(RDAdvice.clippedByteCount(64) == 64)+ #expect(RDAdvice.clippedByteCount(UInt64(Int32.max)) == UInt64(Int32.max))+ #expect(RDAdvice.clippedByteCount(UInt64(Int32.max) + 1) == UInt64(Int32.max))+ }++ @Test func invalidNonVnodeDescriptorReportsFailure() {+ var fds = [CInt](repeating: -1, count: 2)+ #expect(pipe(&fds) == 0)+ defer {+ close(fds[0])+ close(fds[1])+ }++ let result = RDAdvice.call(fd: fds[0], offset: 0, byteCount: 1)+ #expect(!result.succeeded)+ #expect(result.requestedBytes == 1)+ #expect(result.errnoValue != 0)+ }+}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/Streaming/StreamingKernelIntegrationTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/StreamingKernelIntegrationTests.swiftnew file mode 100644index 00000000..16ccba19--- /dev/null+++ b/Tests/TurboFieldfare/Core/Infrastructure/Streaming/StreamingKernelIntegrationTests.swift@@ -0,0 +1,175 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// End-to-end: write a synthetic .gturbo blob containing one "expert" worth of+/// affine-quantized weights (packed nibbles + BF16 scales + BF16 biases), open+/// it through `PreadExpertStreamer`, load it into a bounded cache slot, run+/// `dequant_int4_gemv`, and compare against an FP32 reference computed on the+/// CPU.+///+/// This is the smoke test for the streaming → kernel data path on the affine+/// decode hot path. No real Gemma weights, no model — just proof that the+/// pipe works end-to-end with the new layout.+@Suite struct StreamingKernelIntegrationTests {++ /// Layout for a single "expert blob" used in this test.+ /// M = 64 output rows+ /// N = 128 input columns (2 groups of 64 per row)+ /// Packed: M * N/2 = 4096 bytes+ /// Scales: M * N/groupSize * 2 B = 256 bytes BF16+ /// Biases: M * N/groupSize * 2 B = 256 bytes BF16+ /// We page-align each of the three regions so MTLBuffer offsets are legal.+ private struct Sizes {+ static let M = 64+ static let N = 128+ static let groupsPerRow = N / Quantization.groupSize // 2+ static let packedBytes = M * (N / 2) // 4096+ static let scalesBytes = M * groupsPerRow * MemoryLayout<UInt16>.size // 256+ static let biasesBytes = M * groupsPerRow * MemoryLayout<UInt16>.size // 256+ }++ /// Build the in-memory bytes that we'll write to the fake .gturbo.+ /// Layout inside one expert blob (page-aligned externally):+ /// [0, packedBytes) packed nibbles, row-major+ /// [scalesOff, scalesOff + scalesBytes) BF16 scales, row-major+ /// [biasesOff, biasesOff + biasesBytes) BF16 biases, row-major+ private static func buildExpertBlob(weightsFp32: [[Float]],+ pageSize: Int)+ -> (blob: [UInt8], scalesOffset: Int, biasesOffset: Int, blobSize: Int)+ {+ precondition(weightsFp32.count == Sizes.M)+ precondition(weightsFp32[0].count == Sizes.N)++ var packed = [UInt8]( repeating: 0, count: Sizes.packedBytes)+ var scales = [UInt16](repeating: 0, count: Sizes.M * Sizes.groupsPerRow)+ var biases = [UInt16](repeating: 0, count: Sizes.M * Sizes.groupsPerRow)+ for m in 0..<Sizes.M {+ let q = Quantization.quantizeInt4Affine(weightsFp32[m])+ for i in 0..<q.packed.count { packed[m * (Sizes.N / 2) + i] = q.packed[i] }+ for g in 0..<Sizes.groupsPerRow {+ scales[m * Sizes.groupsPerRow + g] = q.scales[g]+ biases[m * Sizes.groupsPerRow + g] = q.biases[g]+ }+ }++ let scalesOffset = roundUp(Sizes.packedBytes, to: pageSize)+ let biasesOffset = roundUp(scalesOffset + Sizes.scalesBytes, to: pageSize)+ let blobSize = roundUp(biasesOffset + Sizes.biasesBytes, to: pageSize)++ var blob = [UInt8](repeating: 0, count: blobSize)+ blob.withUnsafeMutableBufferPointer { ptr in+ _ = memcpy(ptr.baseAddress!, packed, Sizes.packedBytes)+ scales.withUnsafeBufferPointer { sptr in+ _ = memcpy(ptr.baseAddress!.advanced(by: scalesOffset),+ sptr.baseAddress!, Sizes.scalesBytes)+ }+ biases.withUnsafeBufferPointer { bptr in+ _ = memcpy(ptr.baseAddress!.advanced(by: biasesOffset),+ bptr.baseAddress!, Sizes.biasesBytes)+ }+ }+ return (blob, scalesOffset, biasesOffset, blobSize)+ }++ private static func roundUp(_ n: Int, to pageSize: Int) -> Int {+ (n + pageSize - 1) / pageSize * pageSize+ }++ private static func cpuReferenceGemv(weightsFp32: [[Float]], x: [Float]) -> [Float] {+ var y = [Float](repeating: 0, count: Sizes.M)+ for m in 0..<Sizes.M {+ let q = Quantization.quantizeInt4Affine(weightsFp32[m])+ let w = Quantization.dequantizeInt4Affine(q, n: Sizes.N)+ var acc: Float = 0+ for n in 0..<Sizes.N { acc += w[n] * x[n] }+ y[m] = acc+ }+ return y+ }++ @Test func endToEnd_streamFromFile_runKernel_matchesCpuReference() throws {+ // ----- Setup: random weights + input -----+ var rng = SeedTree(0x51A7_1002).key("streaming-kernel-integration")+ var weights = [[Float]](repeating: [], count: Sizes.M)+ for m in 0..<Sizes.M {+ weights[m] = (0..<Sizes.N).map { _ in rng.uniform(-1.0, 1.0) }+ }+ let xFp32: [Float] = (0..<Sizes.N).map { _ in rng.uniform(-1.0, 1.0) }+ let xFp16: [Float16] = xFp32.map { Float16($0) }++ // ----- Build fake .gturbo on disk -----+ let pageSize = Int(getpagesize())+ let (blob, scalesOffset, biasesOffset, blobSize) =+ Self.buildExpertBlob(weightsFp32: weights, pageSize: pageSize)++ let headerSize = pageSize+ let fileSize = headerSize + blobSize+ var fileBytes = [UInt8](repeating: 0, count: fileSize)+ fileBytes.replaceSubrange(headerSize..<(headerSize + blob.count), with: blob)++ let tmp = FileManager.default.temporaryDirectory+ .appendingPathComponent("turbo-fieldfare-smoke-\(UUID().uuidString).bin")+ try Data(fileBytes).write(to: tmp)+ defer { try? FileManager.default.removeItem(at: tmp) }++ let layout = StreamLayout(+ path: tmp.path,+ streamOffset: UInt64(headerSize),+ streamSize: UInt64(blobSize),+ expertsPerLayer: 1,+ expertStride: UInt64(blobSize)+ )+ let ctx = try MetalContext()+ let streamer = try PreadExpertStreamer(+ layout: layout,+ device: ctx.device,+ slotCount: 1)+ let kernel = try DequantInt4GEMV(context: ctx)+ let expert = try streamer.loadExpert(layer: 0, expert: 0)+ let weightsBuf = expert.buffer++ guard let xBuf = ctx.device.makeBuffer(length: Sizes.N * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let yBuf = ctx.device.makeBuffer(length: Sizes.M * MemoryLayout<Float16>.size,+ options: .storageModeShared) else {+ Issue.record("Failed to allocate x / y buffers")+ return+ }+ xBuf.contents().withMemoryRebound(to: Float16.self, capacity: Sizes.N) { dst in+ for i in 0..<Sizes.N { dst[i] = xFp16[i] }+ }++ guard let cmd = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to make command buffer"); return+ }+ kernel.encode(commandBuffer: cmd,+ weights: weightsBuf, weightsOffset: Int(expert.offset),+ scales: weightsBuf, scalesOffset: Int(expert.offset) + scalesOffset,+ biases: weightsBuf, biasesOffset: Int(expert.offset) + biasesOffset,+ x: xBuf, y: yBuf,+ m: UInt32(Sizes.M), n: UInt32(Sizes.N))+ cmd.commit()+ cmd.waitUntilCompleted()++ let yKernel: [Float] = (0..<Sizes.M).map { i in+ Float(yBuf.contents().load(fromByteOffset: i * MemoryLayout<Float16>.size,+ as: Float16.self))+ }+ let yRef = Self.cpuReferenceGemv(weightsFp32: weights, x: xFp32)++ var maxAbsDiff: Float = 0+ var refNorm: Float = 0+ for i in 0..<Sizes.M {+ maxAbsDiff = max(maxAbsDiff, abs(yKernel[i] - yRef[i]))+ refNorm = max(refNorm, abs(yRef[i]))+ }+ let relErr = maxAbsDiff / max(refNorm, 1e-6)++ #expect(relErr < 5e-3,+ "kernel vs CPU ref relErr=\(relErr) maxAbsDiff=\(maxAbsDiff) refNorm=\(refNorm)")++ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swiftnew file mode 100644index 00000000..b337b324--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift@@ -0,0 +1,614 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Compares the Metal `attention` kernel against `AttentionRef`, which+/// materializes the full attention matrix per Q head via `vDSP_dotpr` and+/// then softmaxes/outputs. The kernel runs FlashAttention-style tiled+/// online softmax; this reference does no online merging. Different code+/// shape, different summation order.+@Suite struct AttentionTests {++ private enum Mode: CustomStringConvertible {+ case swa(window: Int)+ case full+ var description: String {+ switch self {+ case .swa(let w): return "swa(window=\(w))"+ case .full: return "full"+ }+ }+ }++ @Test func attentionSplitGeometry_reportsEffectiveDispatchShape() throws {+ let swa = Attention.splitGeometry(numQHeads: 16,+ numKVHeads: 8,+ seqLen: 1536,+ kvStart: 512,+ preferGQASWA: true)+ #expect(swa.effectiveLength == 1024)+ #expect(swa.numChunks == 16)+ #expect(swa.chunkLength == 64)+ #expect(swa.partialThreadgroups == 128)+ #expect(swa.useSWAGroupedPartial)++ let full = Attention.splitGeometry(numQHeads: 16,+ numKVHeads: 2,+ seqLen: 1536,+ kvStart: 0,+ preferGQASWA: false)+ #expect(full.effectiveLength == 1536)+ #expect(full.numChunks == 16)+ #expect(full.chunkLength == 96)+ #expect(full.partialThreadgroups == 256)+ #expect(!full.useSWAGroupedPartial)+ }++ // MARK: - Gemma 4 scale=1.0 path++ /// Gemma 4 uses an attention scale of 1.0. Verify the kernel honours the+ /// runtime scale argument by computing the same forward with+ /// scale=1.0 in both kernel and reference, and confirming the output+ /// differs from the default rsqrt(head_dim) scale path.+ @Test func attentionSWA_unitScale_matchesReference_andDiffersFromDefault() throws {+ let headDim = 64, numQHeads = 4, numKVHeads = 2+ let seqLen = 8, window = 8+ let qCount = numQHeads * headDim+ let kvCount = seqLen * numKVHeads * headDim++ var rng = SeedTree(0x501).key("attn-scale1-swa")+ let qFp32 = (0..<qCount).map { _ in rng.uniform(-0.5, 0.5) }+ let kFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }+ let vFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }+ let qFp16 = qFp32.map { Float16($0) }+ let kFp16 = kFp32.map { Float16($0) }+ let vFp16 = vFp32.map { Float16($0) }++ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)+ guard let qBuf = Fp16Buffer.make(ctx.device, halves: qFp16),+ let kBuf = Fp16Buffer.make(ctx.device, halves: kFp16),+ let vBuf = Fp16Buffer.make(ctx.device, halves: vFp16),+ let outScaled = Fp16Buffer.make(ctx.device, count: qCount),+ let outUnit = Fp16Buffer.make(ctx.device, count: qCount) else {+ Issue.record("alloc failed"); return+ }+ let cb = ctx.queue.makeCommandBuffer()!+ kernel.encodeSWA(commandBuffer: cb,+ q: qBuf, k: kBuf, v: vBuf, out: outScaled,+ headDim: UInt32(headDim), numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen), window: UInt32(window))+ kernel.encodeSWA(commandBuffer: cb,+ q: qBuf, k: kBuf, v: vBuf, out: outUnit,+ headDim: UInt32(headDim), numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen), window: UInt32(window),+ scale: 1.0)+ cb.commit(); cb.waitUntilCompleted()++ let kernelUnit = Fp16Buffer.read(outUnit, count: qCount)+ let qRef = qFp16.map { Float($0) }+ let kRef = kFp16.map { Float($0) }+ let vRef = vFp16.map { Float($0) }+ let refUnit = AttentionRef.apply(+ q: qRef, k: kRef, v: vRef,+ headDim: headDim, numQHeads: numQHeads, numKVHeads: numKVHeads,+ seqLen: seqLen, window: window, scale: 1.0)+ let rel = RelError.compute(actual: kernelUnit, reference: refUnit)+ #expect(rel < Tolerance.fp16ChainedReduction,+ "scale=1.0 SWA kernel vs ref rel=\(rel)")++ // Regression guard: scale=1.0 must produce different numbers from the+ // default rsqrt(head_dim) scale on the same input.+ let kernelScaled = Fp16Buffer.read(outScaled, count: qCount)+ #expect(kernelUnit != kernelScaled,+ "scale=1.0 produced identical output to rsqrt(head_dim) — runtime arg ignored?")+ }++ private static func runAndCompare(+ headDim: Int,+ numQHeads: Int,+ numKVHeads: Int,+ seqLen: Int,+ mode: Mode,+ shareKV: Bool = false,+ seed: UInt64,+ tolerance: Float = Tolerance.fp16ChainedReduction+ ) throws {+ var rng = SeedTree(seed).key(+ "attn-h\(numQHeads)-kv\(numKVHeads)-d\(headDim)-T\(seqLen)-kv=\(shareKV)"+ )++ let qCount = numQHeads * headDim+ let kvCount = seqLen * numKVHeads * headDim++ let qFp32 = (0..<qCount).map { _ in rng.uniform(-0.5, 0.5) }+ let kFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }+ let vFp32: [Float] = shareKV+ ? kFp32+ : (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }++ let qFp16 = qFp32.map { Float16($0) }+ let kFp16 = kFp32.map { Float16($0) }+ let vFp16 = vFp32.map { Float16($0) }++ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)++ guard let qBuf = Fp16Buffer.make(ctx.device, halves: qFp16),+ let kBuf = Fp16Buffer.make(ctx.device, halves: kFp16),+ let outBuf = Fp16Buffer.make(ctx.device, count: qCount) else {+ Issue.record("Failed to allocate buffers"); return+ }+ let vBuf: MTLBuffer+ if shareKV {+ vBuf = kBuf+ } else {+ guard let b = Fp16Buffer.make(ctx.device, halves: vFp16) else {+ Issue.record("Failed to allocate V buffer"); return+ }+ vBuf = b+ }++ guard let cmd = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to make command buffer"); return+ }+ switch mode {+ case .swa(let window):+ kernel.encodeSWA(commandBuffer: cmd,+ q: qBuf, k: kBuf, v: vBuf, out: outBuf,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen),+ window: UInt32(window))+ case .full:+ kernel.encodeFull(commandBuffer: cmd,+ q: qBuf, k: kBuf, v: vBuf, out: outBuf,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen))+ }+ cmd.commit()+ cmd.waitUntilCompleted()++ let qRef = qFp16.map { Float($0) }+ let kRef = kFp16.map { Float($0) }+ let vRef = vFp16.map { Float($0) }+ let window: Int? = {+ if case .swa(let w) = mode { return w }+ return nil+ }()+ let ref = AttentionRef.apply(+ q: qRef, k: kRef, v: vRef,+ headDim: headDim, numQHeads: numQHeads,+ numKVHeads: numKVHeads, seqLen: seqLen, window: window+ )+ let actual = Fp16Buffer.read(outBuf, count: qCount)++ let rel = RelError.compute(actual: actual, reference: ref)+ let passed = rel < tolerance+ if !passed {+ print("attention check failed: mode=\(mode) headDim=\(headDim) " ++ "Hq=\(numQHeads) Hkv=\(numKVHeads) T=\(seqLen) rel=\(rel)")+ }+ #expect(passed)+ }++ // SWA ---------------------------------------------------------------------++ @Test func attentionSWA_smallShape() throws {+ try Self.runAndCompare(headDim: 64, numQHeads: 4, numKVHeads: 2,+ seqLen: 128, mode: .swa(window: 64), seed: 0x171)+ }++ @Test func attentionSWA_shorterThanWindow() throws {+ try Self.runAndCompare(headDim: 64, numQHeads: 4, numKVHeads: 2,+ seqLen: 32, mode: .swa(window: 128), seed: 0x172)+ }++ @Test func attentionSWA_realShape() throws {+ try Self.runAndCompare(headDim: 256, numQHeads: 16, numKVHeads: 8,+ seqLen: 256, mode: .swa(window: 128), seed: 0x173)+ }++ @Test func attentionSWA_ringCapacityMatchesLinearReference() throws {+ let headDim = 64+ let numQHeads = 4+ let numKVHeads = 2+ let seqLen = 40+ let window = 16+ let ringCapacity = 24+ let qCount = numQHeads * headDim+ let kvStride = numKVHeads * headDim+ let kvCount = seqLen * kvStride+ let ringCount = ringCapacity * kvStride++ var rng = SeedTree(0x174).key("attn-swa-ring")+ let qFp32 = (0..<qCount).map { _ in rng.uniform(-0.5, 0.5) }+ let kFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }+ let vFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }++ var kRing = [Float](repeating: 0, count: ringCount)+ var vRing = [Float](repeating: 0, count: ringCount)+ for p in 0..<seqLen {+ let dst = (p % ringCapacity) * kvStride+ let src = p * kvStride+ kRing.replaceSubrange(dst..<(dst + kvStride),+ with: kFp32[src..<(src + kvStride)])+ vRing.replaceSubrange(dst..<(dst + kvStride),+ with: vFp32[src..<(src + kvStride)])+ }++ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)+ guard let qBuf = Fp16Buffer.make(ctx.device, halves: qFp32.map { Float16($0) }),+ let kBuf = Fp16Buffer.make(ctx.device, halves: kRing.map { Float16($0) }),+ let vBuf = Fp16Buffer.make(ctx.device, halves: vRing.map { Float16($0) }),+ let outBuf = Fp16Buffer.make(ctx.device, count: qCount) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ kernel.encodeSWA(commandBuffer: cb,+ q: qBuf,+ k: kBuf,+ v: vBuf,+ out: outBuf,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen),+ window: UInt32(window),+ ringCapacity: UInt32(ringCapacity))+ cb.commit()+ cb.waitUntilCompleted()++ let actual = Fp16Buffer.read(outBuf, count: qCount)+ let ref = AttentionRef.apply(q: qFp32.map { Float(Float16($0)) },+ k: kFp32.map { Float(Float16($0)) },+ v: vFp32.map { Float(Float16($0)) },+ headDim: headDim,+ numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ seqLen: seqLen,+ window: window)+ let rel = RelError.compute(actual: actual, reference: ref)+ #expect(rel < Tolerance.fp16ChainedReduction,+ "ring SWA kernel vs linear ref rel=\(rel)")+ }++ @Test func attentionSWA_ringCapacityMatchesLinearKernelAtWrapRealShape() throws {+ let headDim = 256+ let numQHeads = 16+ let numKVHeads = 8+ let seqLen = 1187+ let window = 1024+ let ringCapacity = 1152+ let qCount = numQHeads * headDim+ let kvStride = numKVHeads * headDim+ let kvCount = seqLen * kvStride+ let ringCount = ringCapacity * kvStride++ var rng = SeedTree(0x181).key("attn-swa-ring-real-wrap")+ let qFp16 = (0..<qCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }+ let kFp16 = (0..<kvCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }+ let vFp16 = (0..<kvCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }++ var kRing = [Float16](repeating: 0, count: ringCount)+ var vRing = [Float16](repeating: 0, count: ringCount)+ for p in 0..<seqLen {+ let dst = (p % ringCapacity) * kvStride+ let src = p * kvStride+ kRing.replaceSubrange(dst..<(dst + kvStride),+ with: kFp16[src..<(src + kvStride)])+ vRing.replaceSubrange(dst..<(dst + kvStride),+ with: vFp16[src..<(src + kvStride)])+ }++ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)+ guard let qBuf = Fp16Buffer.make(ctx.device, halves: qFp16),+ let kLinearBuf = Fp16Buffer.make(ctx.device, halves: kFp16),+ let vLinearBuf = Fp16Buffer.make(ctx.device, halves: vFp16),+ let kRingBuf = Fp16Buffer.make(ctx.device, halves: kRing),+ let vRingBuf = Fp16Buffer.make(ctx.device, halves: vRing),+ let linearOut = Fp16Buffer.make(ctx.device, count: qCount),+ let ringOut = Fp16Buffer.make(ctx.device, count: qCount) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ kernel.encodeSWA(commandBuffer: cb,+ q: qBuf,+ k: kLinearBuf,+ v: vLinearBuf,+ out: linearOut,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen),+ window: UInt32(window),+ ringCapacity: 0)+ kernel.encodeSWA(commandBuffer: cb,+ q: qBuf,+ k: kRingBuf,+ v: vRingBuf,+ out: ringOut,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen),+ window: UInt32(window),+ ringCapacity: UInt32(ringCapacity))+ cb.commit()+ cb.waitUntilCompleted()++ let linear = Fp16Buffer.read(linearOut, count: qCount)+ let ring = Fp16Buffer.read(ringOut, count: qCount)+ let rel = RelError.compute(actual: ring, reference: linear)+ #expect(rel < Tolerance.fp16ChainedReduction,+ "ring SWA kernel vs linear SWA kernel rel=\(rel)")+ }++ @Test func attentionSWA_turboQuantPackedKV_matchesMaterializedReference() throws {+ try Self.runTurboQuantPackedKVAndCompare(+ headDim: 256,+ numQHeads: 4,+ numKVHeads: 2,+ seqLen: 16,+ mode: .swa(window: 8),+ seed: 0x178)+ }++ private static func runTurboQuantPackedKVAndCompare(+ headDim: Int,+ numQHeads: Int,+ numKVHeads: Int,+ seqLen: Int,+ mode: Mode,+ seed: UInt64+ ) throws {+ let window: Int?+ let kvStart: UInt32+ switch mode {+ case .swa(let w):+ window = w+ kvStart = UInt32(seqLen > w ? seqLen - w : 0)+ case .full:+ window = nil+ kvStart = 0+ }+ let qCount = numQHeads * headDim+ let kvCount = seqLen * numKVHeads * headDim+ let pairs = seqLen * numKVHeads+ let layer: UInt32 = 3+ let rotationSeed: UInt32 = 0xC0FFEE++ var rng = SeedTree(seed).key("attn-tq-kv-\(mode)-d\(headDim)")+ let qFp32 = (0..<qCount).map { _ in rng.uniform(-0.5, 0.5) }+ let kFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }+ let vFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }+ let qFp16 = qFp32.map { Float16($0) }+ let kFp16 = kFp32.map { Float16($0) }+ let vFp16 = vFp32.map { Float16($0) }++ let keyLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,+ headDim: headDim,+ numKVHeads: numKVHeads)+ let valueLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,+ headDim: headDim,+ numKVHeads: numKVHeads)++ let ctx = try MetalContext()+ let quant = try TurboQuantQuant(context: ctx)+ let attention = try Attention(context: ctx)++ guard let qBuf = Fp16Buffer.make(ctx.device, halves: qFp16),+ let kBuf = Fp16Buffer.make(ctx.device, halves: kFp16),+ let vBuf = Fp16Buffer.make(ctx.device, halves: vFp16),+ let outPackedSplit = Fp16Buffer.make(ctx.device, count: qCount),+ let keyCache = ctx.device.makeBuffer(length: keyLayout.bytesPerToken * seqLen,+ options: .storageModeShared),+ let valueCache = ctx.device.makeBuffer(length: valueLayout.bytesPerToken * seqLen,+ options: .storageModeShared) else {+ Issue.record("alloc failed"); return+ }++ let whtParams = TurboQuantWHTParams(numHeads: UInt32(numKVHeads),+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)+ let keyWrite = TurboQuantKVWriteParams(d: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ roleLayout: keyLayout)+ let valueWrite = TurboQuantKVWriteParams(d: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ roleLayout: valueLayout)+ let attentionParams = AttentionTurboQuantKVParams(+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen),+ kvStart: kvStart,+ scale: 1.0,+ layer: layer,+ rotationSeed: rotationSeed,+ keyLayout: keyLayout,+ valueLayout: valueLayout)++ let cb = ctx.queue.makeCommandBuffer()!+ quant.encodeKVWriteWHT(commandBuffer: cb,+ x: kBuf,+ cache: keyCache,+ params: keyWrite,+ whtParams: whtParams,+ pairs: pairs)+ quant.encodeKVWriteWHT(commandBuffer: cb,+ x: vBuf,+ cache: valueCache,+ params: valueWrite,+ whtParams: whtParams,+ pairs: pairs)+ attention.encodeTurboQuantSplit(commandBuffer: cb,+ q: qBuf,+ keyCache: keyCache,+ valueCache: valueCache,+ out: outPackedSplit,+ params: attentionParams)+ cb.commit()+ cb.waitUntilCompleted()++ let actualSplit = Fp16Buffer.read(outPackedSplit, count: qCount)+ let keyBytes = Array(UnsafeBufferPointer(+ start: keyCache.contents().assumingMemoryBound(to: UInt8.self),+ count: keyCache.length))+ let valueBytes = Array(UnsafeBufferPointer(+ start: valueCache.contents().assumingMemoryBound(to: UInt8.self),+ count: valueCache.length))+ let materializedKey = TurboQuantRef.materializePackedCache(+ keyBytes,+ tokenCount: seqLen,+ headDim: headDim,+ numHeads: numKVHeads,+ bytesPerHead: keyLayout.bytesPerHead,+ bytesPerToken: keyLayout.bytesPerToken,+ packedOffset: keyLayout.packedOffsetPerHead,+ scaleOffset: keyLayout.scaleOffsetPerHead,+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)+ let materializedValue = TurboQuantRef.materializePackedCache(+ valueBytes,+ tokenCount: seqLen,+ headDim: headDim,+ numHeads: numKVHeads,+ bytesPerHead: valueLayout.bytesPerHead,+ bytesPerToken: valueLayout.bytesPerToken,+ packedOffset: valueLayout.packedOffsetPerHead,+ scaleOffset: valueLayout.scaleOffsetPerHead,+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)+ let ref = AttentionRef.apply(q: qFp16.map { Float($0) },+ k: materializedKey,+ v: materializedValue,+ headDim: headDim,+ numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ seqLen: seqLen,+ window: window,+ scale: 1.0)+ let splitRel = RelError.compute(actual: actualSplit, reference: ref)+ #expect(splitRel < 0.02, "packed TurboQuant split attention rel=\(splitRel)")+ }++ // Full --------------------------------------------------------------------++ @Test func attentionFull_smallShape() throws {+ try Self.runAndCompare(headDim: 64, numQHeads: 8, numKVHeads: 1,+ seqLen: 128, mode: .full, seed: 0x174)+ }++ @Test func attentionFull_realShape() throws {+ try Self.runAndCompare(headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: 128, mode: .full, seed: 0x175)+ }++ @Test func attentionFull_mlxGeometryV2_distinctKV_stripeBoundaries() throws {+ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)++ let headDim = 512+ let numQHeads = 16+ let numKVHeads = 2+ let qCount = numQHeads * headDim+ for seqLen in [1, 31, 32, 33, 257] {+ var rng = SeedTree(UInt64(0x5200 + seqLen)).key("mlx-v2-distinct-kv")+ let q = (0..<qCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }+ let kvCount = seqLen * numKVHeads * headDim+ let k = (0..<kvCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }+ let v = (0..<kvCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }+ guard let qBuf = Fp16Buffer.make(ctx.device, halves: q),+ let kBuf = Fp16Buffer.make(ctx.device, halves: k),+ let vBuf = Fp16Buffer.make(ctx.device, halves: v),+ let outA = Fp16Buffer.make(ctx.device, count: qCount),+ let outB = Fp16Buffer.make(ctx.device, count: qCount) else {+ Issue.record("allocation failed at seqLen=\(seqLen)")+ return+ }++ for output in [outA, outB] {+ guard let cb = ctx.queue.makeCommandBuffer() else {+ Issue.record("command buffer failed")+ return+ }+ kernel.encodeFull(commandBuffer: cb,+ q: qBuf, k: kBuf, v: vBuf, out: output,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ seqLen: UInt32(seqLen),+ scale: 1.0)+ cb.commit()+ cb.waitUntilCompleted()+ if let error = cb.error { throw error }+ }++ let actualA = Fp16Buffer.read(outA, count: qCount)+ let actualB = Fp16Buffer.read(outB, count: qCount)+ #expect(actualA == actualB, "candidate output changed at seqLen=\(seqLen)")+ let reference = AttentionRef.apply(q: q.map(Float.init),+ k: k.map(Float.init),+ v: v.map(Float.init),+ headDim: headDim,+ numQHeads: numQHeads,+ numKVHeads: numKVHeads,+ seqLen: seqLen,+ window: nil,+ scale: 1.0)+ let rel = RelError.compute(actual: actualA, reference: reference)+ #expect(rel < Tolerance.fp16ChainedReduction,+ "candidate rel=\(rel) at seqLen=\(seqLen)")+ }+ }++ @Test func attentionFull_turboQuantPackedKV_matchesMaterializedReference() throws {+ try Self.runTurboQuantPackedKVAndCompare(+ headDim: 512,+ numQHeads: 8,+ numKVHeads: 1,+ seqLen: 16,+ mode: .full,+ seed: 0x179)+ }++ @Test func attentionFull_turboQuantPackedKV_realHeadShape_matchesMaterializedReference() throws {+ try Self.runTurboQuantPackedKVAndCompare(+ headDim: 512,+ numQHeads: 16,+ numKVHeads: 2,+ seqLen: 16,+ mode: .full,+ seed: 0x17A)+ }++ /// Generic aliasing coverage. Gemma 4 runtime uses distinct post-norm K/V.+ @Test func attentionFull_kvShared_smallShape() throws {+ try Self.runAndCompare(headDim: 64, numQHeads: 8, numKVHeads: 1,+ seqLen: 128, mode: .full, shareKV: true,+ seed: 0x176)+ }++ @Test func attentionFull_kvShared_realShape() throws {+ try Self.runAndCompare(headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: 128, mode: .full, shareKV: true,+ seed: 0x177)+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swiftnew file mode 100644index 00000000..2b8db37b--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift@@ -0,0 +1,463 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillAttentionTests {+ private struct Fixture {+ var q: [Float]+ var k: [Float]+ var v: [Float]+ var qStride: Int+ var kvStride: Int+ var oStride: Int+ var headDim: Int+ var qHeads: Int+ var kvHeads: Int+ var start: Int+ var chunk: Int+ var kvValid: Int+ var window: Int+ var scale: Float+ }++ @Test func prefillAttentionMatchesCPUReferenceFullAndSWA() throws {+ let cases: [(label: String, start: Int, chunk: Int, window: Int)] = [+ ("full-origin", 0, 3, 0),+ ("full-offset", 4, 3, 0),+ ("swa-inside-window", 2, 4, 16),+ ("swa-truncated", 7, 4, 5),+ ]++ for (index, c) in cases.enumerated() {+ let fixture = Self.makeFixture(start: c.start,+ chunk: c.chunk,+ window: c.window,+ seed: 0xA510 + UInt64(index))+ try Self.runAndCompare(fixture, label: c.label)+ }+ }++ @Test func prefillAttentionRingCapacityMatchesLinearReference() throws {+ let fixture = Self.makeFixture(start: 20,+ chunk: 4,+ window: 8,+ seed: 0xA611,+ headDim: 32,+ qHeads: 4,+ kvHeads: 2)+ let ringCapacity = 16+ var kRing = [Float](repeating: 0, count: ringCapacity * fixture.kvStride)+ var vRing = [Float](repeating: 0, count: ringCapacity * fixture.kvStride)+ for p in 0..<fixture.kvValid {+ let dst = (p % ringCapacity) * fixture.kvStride+ let src = p * fixture.kvStride+ kRing.replaceSubrange(dst..<(dst + fixture.kvStride),+ with: fixture.k[src..<(src + fixture.kvStride)])+ vRing.replaceSubrange(dst..<(dst + fixture.kvStride),+ with: fixture.v[src..<(src + fixture.kvStride)])+ }++ var ringFixture = fixture+ ringFixture.k = kRing+ ringFixture.v = vRing+ let actual = try Self.runKernel(ringFixture, kvRingCapacity: UInt32(ringCapacity))+ let reference = Self.reference(fixture)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ let rel = RelError.compute(actual: actual, reference: reference)+ #expect(maxAbs <= 2e-2, "ring prefill maxAbs=\(maxAbs) rel=\(rel)")+ #expect(rel <= 2e-2, "ring prefill rel=\(rel) maxAbs=\(maxAbs)")+ }++ @Test func prefillAttentionMasksFutureChunkTokens() throws {+ var fixture = Self.makeFixture(start: 5, chunk: 4, window: 0, seed: 0xA620)+ let qPerKV = fixture.qHeads / fixture.kvHeads+ for row in fixture.start..<fixture.kvValid {+ for kvh in 0..<fixture.kvHeads {+ for d in 0..<fixture.headDim {+ let base = row * fixture.kvStride + kvh * fixture.headDim + d+ fixture.k[base] = Float(row - fixture.start + 1) * 2.0 + Float(d) * 0.125+ fixture.v[base] = Float(row - fixture.start + 1) * -2.0 - Float(d) * 0.125+ }+ }+ }++ let actual = try Self.runKernel(fixture)+ let reference = Self.reference(fixture)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ let rel = RelError.compute(actual: actual, reference: reference)+ #expect(maxAbs <= 2e-2, "future mask maxAbs=\(maxAbs) rel=\(rel) qPerKV=\(qPerKV)")+ #expect(rel <= 2e-2, "future mask rel=\(rel) maxAbs=\(maxAbs)")+ }++ @Test func prefillAttentionProductionDimsBoundedVisibility() throws {+ let cases: [(label: String, start: Int, chunk: Int, window: Int, headDim: Int, qHeads: Int, kvHeads: Int)] = [+ ("swa-current-key-at-1023", 1023, 1, 1, 256, 16, 8),+ ("swa-current-key-at-1024", 1024, 1, 1, 256, 16, 8),+ ("swa-current-key-at-4095", 4095, 1, 1, 256, 16, 8),+ ("full-origin", 0, 1, 0, 512, 16, 2),+ ("full-short-gqa", 3, 1, 0, 512, 16, 2),+ ]++ for (index, c) in cases.enumerated() {+ let fixture = Self.makeFixture(start: c.start,+ chunk: c.chunk,+ window: c.window,+ seed: 0xA730 + UInt64(index),+ headDim: c.headDim,+ qHeads: c.qHeads,+ kvHeads: c.kvHeads)+ try Self.runAndCompare(fixture, label: c.label)+ }+ }++ @Test func prefillAttentionTiledProductionBoundarySmoke() throws {+ let cases: [(label: String, start: Int, chunk: Int, window: Int, headDim: Int, qHeads: Int, kvHeads: Int)] = [+ ("swa-production-window-1024", 1023, 4, 1024, 256, 16, 8),+ ("full-production-gqa", 31, 8, 0, 512, 16, 2),+ ]++ for (index, c) in cases.enumerated() {+ let fixture = Self.makeFixture(start: c.start,+ chunk: c.chunk,+ window: c.window,+ seed: 0xA840 + UInt64(index),+ headDim: c.headDim,+ qHeads: c.qHeads,+ kvHeads: c.kvHeads)+ try Self.runAndCompare(fixture, label: c.label)+ }+ }++ @Test func prefillTurboQuantPackedAttentionMatchesMaterializedDefaultKV() throws {+ try Self.runTurboQuantPackedAndCompare()+ }++ private static func makeFixture(start: Int,+ chunk: Int,+ window: Int,+ seed: UInt64,+ headDim: Int = 8,+ qHeads: Int = 4,+ kvHeads: Int = 2) -> Fixture {+ let qStride = qHeads * headDim + 3+ let kvStride = kvHeads * headDim + 5+ let oStride = qHeads * headDim + 7+ let kvValid = start + chunk+ var rng = SeedTree(seed).key("prefill-attn-start\(start)-chunk\(chunk)-window\(window)")+ var q = [Float](repeating: 0, count: chunk * qStride)+ var k = [Float](repeating: 0, count: kvValid * kvStride)+ var v = [Float](repeating: 0, count: kvValid * kvStride)++ for t in 0..<chunk {+ for h in 0..<qHeads {+ for d in 0..<headDim {+ q[t * qStride + h * headDim + d] = rng.uniform(-0.35, 0.35)+ }+ }+ }+ for pos in 0..<kvValid {+ for h in 0..<kvHeads {+ for d in 0..<headDim {+ k[pos * kvStride + h * headDim + d] = rng.uniform(-0.35, 0.35)+ v[pos * kvStride + h * headDim + d] = rng.uniform(-0.35, 0.35)+ }+ }+ }++ return Fixture(q: q, k: k, v: v,+ qStride: qStride, kvStride: kvStride, oStride: oStride,+ headDim: headDim, qHeads: qHeads, kvHeads: kvHeads,+ start: start, chunk: chunk, kvValid: kvValid,+ window: window, scale: 1.0)+ }++ private static func runAndCompare(_ fixture: Fixture, label: String) throws {+ let actual = try Self.runKernel(fixture)+ let reference = Self.reference(fixture)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ let rel = RelError.compute(actual: actual, reference: reference)+ #expect(maxAbs <= 2e-2, "\(label) maxAbs=\(maxAbs) rel=\(rel)")+ #expect(rel <= 2e-2, "\(label) rel=\(rel) maxAbs=\(maxAbs)")+ }++ private static func runKernel(_ fixture: Fixture,+ kvRingCapacity: UInt32 = 0) throws -> [Float] {+ let ctx = try MetalContext()+ let prefill = try PrefillAttention(context: ctx)+ let qPrefix = 17+ let kPrefix = 19+ let vPrefix = 23+ let oPrefix = 29+ let outCount = oPrefix + fixture.chunk * fixture.oStride++ guard let qBuf = Fp16Buffer.make(ctx.device,+ values: [Float](repeating: 0, count: qPrefix) + fixture.q),+ let kBuf = Fp16Buffer.make(ctx.device,+ values: [Float](repeating: 0, count: kPrefix) + fixture.k),+ let vBuf = Fp16Buffer.make(ctx.device,+ values: [Float](repeating: 0, count: vPrefix) + fixture.v),+ let outBuf = Fp16Buffer.make(ctx.device, count: outCount) else {+ Issue.record("alloc failed")+ return []+ }++ let params = PrefillAttentionParams(+ startPosition: UInt32(fixture.start),+ queryCount: UInt32(fixture.chunk),+ headDim: UInt32(fixture.headDim),+ numQHeads: UInt32(fixture.qHeads),+ numKVHeads: UInt32(fixture.kvHeads),+ kvValidCount: UInt32(fixture.kvValid),+ slidingWindow: UInt32(fixture.window),+ kvTokenStrideElements: UInt32(fixture.kvStride),+ qTokenStrideElements: UInt32(fixture.qStride),+ oTokenStrideElements: UInt32(fixture.oStride),+ scale: fixture.scale)++ let cb = ctx.queue.makeCommandBuffer()!+ prefill.encodeCausal(commandBuffer: cb,+ q: qBuf,+ qOffset: qPrefix * MemoryLayout<Float16>.size,+ k: kBuf,+ kOffset: kPrefix * MemoryLayout<Float16>.size,+ v: vBuf,+ vOffset: vPrefix * MemoryLayout<Float16>.size,+ out: outBuf,+ outOffset: oPrefix * MemoryLayout<Float16>.size,+ params: params,+ kvRingCapacity: kvRingCapacity)+ cb.commit()+ cb.waitUntilCompleted()++ let out = Fp16Buffer.read(outBuf, count: outCount)+ var compact = [Float](repeating: 0, count: fixture.chunk * fixture.qHeads * fixture.headDim)+ for t in 0..<fixture.chunk {+ for h in 0..<fixture.qHeads {+ for d in 0..<fixture.headDim {+ compact[(t * fixture.qHeads + h) * fixture.headDim + d] =+ out[oPrefix + t * fixture.oStride + h * fixture.headDim + d]+ }+ }+ }+ return compact+ }++ private static func runTurboQuantPackedAndCompare() throws {+ let headDim = 256+ let qHeads = 4+ let kvHeads = 2+ let start = 5+ let chunk = 3+ let kvValid = start + chunk+ let window = 6+ let qStride = qHeads * headDim+ let kvStride = kvHeads * headDim+ let oStride = qStride+ let layer: UInt32 = 2+ let rotationSeed: UInt32 = 0xA11CE++ var rng = SeedTree(0xA910).key("prefill-tq-k4v4")+ let q = (0..<(chunk * qStride)).map { _ in rng.uniform(-0.35, 0.35) }+ let k = (0..<(kvValid * kvStride)).map { _ in rng.uniform(-0.35, 0.35) }+ let v = (0..<(kvValid * kvStride)).map { _ in rng.uniform(-0.35, 0.35) }++ let keyLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,+ headDim: headDim,+ numKVHeads: kvHeads)+ let valueLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,+ headDim: headDim,+ numKVHeads: kvHeads)++ let ctx = try MetalContext()+ let prefill = try PrefillAttention(context: ctx)+ let quant = try TurboQuantQuant(context: ctx)++ guard let qBuf = Fp16Buffer.make(ctx.device, values: q),+ let kBuf = Fp16Buffer.make(ctx.device, values: k),+ let vBuf = Fp16Buffer.make(ctx.device, values: v),+ let outBuf = Fp16Buffer.make(ctx.device, count: chunk * oStride),+ let keyCache = ctx.device.makeBuffer(length: kvValid * keyLayout.bytesPerToken,+ options: .storageModeShared),+ let valueCache = ctx.device.makeBuffer(length: kvValid * valueLayout.bytesPerToken,+ options: .storageModeShared) else {+ Issue.record("alloc failed")+ return+ }++ let whtParams = TurboQuantWHTParams(numHeads: UInt32(kvHeads),+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)+ let keyWrite = TurboQuantKVWriteParams(d: UInt32(headDim),+ numHeads: UInt32(kvHeads),+ roleLayout: keyLayout)+ let valueWrite = TurboQuantKVWriteParams(d: UInt32(headDim),+ numHeads: UInt32(kvHeads),+ roleLayout: valueLayout)+ let keyBulk = TurboQuantKVBulkWriteParams(kv: keyWrite,+ tokenCount: kvValid,+ dstTokenBase: 0,+ cacheTokenCapacity: kvValid,+ sourceTokenStrideElements: kvStride)+ let valueBulk = TurboQuantKVBulkWriteParams(kv: valueWrite,+ tokenCount: kvValid,+ dstTokenBase: 0,+ cacheTokenCapacity: kvValid,+ sourceTokenStrideElements: kvStride)+ let prefillParams = PrefillAttentionParams(+ startPosition: UInt32(start),+ queryCount: UInt32(chunk),+ headDim: UInt32(headDim),+ numQHeads: UInt32(qHeads),+ numKVHeads: UInt32(kvHeads),+ kvValidCount: UInt32(kvValid),+ slidingWindow: UInt32(window),+ kvTokenStrideElements: UInt32(kvStride),+ qTokenStrideElements: UInt32(qStride),+ oTokenStrideElements: UInt32(oStride),+ scale: 1.0)+ let tqParams = PrefillTurboQuantAttentionParams(prefill: prefillParams,+ layer: layer,+ rotationSeed: rotationSeed,+ keyLayout: keyLayout,+ valueLayout: valueLayout)++ let cb = ctx.queue.makeCommandBuffer()!+ try quant.encodeKVWriteWHTBulk(commandBuffer: cb,+ x: kBuf,+ cache: keyCache,+ params: keyBulk,+ whtParams: whtParams)+ try quant.encodeKVWriteWHTBulk(commandBuffer: cb,+ x: vBuf,+ cache: valueCache,+ params: valueBulk,+ whtParams: whtParams)+ prefill.encodeTurboQuantCausal(commandBuffer: cb,+ q: qBuf,+ keyCache: keyCache,+ valueCache: valueCache,+ out: outBuf,+ params: tqParams)+ cb.commit()+ cb.waitUntilCompleted()++ let actual = Fp16Buffer.read(outBuf, count: chunk * oStride)+ let keyBytes = Array(UnsafeBufferPointer(+ start: keyCache.contents().assumingMemoryBound(to: UInt8.self),+ count: keyCache.length))+ let valueBytes = Array(UnsafeBufferPointer(+ start: valueCache.contents().assumingMemoryBound(to: UInt8.self),+ count: valueCache.length))+ let materializedKey = TurboQuantRef.materializePackedCache(+ keyBytes,+ tokenCount: kvValid,+ headDim: headDim,+ numHeads: kvHeads,+ bytesPerHead: keyLayout.bytesPerHead,+ bytesPerToken: keyLayout.bytesPerToken,+ packedOffset: keyLayout.packedOffsetPerHead,+ scaleOffset: keyLayout.scaleOffsetPerHead,+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)+ let materializedValue = TurboQuantRef.materializePackedCache(+ valueBytes,+ tokenCount: kvValid,+ headDim: headDim,+ numHeads: kvHeads,+ bytesPerHead: valueLayout.bytesPerHead,+ bytesPerToken: valueLayout.bytesPerToken,+ packedOffset: valueLayout.packedOffsetPerHead,+ scaleOffset: valueLayout.scaleOffsetPerHead,+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)+ let refFixture = Fixture(q: q,+ k: materializedKey,+ v: materializedValue,+ qStride: qStride,+ kvStride: kvStride,+ oStride: oStride,+ headDim: headDim,+ qHeads: qHeads,+ kvHeads: kvHeads,+ start: start,+ chunk: chunk,+ kvValid: kvValid,+ window: window,+ scale: 1.0)+ let reference = Self.reference(refFixture)+ let compact = Self.compactOutput(actual,+ chunk: chunk,+ qHeads: qHeads,+ headDim: headDim,+ oStride: oStride)+ let maxAbs = RelError.maxAbsDiff(compact, reference)+ let rel = RelError.compute(actual: compact, reference: reference)+ #expect(maxAbs <= 3e-2, "k4v4 packed maxAbs=\(maxAbs) rel=\(rel)")+ #expect(rel <= 3e-2, "k4v4 packed rel=\(rel) maxAbs=\(maxAbs)")+ }++ private static func compactOutput(_ out: [Float],+ chunk: Int,+ qHeads: Int,+ headDim: Int,+ oStride: Int) -> [Float] {+ var compact = [Float](repeating: 0, count: chunk * qHeads * headDim)+ for t in 0..<chunk {+ for h in 0..<qHeads {+ for d in 0..<headDim {+ compact[(t * qHeads + h) * headDim + d] =+ out[t * oStride + h * headDim + d]+ }+ }+ }+ return compact+ }++ private static func reference(_ fixture: Fixture) -> [Float] {+ var out = [Float](repeating: 0, count: fixture.chunk * fixture.qHeads * fixture.headDim)+ let qPerKV = fixture.qHeads / fixture.kvHeads+ for t in 0..<fixture.chunk {+ let absQ = fixture.start + t+ let first: Int+ if fixture.window == 0 {+ first = 0+ } else {+ first = max(0, absQ + 1 - fixture.window)+ }+ let last = min(fixture.kvValid, absQ + 1)+ for qh in 0..<fixture.qHeads {+ let kvh = qh / qPerKV+ var scores: [Float] = []+ scores.reserveCapacity(last - first)+ for key in first..<last {+ var score: Float = 0+ for d in 0..<fixture.headDim {+ let qv = fixture.q[t * fixture.qStride + qh * fixture.headDim + d]+ let kv = fixture.k[key * fixture.kvStride + kvh * fixture.headDim + d]+ score += qv * kv+ }+ scores.append(score * fixture.scale)+ }+ let maxScore = scores.max() ?? -.infinity+ var denom: Float = 0+ for score in scores {+ denom += Foundation.exp(score - maxScore)+ }+ for d in 0..<fixture.headDim {+ var acc: Float = 0+ for (i, key) in (first..<last).enumerated() {+ let w = Foundation.exp(scores[i] - maxScore)+ acc += w * fixture.v[key * fixture.kvStride + kvh * fixture.headDim + d]+ }+ out[(t * fixture.qHeads + qh) * fixture.headDim + d] = denom > 0 ? acc / denom : 0+ }+ }+ }+ return out+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedLayerTailTests.swift b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedLayerTailTests.swiftnew file mode 100644index 00000000..8c2c8077--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedLayerTailTests.swift@@ -0,0 +1,93 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct FusedLayerTailTests {+ private static let d = ArchConfig.gemma4_26B_A4B.hiddenSize+ private static let eps: Float = 1e-6++ @Test func fusedLayerTail_matchesCpuReferenceTolerance_realShape() throws {+ var rng = SplitMix64(seed: 0xC0DE_7A11)+ let h2 = (0..<Self.d).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let h1 = (0..<Self.d).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let hidden = (0..<Self.d).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let wPostFFN2 = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let wPostFFN = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let layerScalar = rng.uniform(0.75, 1.25)++ let ctx = try MetalContext()+ let fused = try FusedLayerTail(context: ctx)+ guard+ let h2Buf = ctx.device.makeBuffer(bytes: h2, length: Self.bytes(h2.count), options: .storageModeShared),+ let h1Buf = ctx.device.makeBuffer(bytes: h1, length: Self.bytes(h1.count), options: .storageModeShared),+ let hiddenBuf = ctx.device.makeBuffer(bytes: hidden, length: Self.bytes(hidden.count), options: .storageModeShared),+ let w2 = ctx.device.makeBuffer(bytes: wPostFFN2,+ length: wPostFFN2.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let w = ctx.device.makeBuffer(bytes: wPostFFN,+ length: wPostFFN.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared)+ else {+ Issue.record("Failed to allocate buffers")+ return+ }++ guard let commandBuffer = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to create command buffer")+ return+ }+ fused.encode(commandBuffer: commandBuffer,+ h2: h2Buf,+ h1: h1Buf,+ hidden: hiddenBuf,+ postFFN2Weight: w2,+ postFFNWeight: w,+ d: UInt32(Self.d),+ eps: Self.eps,+ layerScalar: layerScalar)+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ if let error = commandBuffer.error { throw error }++ let ref = Self.cpuReference(h2: h2,+ h1: h1,+ hidden: hidden,+ wPostFFN2: wPostFFN2,+ wPostFFN: wPostFFN,+ layerScalar: layerScalar)+ var maxAbs: Float = 0+ var refNorm: Float = 0+ for i in 0..<Self.d {+ let got = Float(hiddenBuf.contents().load(fromByteOffset: i * MemoryLayout<Float16>.size,+ as: Float16.self))+ maxAbs = max(maxAbs, abs(got - ref[i]))+ refNorm = max(refNorm, abs(ref[i]))+ }+ let rel = maxAbs / max(refNorm, 1e-6)+ #expect(rel < 4e-3, "rel=\(rel) maxAbs=\(maxAbs) refNorm=\(refNorm)")+ }++ private static func cpuReference(h2: [Float16],+ h1: [Float16],+ hidden: [Float16],+ wPostFFN2: [UInt16],+ wPostFFN: [UInt16],+ layerScalar: Float) -> [Float] {+ let w2 = wPostFFN2.map { Quantization.bf16ToFloat($0) }+ let w = wPostFFN.map { Quantization.bf16ToFloat($0) }+ let h2Norm = RmsNormRef.apply(x: h2.map(Float.init), weight: w2, eps: eps)+ .map { Float(Float16($0)) }+ let h12 = zip(h1, h2Norm).map { Float(Float16(Float($0.0) + $0.1)) }+ let h12Norm = RmsNormRef.apply(x: h12, weight: w, eps: eps)+ .map { Float(Float16($0)) }+ let hScale = Float(Float16(layerScalar))+ return zip(hidden, h12Norm).map { Float(Float16(Float(Float16(Float($0.0) + $0.1)) * hScale)) }+ }++ private static func bytes(_ count: Int) -> Int {+ count * MemoryLayout<Float16>.size+ }++}diff --git a/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedPostAttentionSetupTests.swift b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedPostAttentionSetupTests.swiftnew file mode 100644index 00000000..bcd23254--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedPostAttentionSetupTests.swift@@ -0,0 +1,124 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct FusedPostAttentionSetupTests {+ private static let d = ArchConfig.gemma4_26B_A4B.hiddenSize+ private static let eps: Float = 1e-6++ @Test func fusedPostAttentionSetup_matchesPrimitiveChainBitwise_realShape() throws {+ var rng = SplitMix64(seed: 0x9057_A77E)+ let hidden = (0..<Self.d).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let attn = (0..<Self.d).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let wPost = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let wPre = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let wPre2 = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }++ let ctx = try MetalContext()+ let rms = try RMSNorm(context: ctx)+ let fused = try FusedPostAttentionSetup(context: ctx)++ guard+ let hiddenLegacy = ctx.device.makeBuffer(bytes: hidden, length: Self.bytes(Self.d), options: .storageModeShared),+ let attnLegacy = ctx.device.makeBuffer(bytes: attn, length: Self.bytes(Self.d), options: .storageModeShared),+ let denseLegacy = ctx.device.makeBuffer(length: Self.bytes(Self.d), options: .storageModeShared),+ let routedLegacy = ctx.device.makeBuffer(length: Self.bytes(Self.d), options: .storageModeShared),+ let routerLegacy = ctx.device.makeBuffer(length: Self.bytes(Self.d), options: .storageModeShared),+ let hiddenFused = ctx.device.makeBuffer(bytes: hidden, length: Self.bytes(Self.d), options: .storageModeShared),+ let attnFused = ctx.device.makeBuffer(bytes: attn, length: Self.bytes(Self.d), options: .storageModeShared),+ let denseFused = ctx.device.makeBuffer(length: Self.bytes(Self.d), options: .storageModeShared),+ let routedFused = ctx.device.makeBuffer(length: Self.bytes(Self.d), options: .storageModeShared),+ let routerFused = ctx.device.makeBuffer(length: Self.bytes(Self.d), options: .storageModeShared),+ let wPostBuf = ctx.device.makeBuffer(bytes: wPost,+ length: wPost.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let wPreBuf = ctx.device.makeBuffer(bytes: wPre,+ length: wPre.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let wPre2Buf = ctx.device.makeBuffer(bytes: wPre2,+ length: wPre2.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared)+ else {+ Issue.record("Failed to allocate buffers")+ return+ }++ guard let attentionNormCB = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to allocate command buffer")+ return+ }+ rms.encodeBF16W(commandBuffer: attentionNormCB,+ x: attnLegacy,+ weight: wPostBuf,+ out: attnLegacy,+ d: UInt32(Self.d),+ eps: Self.eps)+ attentionNormCB.commit()+ attentionNormCB.waitUntilCompleted()+ if let error = attentionNormCB.error {+ Issue.record("Command buffer failed: \(error)")+ return+ }++ let hiddenPointer = hiddenLegacy.contents().assumingMemoryBound(to: Float16.self)+ let attentionPointer = attnLegacy.contents().assumingMemoryBound(to: Float16.self)+ for index in 0..<Self.d {+ hiddenPointer[index] += attentionPointer[index]+ }++ guard let cb = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to allocate command buffer")+ return+ }+ rms.encodeBF16W(commandBuffer: cb,+ x: hiddenLegacy,+ weight: wPreBuf,+ out: denseLegacy,+ d: UInt32(Self.d),+ eps: Self.eps)+ rms.encodeBF16W(commandBuffer: cb,+ x: hiddenLegacy,+ weight: wPre2Buf,+ out: routedLegacy,+ d: UInt32(Self.d),+ eps: Self.eps)+ rms.encodeNoScale(commandBuffer: cb,+ x: hiddenLegacy,+ out: routerLegacy,+ d: UInt32(Self.d),+ eps: Self.eps)+ fused.encode(commandBuffer: cb,+ hidden: hiddenFused,+ attn: attnFused,+ denseX: denseFused,+ routedX: routedFused,+ routerX: routerFused,+ postAttentionWeight: wPostBuf,+ preFFNWeight: wPreBuf,+ preFFN2Weight: wPre2Buf,+ d: UInt32(Self.d),+ eps: Self.eps)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ Issue.record("Command buffer failed: \(err)")+ return+ }++ #expect(Self.bufferBytes(hiddenLegacy) == Self.bufferBytes(hiddenFused))+ #expect(Self.bufferBytes(denseLegacy) == Self.bufferBytes(denseFused))+ #expect(Self.bufferBytes(routedLegacy) == Self.bufferBytes(routedFused))+ #expect(Self.bufferBytes(routerLegacy) == Self.bufferBytes(routerFused))+ }++ private static func bytes(_ count: Int) -> Int {+ count * MemoryLayout<Float16>.size+ }++ private static func bufferBytes(_ buffer: MTLBuffer) -> [UInt8] {+ let ptr = buffer.contents().assumingMemoryBound(to: UInt8.self)+ return Array(UnsafeBufferPointer(start: ptr, count: Self.bytes(Self.d)))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVEpilogueTests.swift b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVEpilogueTests.swiftnew file mode 100644index 00000000..8198cb81--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVEpilogueTests.swift@@ -0,0 +1,158 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct FusedQKVEpilogueTests {+ @Test func fusedQKVEpilogue_matchesLegacyChainBitwise_swaShape() throws {+ try Self.expectMatchesLegacy(numQHeads: 16,+ numKVHeads: 8,+ headDim: 256,+ position: 17,+ theta: 10_000.0,+ rotatedPairs: 128,+ seed: 0x714D_E911)+ }++ @Test func fusedQKVEpilogue_matchesLegacyChainBitwise_fullShape() throws {+ try Self.expectMatchesLegacy(numQHeads: 16,+ numKVHeads: 2,+ headDim: 512,+ position: 23,+ theta: 1_000_000.0,+ rotatedPairs: 64,+ seed: 0x714D_F211)+ }++ private static func expectMatchesLegacy(numQHeads: Int,+ numKVHeads: Int,+ headDim: Int,+ position: Int,+ theta: Float,+ rotatedPairs: UInt32,+ seed: UInt64) throws {+ var rng = SplitMix64(seed: seed)+ let qCount = numQHeads * headDim+ let kvCount = numKVHeads * headDim+ let q = (0..<qCount).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let k = (0..<kvCount).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let v = (0..<kvCount).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let qWeight = (0..<headDim).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let kWeight = (0..<headDim).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }++ let ctx = try MetalContext()+ let rms = try RMSNorm(context: ctx)+ let rope = try RoPE(context: ctx)+ let fused = try FusedQKVEpilogue(context: ctx)++ guard+ let qLegacy = ctx.device.makeBuffer(bytes: q, length: Self.bytes(qCount), options: .storageModeShared),+ let kLegacy = ctx.device.makeBuffer(bytes: k, length: Self.bytes(kvCount), options: .storageModeShared),+ let vLegacy = ctx.device.makeBuffer(bytes: v,+ length: Self.bytes(kvCount),+ options: .storageModeShared),+ let qFused = ctx.device.makeBuffer(bytes: q, length: Self.bytes(qCount), options: .storageModeShared),+ let kFused = ctx.device.makeBuffer(bytes: k, length: Self.bytes(kvCount), options: .storageModeShared),+ let vFused = ctx.device.makeBuffer(bytes: v, length: Self.bytes(kvCount), options: .storageModeShared),+ let qW = ctx.device.makeBuffer(bytes: qWeight,+ length: qWeight.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let kW = ctx.device.makeBuffer(bytes: kWeight,+ length: kWeight.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared)+ else {+ Issue.record("Failed to allocate buffers")+ return+ }++ guard let cb = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to allocate command buffer")+ return+ }+ rms.encodeBF16WPerHead(commandBuffer: cb,+ x: qLegacy,+ weight: qW,+ out: qLegacy,+ headDim: UInt32(headDim),+ numHeads: numQHeads,+ eps: 1e-6)+ rms.encodeBF16WPerHead(commandBuffer: cb,+ x: kLegacy,+ weight: kW,+ out: kLegacy,+ headDim: UInt32(headDim),+ numHeads: numKVHeads,+ eps: 1e-6)+ rms.encodeNoScalePerHead(commandBuffer: cb,+ x: vLegacy,+ out: vLegacy,+ headDim: UInt32(headDim),+ numHeads: numKVHeads,+ eps: 1e-6)+ if rotatedPairs * 2 == UInt32(headDim) {+ rope.encodeDefaultNeox(commandBuffer: cb,+ data: qLegacy,+ position: UInt32(position),+ headDim: UInt32(headDim),+ numHeads: UInt32(numQHeads),+ theta: theta)+ rope.encodeDefaultNeox(commandBuffer: cb,+ data: kLegacy,+ position: UInt32(position),+ headDim: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ theta: theta)+ } else {+ rope.encodeProportionalNeox(commandBuffer: cb,+ data: qLegacy,+ position: UInt32(position),+ headDim: UInt32(headDim),+ numHeads: UInt32(numQHeads),+ rotatedPairs: rotatedPairs,+ theta: theta)+ rope.encodeProportionalNeox(commandBuffer: cb,+ data: kLegacy,+ position: UInt32(position),+ headDim: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ rotatedPairs: rotatedPairs,+ theta: theta)+ }+ fused.encode(commandBuffer: cb,+ q: qFused,+ k: kFused,+ v: vFused,+ qWeight: qW,+ kWeight: kW,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ position: UInt32(position),+ theta: theta,+ rotatedPairs: rotatedPairs,+ eps: 1e-6)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ Issue.record("Command buffer failed: \(err)")+ return+ }++ #expect(Self.bufferBytes(qLegacy, count: qCount) == Self.bufferBytes(qFused, count: qCount),+ "Q mismatch for headDim=\(headDim) kvHeads=\(numKVHeads)")+ #expect(Self.bufferBytes(kLegacy, count: kvCount) == Self.bufferBytes(kFused, count: kvCount),+ "K mismatch for headDim=\(headDim) kvHeads=\(numKVHeads)")+ #expect(Self.bufferBytes(vLegacy, count: kvCount) == Self.bufferBytes(vFused, count: kvCount),+ "V mismatch for headDim=\(headDim) kvHeads=\(numKVHeads)")+ }++ private static func bytes(_ count: Int) -> Int {+ count * MemoryLayout<Float16>.size+ }++ private static func bufferBytes(_ buffer: MTLBuffer, count: Int) -> [UInt8] {+ Array(UnsafeBufferPointer(start: buffer.contents().assumingMemoryBound(to: UInt8.self),+ count: bytes(count)))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVGEMVTests.swift b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVGEMVTests.swiftnew file mode 100644index 00000000..1919d2f8--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVGEMVTests.swift@@ -0,0 +1,139 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct FusedQKVGEMVTests {+ @Test func fusedQKVGEMV_matchesThreeGEMVs_smallShape() throws {+ try Self.expectMatches(qRows: 64, kvRows: 32, n: 128, seed: 0x5156_4745)+ }++ @Test func fusedQKVGEMV_matchesThreeGEMVs_offsetWeights() throws {+ try Self.expectMatches(qRows: 128, kvRows: 64, n: 2816, seed: 0x5156_4746,+ weightOffset: 2)+ }++ private static func expectMatches(qRows: Int,+ kvRows: Int,+ n: Int,+ seed: UInt64,+ weightOffset: Int = 0) throws {+ precondition(n % Quantization.groupSize == 0)+ var rng = SplitMix64(seed: seed)+ let q = Self.makeProjection(rows: qRows, n: n, rng: &rng, weightOffset: weightOffset)+ let k = Self.makeProjection(rows: kvRows, n: n, rng: &rng, weightOffset: weightOffset)+ let v = Self.makeProjection(rows: kvRows, n: n, rng: &rng, weightOffset: weightOffset)+ let x = (0..<n).map { _ in Float16(rng.uniform(-1.0, 1.0)) }++ let ctx = try MetalContext()+ let gemv = try DequantInt4GEMV(context: ctx)+ let fused = try FusedQKVGEMV(context: ctx)+ guard+ let qW = ctx.device.makeBuffer(bytes: q.weights, length: q.weights.count,+ options: .storageModeShared),+ let qS = ctx.device.makeBuffer(bytes: q.scales,+ length: q.scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let qB = ctx.device.makeBuffer(bytes: q.biases,+ length: q.biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let kW = ctx.device.makeBuffer(bytes: k.weights, length: k.weights.count,+ options: .storageModeShared),+ let kS = ctx.device.makeBuffer(bytes: k.scales,+ length: k.scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let kB = ctx.device.makeBuffer(bytes: k.biases,+ length: k.biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let vW = ctx.device.makeBuffer(bytes: v.weights, length: v.weights.count,+ options: .storageModeShared),+ let vS = ctx.device.makeBuffer(bytes: v.scales,+ length: v.scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let vB = ctx.device.makeBuffer(bytes: v.biases,+ length: v.biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let qLegacy = Fp16Buffer.make(ctx.device, count: qRows),+ let kLegacy = Fp16Buffer.make(ctx.device, count: kvRows),+ let vLegacy = Fp16Buffer.make(ctx.device, count: kvRows),+ let qFused = Fp16Buffer.make(ctx.device, count: qRows),+ let kFused = Fp16Buffer.make(ctx.device, count: kvRows),+ let vFused = Fp16Buffer.make(ctx.device, count: kvRows)+ else {+ Issue.record("Failed to allocate buffers")+ return+ }++ guard let cb = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to allocate command buffer")+ return+ }+ gemv.encode(commandBuffer: cb,+ weights: qW, weightsOffset: weightOffset,+ scales: qS, biases: qB,+ x: xBuf, y: qLegacy,+ m: UInt32(qRows), n: UInt32(n))+ gemv.encode(commandBuffer: cb,+ weights: kW, weightsOffset: weightOffset,+ scales: kS, biases: kB,+ x: xBuf, y: kLegacy,+ m: UInt32(kvRows), n: UInt32(n))+ gemv.encode(commandBuffer: cb,+ weights: vW, weightsOffset: weightOffset,+ scales: vS, biases: vB,+ x: xBuf, y: vLegacy,+ m: UInt32(kvRows), n: UInt32(n))+ fused.encode(commandBuffer: cb,+ qWeights: qW, qWeightsOffset: weightOffset,+ qScales: qS, qBiases: qB,+ kWeights: kW, kWeightsOffset: weightOffset,+ kScales: kS, kBiases: kB,+ vWeights: vW, vWeightsOffset: weightOffset,+ vScales: vS, vBiases: vB,+ x: xBuf,+ qOut: qFused,+ kOut: kFused,+ vOut: vFused,+ qRows: UInt32(qRows),+ kvRows: UInt32(kvRows),+ n: UInt32(n))+ cb.commit()+ cb.waitUntilCompleted()+ if let error = cb.error {+ Issue.record("Command buffer failed: \(error)")+ return+ }++ #expect(Self.bytes(qLegacy, count: qRows) == Self.bytes(qFused, count: qRows))+ #expect(Self.bytes(kLegacy, count: kvRows) == Self.bytes(kFused, count: kvRows))+ #expect(Self.bytes(vLegacy, count: kvRows) == Self.bytes(vFused, count: kvRows))+ }++ private static func makeProjection(rows: Int,+ n: Int,+ rng: inout SplitMix64,+ weightOffset: Int) -> (weights: [UInt8], scales: [UInt16], biases: [UInt16]) {+ let packedPerRow = n / 2+ let groups = n / Quantization.groupSize+ var weights = [UInt8](repeating: 0, count: rows * packedPerRow + weightOffset)+ var scales = [UInt16](repeating: 0, count: rows * groups)+ var biases = [UInt16](repeating: 0, count: rows * groups)+ for row in 0..<rows {+ let values = (0..<n).map { _ in rng.uniform(-0.5, 0.5) }+ let q = Quantization.quantizeInt4Affine(values)+ for i in 0..<packedPerRow { weights[weightOffset + row * packedPerRow + i] = q.packed[i] }+ for i in 0..<groups {+ scales[row * groups + i] = q.scales[i]+ biases[row * groups + i] = q.biases[i]+ }+ }+ return (weights, scales, biases)+ }++ private static func bytes(_ buffer: MTLBuffer, count: Int) -> [UInt8] {+ Array(UnsafeBufferPointer(start: buffer.contents().assumingMemoryBound(to: UInt8.self),+ count: count * MemoryLayout<Float16>.size))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVPipelineTests.swift b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVPipelineTests.swiftnew file mode 100644index 00000000..c8f54983--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Fusions/FusedQKVPipelineTests.swift@@ -0,0 +1,161 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct FusedQKVPipelineTests {+ @Test func fullShapeFusedPipelineMatchesThreeGEMVChainBitwise() throws {+ let qRows = 8192+ let kvRows = 1024+ let n = 2816+ let headDim = 512+ let numQHeads = 16+ let numKVHeads = 2+ let qProjection = Self.makeProjection(rows: qRows, n: n, seed: 0x5156_5049)+ let kvProjection = Self.makeProjection(rows: kvRows, n: n, seed: 0x4B56_5049)+ var rng = SplitMix64(seed: 0x585F_5049)+ let x = (0..<n).map { _ in Float16(rng.uniform(-1, 1)) }+ let qNorm = (0..<headDim).map { _ in+ Quantization.bf16Bits(rng.uniform(0.5, 1.5))+ }+ let kNorm = (0..<headDim).map { _ in+ Quantization.bf16Bits(rng.uniform(0.5, 1.5))+ }++ let ctx = try MetalContext()+ let gemv = try DequantInt4GEMV(context: ctx)+ let fusedGEMV = try FusedQKVGEMV(context: ctx)+ let rms = try RMSNorm(context: ctx)+ let rope = try RoPE(context: ctx)+ let fusedEpilogue = try FusedQKVEpilogue(context: ctx)++ guard+ let qWeights = ctx.device.makeBuffer(bytes: qProjection.weights,+ length: qProjection.weights.count,+ options: .storageModeShared),+ let qScales = ctx.device.makeBuffer(bytes: qProjection.scales,+ length: qProjection.scales.count * 2,+ options: .storageModeShared),+ let qBiases = ctx.device.makeBuffer(bytes: qProjection.biases,+ length: qProjection.biases.count * 2,+ options: .storageModeShared),+ let kvWeights = ctx.device.makeBuffer(bytes: kvProjection.weights,+ length: kvProjection.weights.count,+ options: .storageModeShared),+ let kvScales = ctx.device.makeBuffer(bytes: kvProjection.scales,+ length: kvProjection.scales.count * 2,+ options: .storageModeShared),+ let kvBiases = ctx.device.makeBuffer(bytes: kvProjection.biases,+ length: kvProjection.biases.count * 2,+ options: .storageModeShared),+ let xBuffer = Fp16Buffer.make(ctx.device, halves: x),+ let qNormBuffer = ctx.device.makeBuffer(bytes: qNorm,+ length: qNorm.count * 2,+ options: .storageModeShared),+ let kNormBuffer = ctx.device.makeBuffer(bytes: kNorm,+ length: kNorm.count * 2,+ options: .storageModeShared),+ let qLegacy = Fp16Buffer.make(ctx.device, count: qRows),+ let kLegacy = Fp16Buffer.make(ctx.device, count: kvRows),+ let vLegacy = Fp16Buffer.make(ctx.device, count: kvRows),+ let qFused = Fp16Buffer.make(ctx.device, count: qRows),+ let kFused = Fp16Buffer.make(ctx.device, count: kvRows),+ let vFused = Fp16Buffer.make(ctx.device, count: kvRows),+ let commandBuffer = ctx.queue.makeCommandBuffer()+ else {+ Issue.record("Failed to allocate full-shape QKV pipeline resources")+ return+ }++ gemv.encode(commandBuffer: commandBuffer,+ weights: qWeights, scales: qScales, biases: qBiases,+ x: xBuffer, y: qLegacy,+ m: UInt32(qRows), n: UInt32(n))+ gemv.encode(commandBuffer: commandBuffer,+ weights: kvWeights, scales: kvScales, biases: kvBiases,+ x: xBuffer, y: kLegacy,+ m: UInt32(kvRows), n: UInt32(n))+ gemv.encode(commandBuffer: commandBuffer,+ weights: kvWeights, scales: kvScales, biases: kvBiases,+ x: xBuffer, y: vLegacy,+ m: UInt32(kvRows), n: UInt32(n))+ rms.encodeBF16WPerHead(commandBuffer: commandBuffer,+ x: qLegacy, weight: qNormBuffer, out: qLegacy,+ headDim: UInt32(headDim), numHeads: numQHeads, eps: 1e-6)+ rms.encodeBF16WPerHead(commandBuffer: commandBuffer,+ x: kLegacy, weight: kNormBuffer, out: kLegacy,+ headDim: UInt32(headDim), numHeads: numKVHeads, eps: 1e-6)+ rms.encodeNoScalePerHead(commandBuffer: commandBuffer,+ x: vLegacy, out: vLegacy,+ headDim: UInt32(headDim), numHeads: numKVHeads, eps: 1e-6)+ rope.encodeProportionalNeox(commandBuffer: commandBuffer,+ data: qLegacy,+ position: 12,+ headDim: UInt32(headDim),+ numHeads: UInt32(numQHeads),+ rotatedPairs: 64,+ theta: 1_000_000)+ rope.encodeProportionalNeox(commandBuffer: commandBuffer,+ data: kLegacy,+ position: 12,+ headDim: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ rotatedPairs: 64,+ theta: 1_000_000)++ fusedGEMV.encode(commandBuffer: commandBuffer,+ qWeights: qWeights, qScales: qScales, qBiases: qBiases,+ kWeights: kvWeights, kScales: kvScales, kBiases: kvBiases,+ vWeights: kvWeights, vScales: kvScales, vBiases: kvBiases,+ x: xBuffer,+ qOut: qFused, kOut: kFused, vOut: vFused,+ qRows: UInt32(qRows), kvRows: UInt32(kvRows), n: UInt32(n))+ fusedEpilogue.encode(commandBuffer: commandBuffer,+ q: qFused, k: kFused, v: vFused,+ qWeight: qNormBuffer, kWeight: kNormBuffer,+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ position: 12,+ theta: 1_000_000,+ rotatedPairs: 64,+ eps: 1e-6)++ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ if let error = commandBuffer.error {+ Issue.record("Command buffer failed: \(error)")+ return+ }++ #expect(Self.bytes(qLegacy, count: qRows) == Self.bytes(qFused, count: qRows))+ #expect(Self.bytes(kLegacy, count: kvRows) == Self.bytes(kFused, count: kvRows))+ #expect(Self.bytes(vLegacy, count: kvRows) == Self.bytes(vFused, count: kvRows))+ }++ private static func makeProjection(rows: Int,+ n: Int,+ seed: UInt64) -> (weights: [UInt8],+ scales: [UInt16],+ biases: [UInt16]) {+ let packedCount = rows * n / 2+ let groupCount = rows * n / Quantization.groupSize+ let weights = (0..<packedCount).map { index in+ UInt8(truncatingIfNeeded: (UInt64(index) &* 0x9E37_79B9) &+ seed)+ }+ let scales = (0..<groupCount).map { index in+ Quantization.bf16Bits(0.015625 + Float(index % 7) * 0.001953125)+ }+ let biases = (0..<groupCount).map { index in+ Quantization.bf16Bits(-0.125 + Float(index % 5) * 0.03125)+ }+ return (weights, scales, biases)+ }++ private static func bytes(_ buffer: MTLBuffer, count: Int) -> [UInt8] {+ Array(UnsafeBufferPointer(+ start: buffer.contents().assumingMemoryBound(to: UInt8.self),+ count: count * MemoryLayout<Float16>.size))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Fusions/LMHeadChainInt4Tests.swift b/Tests/TurboFieldfare/Core/Kernels/Fusions/LMHeadChainInt4Tests.swiftnew file mode 100644index 00000000..bfaf7528--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Fusions/LMHeadChainInt4Tests.swift@@ -0,0 +1,225 @@+import Accelerate+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct LMHeadChainInt4Tests {+ private static let rmsEps: Float = 1e-6++ private static func cpuGreedy(hiddenFp16: [Float16],+ normWeightBF16: [UInt16],+ rows: [Quantization.Int4AffineRow],+ d: Int,+ v: Int) -> UInt32 {+ let hidden = hiddenFp16.map(Float.init)+ let normWeight = normWeightBF16.map(Quantization.bf16ToFloat)+ let normed = RmsNormRef.apply(x: hidden, weight: normWeight, eps: rmsEps)+ .map { Float(Float16($0)) }++ var bestValue: Float = -.infinity+ var bestIndex: UInt32 = 0+ for row in 0..<v {+ let dequantized = Quantization.dequantizeInt4Affine(rows[row], n: d)+ var dot: Float = 0+ dequantized.withUnsafeBufferPointer { weights in+ normed.withUnsafeBufferPointer { input in+ vDSP_dotpr(weights.baseAddress!, 1,+ input.baseAddress!, 1,+ &dot,+ vDSP_Length(d))+ }+ }+ if dot > bestValue {+ bestValue = dot+ bestIndex = UInt32(row)+ }+ }+ return bestIndex+ }++ private static func packRows(_ rows: [Quantization.Int4AffineRow])+ -> (packed: [UInt8], scales: [UInt16], biases: [UInt16]) {+ let packedRowCount = rows[0].packed.count+ let groupCount = rows[0].scales.count+ var packed = [UInt8](repeating: 0, count: rows.count * packedRowCount)+ var scales = [UInt16](repeating: 0, count: rows.count * groupCount)+ var biases = [UInt16](repeating: 0, count: rows.count * groupCount)+ for row in rows.indices {+ for index in 0..<packedRowCount {+ packed[row * packedRowCount + index] = rows[row].packed[index]+ }+ for index in 0..<groupCount {+ scales[row * groupCount + index] = rows[row].scales[index]+ biases[row * groupCount + index] = rows[row].biases[index]+ }+ }+ return (packed, scales, biases)+ }++ private static func gpuGreedy(hiddenFp16: [Float16],+ normBF16: [UInt16],+ rows: [Quantization.Int4AffineRow],+ d: Int,+ v: Int,+ hiddenOffset: Int = 0) throws -> UInt32 {+ let (packed, scales, biases) = Self.packRows(rows)+ let context = try MetalContext()+ let chain = try LMHeadChainInt4(context: context, maxD: d, maxVocab: v)++ guard let hidden = context.device.makeBuffer(+ bytes: hiddenFp16,+ length: hiddenFp16.count * MemoryLayout<Float16>.stride,+ options: .storageModeShared),+ let norm = context.device.makeBuffer(+ bytes: normBF16,+ length: normBF16.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared),+ let weights = context.device.makeBuffer(+ bytes: packed,+ length: packed.count,+ options: .storageModeShared),+ let scaleBuffer = context.device.makeBuffer(+ bytes: scales,+ length: scales.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared),+ let biasBuffer = context.device.makeBuffer(+ bytes: biases,+ length: biases.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared),+ let output = context.device.makeBuffer(+ length: MemoryLayout<UInt32>.stride,+ options: .storageModeShared),+ let commandBuffer = context.queue.makeCommandBuffer() else {+ Issue.record("buffer allocation failed")+ return 0+ }++ chain.encodeGreedyDecode(commandBuffer: commandBuffer,+ hidden: hidden,+ hiddenOffset: hiddenOffset,+ normWeight: norm,+ weights: weights,+ scales: scaleBuffer,+ biases: biasBuffer,+ outToken: output,+ d: UInt32(d),+ vocab: UInt32(v))+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ return output.contents().load(as: UInt32.self)+ }++ @Test func rawGreedyMatchesCPUReference() throws {+ let d = 64+ let v = 1024+ var rng = SplitMix64(seed: 0x1A4E_4EAD_2026_0603)+ let hidden = (0..<d).map { _ in Float16(rng.uniform(-1, 1)) }+ let norm = (0..<d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let rows = (0..<v).map { _ in+ Quantization.quantizeInt4Affine((0..<d).map { _ in rng.uniform(-1, 1) })+ }++ let reference = Self.cpuGreedy(hiddenFp16: hidden,+ normWeightBF16: norm,+ rows: rows,+ d: d,+ v: v)+ let result = try Self.gpuGreedy(hiddenFp16: hidden,+ normBF16: norm,+ rows: rows,+ d: d,+ v: v)+ #expect(result == reference)+ }++ @Test func allInvalidCandidatesFallBackToZero() throws {+ let d = 64+ let v = 1024+ let hidden = [Float16](repeating: .nan, count: d)+ let norm = (0..<d).map { _ in Quantization.bf16Bits(1) }+ let rows = (0..<v).map { _ in+ Quantization.quantizeInt4Affine([Float](repeating: 0.25, count: d))+ }++ let result = try Self.gpuGreedy(hiddenFp16: hidden,+ normBF16: norm,+ rows: rows,+ d: d,+ v: v)+ #expect(result == 0)+ }++ @Test(arguments: [1024, 2048, 4096])+ func greedyMatchesCPUReferenceAcrossVocabSizes(v: Int) throws {+ let d = 64+ let target = v - 3+ let hidden = (0..<d).map { Float16(0.25 + Float($0 % 7) * 0.01) }+ let norm = (0..<d).map { _ in Quantization.bf16Bits(1) }+ let rows = (0..<v).map { row in+ let value: Float = row == target ? 1 : -0.5+ return Quantization.quantizeInt4Affine([Float](repeating: value, count: d))+ }++ let reference = Self.cpuGreedy(hiddenFp16: hidden,+ normWeightBF16: norm,+ rows: rows,+ d: d,+ v: v)+ let result = try Self.gpuGreedy(hiddenFp16: hidden,+ normBF16: norm,+ rows: rows,+ d: d,+ v: v)+ #expect(result == reference)+ }++ @Test func tiesResolveToLowestIndex() throws {+ let d = 64+ let v = 1024+ let hidden = (0..<d).map { Float16(0.2 + Float($0 % 5) * 0.02) }+ let norm = (0..<d).map { _ in Quantization.bf16Bits(1) }+ let rows = (0..<v).map { row in+ let value: Float = (row == 17 || row == 311) ? 1 : -0.25+ return Quantization.quantizeInt4Affine([Float](repeating: value, count: d))+ }++ let result = try Self.gpuGreedy(hiddenFp16: hidden,+ normBF16: norm,+ rows: rows,+ d: d,+ v: v)+ #expect(result == 17)+ }++ @Test func readsSelectedHiddenRow() throws {+ let d = 64+ let v = 1024+ let rowStride = d + 16+ let selectedRow = 3+ let target = 777+ var hiddenRows = [Float16](repeating: 0, count: 5 * rowStride)+ for row in 0..<5 {+ for index in 0..<d {+ let value = row == selectedRow+ ? Float(0.25 + Float(index % 7) * 0.01)+ : Float(-0.4 - Float(index % 5) * 0.01)+ hiddenRows[row * rowStride + index] = Float16(value)+ }+ }+ let norm = (0..<d).map { _ in Quantization.bf16Bits(1) }+ let rows = (0..<v).map { row in+ let value: Float = row == target ? 1 : -0.25+ return Quantization.quantizeInt4Affine([Float](repeating: value, count: d))+ }++ let result = try Self.gpuGreedy(+ hiddenFp16: hiddenRows,+ normBF16: norm,+ rows: rows,+ d: d,+ v: v,+ hiddenOffset: selectedRow * rowStride * MemoryLayout<Float16>.stride)+ #expect(result == UInt32(target))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+BulkWrite.swift b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+BulkWrite.swiftnew file mode 100644index 00000000..cd10fac8--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+BulkWrite.swift@@ -0,0 +1,42 @@+import Testing++@testable import TurboFieldfare++extension TurboQuantTests {+ @Test func fusedBulkWriteMatchesRepeatedScalarWrites() throws {+ try Self.runBulkWriteMatchesRepeatedScalarWrites()+ }++ @Test func fusedBulkWriteUsesDestinationTokenBase() throws {+ try Self.runBulkWriteMatchesRepeatedScalarWrites(dstTokenBase: 2)+ }++ @Test func bulkWriteRejectsOutOfRangeTokenCount() throws {+ let d = 256+ let numHeads = 2+ let layout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,+ headDim: d,+ numKVHeads: numHeads)+ let context = try Self.makeContext()+ let quant = try TurboQuantQuant(context: context)+ let commandBuffer = context.queue.makeCommandBuffer()!+ let input = Self.makeBuffer(context, count: numHeads * d, type: Float16.self)+ let cache = Self.makeBuffer(context, count: layout.bytesPerToken, type: UInt8.self)+ let write = TurboQuantKVWriteParams(d: UInt32(d),+ numHeads: UInt32(numHeads),+ roleLayout: layout)+ let params = TurboQuantKVBulkWriteParams(kv: write,+ tokenCount: 2,+ dstTokenBase: 0,+ cacheTokenCapacity: 1,+ sourceTokenStrideElements: numHeads * d)++ #expect(throws: TurboQuantKVBulkWriteError.self) {+ try quant.encodeKVWriteWHTBulk(commandBuffer: commandBuffer,+ x: input,+ cache: cache,+ params: params,+ whtParams: TurboQuantWHTParams())+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+Quantization.swift b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+Quantization.swiftnew file mode 100644index 00000000..f6c761a1--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+Quantization.swift@@ -0,0 +1,11 @@+import Testing++extension TurboQuantTests {+ @Test func packedRoundTripD256() throws {+ try Self.runPackedRoundTrip(headDim: 256)+ }++ @Test func packedRoundTripD512() throws {+ try Self.runPackedRoundTrip(headDim: 512)+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests.swift b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests.swiftnew file mode 100644index 00000000..cd6bc381--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests.swift@@ -0,0 +1,150 @@+import Foundation+import Metal+import Testing+import TurboFieldfareValidationSupport++@testable import TurboFieldfare++@Suite struct TurboQuantTests {+ static func makeContext() throws -> MetalContext {+ try MetalContext()+ }++ static func makeBuffer<T>(_ context: MetalContext, count: Int, type: T.Type) -> MTLBuffer {+ context.device.makeBuffer(length: count * MemoryLayout<T>.stride,+ options: .storageModeShared)!+ }++ static func bufferWith<T>(_ context: MetalContext, _ values: [T]) -> MTLBuffer {+ let buffer = makeBuffer(context, count: values.count, type: T.self)+ values.withUnsafeBytes { source in+ if let base = source.baseAddress {+ memcpy(buffer.contents(), base, source.count)+ }+ }+ return buffer+ }++ static func runPackedRoundTrip(headDim: Int) throws {+ let numHeads = headDim == 256 ? 8 : 2+ let tokenCount = 2+ let layer: UInt32 = 3+ let rotationSeed: UInt32 = 0x51A7_1010+ var random = SeedTree(0x51A7_1010).key("packed-round-trip-d\(headDim)")+ let input = (0..<(tokenCount * numHeads * headDim)).map {+ _ in Float16(random.uniform(-1, 1))+ }+ let layout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,+ headDim: headDim,+ numKVHeads: numHeads)+ let context = try makeContext()+ let quant = try TurboQuantQuant(context: context)+ let inputBuffer = bufferWith(context, input)+ let cache = makeBuffer(context,+ count: tokenCount * layout.bytesPerToken,+ type: UInt8.self)+ let params = TurboQuantKVWriteParams(d: UInt32(headDim),+ numHeads: UInt32(numHeads),+ roleLayout: layout)+ let transform = TurboQuantWHTParams(numHeads: UInt32(numHeads),+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)++ let commandBuffer = context.queue.makeCommandBuffer()!+ quant.encodeKVWriteWHT(commandBuffer: commandBuffer,+ x: inputBuffer,+ cache: cache,+ params: params,+ whtParams: transform,+ pairs: tokenCount * numHeads)+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ if let error = commandBuffer.error { throw error }++ let pointer = cache.contents().bindMemory(to: UInt8.self, capacity: cache.length)+ let cacheBytes = Array(UnsafeBufferPointer(start: pointer, count: cache.length))+ let actual = TurboQuantRef.materializePackedCache(+ cacheBytes,+ tokenCount: tokenCount,+ headDim: headDim,+ numHeads: numHeads,+ bytesPerHead: layout.bytesPerHead,+ bytesPerToken: layout.bytesPerToken,+ packedOffset: layout.packedOffsetPerHead,+ scaleOffset: layout.scaleOffsetPerHead,+ layer: layer,+ rotationSeed: rotationSeed,+ applyRotation: true)+ let expected = input.map(Float.init)+ let squaredError = zip(actual, expected).reduce(Float.zero) { result, pair in+ let error = pair.0 - pair.1+ return result + error * error+ }+ let squaredReference = expected.reduce(Float.zero) { $0 + $1 * $1 }+ #expect((squaredError / squaredReference).squareRoot() < 0.16)+ }++ static func runBulkWriteMatchesRepeatedScalarWrites(dstTokenBase: Int = 0) throws {+ let d = 256+ let numHeads = 2+ let tokenCount = 3+ let capacity = dstTokenBase + tokenCount + 1+ let layout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,+ headDim: d,+ numKVHeads: numHeads)+ var random = SeedTree(0xB117).key("tq-bulk-k4-base-\(dstTokenBase)")+ let input = (0..<(tokenCount * numHeads * d)).map {+ _ in Float16(random.uniform(-1, 1))+ }+ let context = try makeContext()+ let quant = try TurboQuantQuant(context: context)+ let inputBuffer = bufferWith(context, input)+ let scalar = makeBuffer(context,+ count: capacity * layout.bytesPerToken,+ type: UInt8.self)+ let bulk = makeBuffer(context,+ count: capacity * layout.bytesPerToken,+ type: UInt8.self)+ memset(scalar.contents(), 0xA5, scalar.length)+ memset(bulk.contents(), 0xA5, bulk.length)+ let params = TurboQuantKVWriteParams(d: UInt32(d),+ numHeads: UInt32(numHeads),+ roleLayout: layout)+ let bulkParams = TurboQuantKVBulkWriteParams(+ kv: params,+ tokenCount: tokenCount,+ dstTokenBase: dstTokenBase,+ cacheTokenCapacity: capacity,+ sourceTokenStrideElements: numHeads * d)++ let commandBuffer = context.queue.makeCommandBuffer()!+ for token in 0..<tokenCount {+ var tokenParams = params+ tokenParams.tokenBase = UInt32(dstTokenBase + token)+ quant.encodeKVWriteWHT(+ commandBuffer: commandBuffer,+ x: inputBuffer,+ xOffset: token * numHeads * d * MemoryLayout<Float16>.stride,+ cache: scalar,+ cacheOffset: (dstTokenBase + token) * layout.bytesPerToken,+ params: tokenParams,+ whtParams: TurboQuantWHTParams(),+ pairs: numHeads)+ }+ try quant.encodeKVWriteWHTBulk(commandBuffer: commandBuffer,+ x: inputBuffer,+ cache: bulk,+ params: bulkParams,+ whtParams: TurboQuantWHTParams())+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ if let error = commandBuffer.error { throw error }++ let lhs = scalar.contents().bindMemory(to: UInt8.self, capacity: scalar.length)+ let rhs = bulk.contents().bindMemory(to: UInt8.self, capacity: bulk.length)+ for index in 0..<scalar.length {+ #expect(lhs[index] == rhs[index], "bulk cache byte \(index)")+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/MoE/MoEFusedFFNTests.swift b/Tests/TurboFieldfare/Core/Kernels/MoE/MoEFusedFFNTests.swiftnew file mode 100644index 00000000..0f85ab59--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/MoE/MoEFusedFFNTests.swift@@ -0,0 +1,198 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct MoEFusedFFNTests {+ private static let dimension = 128+ private static let intermediate = 64+ private static let topK = 8++ private struct RoutedBlob {+ let bytes: [UInt8]+ let offsets: MoEExpertOffsets+ }++ @Test func productionRoutedPipelineAndHitSplitMatchReference() throws {+ var rng = SeedTree(0x2D3).key("production-routed-moe")+ func matrix(rows: Int, columns: Int) -> [[Float]] {+ (0..<rows).map { _ in+ (0..<columns).map { _ in rng.uniform(-0.4, 0.4) }+ }+ }++ var gates = [[[Float]]]()+ var ups = [[[Float]]]()+ var downs = [[[Float]]]()+ for _ in 0..<Self.topK {+ gates.append(matrix(rows: Self.intermediate, columns: Self.dimension))+ ups.append(matrix(rows: Self.intermediate, columns: Self.dimension))+ downs.append(matrix(rows: Self.dimension, columns: Self.intermediate))+ }+ let x = (0..<Self.dimension).map { _ in+ Float(Float16(rng.uniform(-0.5, 0.5)))+ }+ let residual = (0..<Self.dimension).map { _ in+ Float(Float16(rng.uniform(-0.5, 0.5)))+ }+ let routingWeights = (0..<Self.topK).map {+ Float(Float16(0.04 + Float($0) * 0.015))+ }+ let expected = MoeRef.applyStreamedRouted(+ x: x,+ residual: residual,+ routedGate: gates.map { rows in+ rows.map { Quantization.quantizeInt4Affine($0) }+ },+ routedUp: ups.map { rows in+ rows.map { Quantization.quantizeInt4Affine($0) }+ },+ routedDown: downs.map { rows in+ rows.map { Quantization.quantizeInt4Affine($0) }+ },+ indices: Array(0..<Self.topK),+ routingWeights: routingWeights,+ d: Self.dimension,+ f: Self.intermediate)+ let blobs = (0..<Self.topK).map {+ Self.makeBlob(gate: gates[$0], up: ups[$0], down: downs[$0])+ }++ let context = try MetalContext()+ let kernel = try MoE(context: context)+ let routedBuffers = blobs.compactMap {+ context.device.makeBuffer(bytes: $0.bytes,+ length: $0.bytes.count,+ options: .storageModeShared)+ }+ guard routedBuffers.count == Self.topK,+ let xBuffer = Fp16Buffer.make(context.device, values: x),+ let residualBuffer = Fp16Buffer.make(context.device, values: residual),+ let routingBuffer = Fp16Buffer.make(context.device, values: routingWeights),+ let fullActs = Fp16Buffer.make(+ context.device, count: Self.topK * Self.intermediate),+ let splitActs = Fp16Buffer.make(+ context.device, count: Self.topK * Self.intermediate),+ let fullOutput = Fp16Buffer.make(context.device, count: Self.dimension),+ let splitOutput = Fp16Buffer.make(context.device, count: Self.dimension),+ let lowSlots = context.device.makeBuffer(+ bytes: [UInt32](0...3),+ length: 4 * MemoryLayout<UInt32>.stride,+ options: .storageModeShared),+ let highSlots = context.device.makeBuffer(+ bytes: [UInt32](4...7),+ length: 4 * MemoryLayout<UInt32>.stride,+ options: .storageModeShared),+ let argumentBuffer = kernel.makeRoutedArgumentBuffer(+ routedBlobs: routedBuffers,+ topK: UInt32(Self.topK)) else {+ Issue.record("buffer allocation failed")+ return+ }++ let fullCommand = context.queue.makeCommandBuffer()!+ kernel.encodeRoutedPersistentPhase1U16Load(+ commandBuffer: fullCommand,+ routedArgBuffer: argumentBuffer,+ routedBlobs: routedBuffers,+ routedOffsets: blobs[0].offsets,+ x: xBuffer,+ acts: fullActs,+ d: UInt32(Self.dimension),+ f: UInt32(Self.intermediate),+ topK: UInt32(Self.topK))+ kernel.encodeRoutedPersistentPhase2Reduce(+ commandBuffer: fullCommand,+ routedArgBuffer: argumentBuffer,+ routedBlobs: routedBuffers,+ routedOffsets: blobs[0].offsets,+ acts: fullActs,+ routingWeights: routingBuffer,+ residual: residualBuffer,+ y: fullOutput,+ d: UInt32(Self.dimension),+ f: UInt32(Self.intermediate),+ topK: UInt32(Self.topK))+ fullCommand.commit()+ fullCommand.waitUntilCompleted()+ #expect(fullCommand.error == nil)++ let splitCommand = context.queue.makeCommandBuffer()!+ for (slots, activeSlots) in [([UInt32](0...3), lowSlots),+ ([UInt32](4...7), highSlots)] {+ kernel.encodeRoutedPersistentPhase1SubsetU16Load(+ commandBuffer: splitCommand,+ routedArgBuffer: argumentBuffer,+ routedBlobs: routedBuffers,+ routedOffsets: blobs[0].offsets,+ x: xBuffer,+ acts: splitActs,+ activeSlots: activeSlots,+ activeSlotIndices: slots,+ activeCount: UInt32(slots.count),+ d: UInt32(Self.dimension),+ f: UInt32(Self.intermediate),+ topK: UInt32(Self.topK))+ }+ kernel.encodeRoutedPersistentPhase2Reduce(+ commandBuffer: splitCommand,+ routedArgBuffer: argumentBuffer,+ routedBlobs: routedBuffers,+ routedOffsets: blobs[0].offsets,+ acts: splitActs,+ routingWeights: routingBuffer,+ residual: residualBuffer,+ y: splitOutput,+ d: UInt32(Self.dimension),+ f: UInt32(Self.intermediate),+ topK: UInt32(Self.topK))+ splitCommand.commit()+ splitCommand.waitUntilCompleted()+ #expect(splitCommand.error == nil)++ let full = Fp16Buffer.read(fullOutput, count: Self.dimension)+ let split = Fp16Buffer.read(splitOutput, count: Self.dimension)+ #expect(full == split)+ #expect(RelError.compute(actual: full, reference: expected)+ < Tolerance.fp16ChainedReduction)+ }++ private static func makeBlob(gate: [[Float]],+ up: [[Float]],+ down: [[Float]]) -> RoutedBlob {+ func packed(_ rows: [[Float]])+ -> (weights: [UInt8], scales: [UInt16], biases: [UInt16]) {+ let quantized = rows.map { Quantization.quantizeInt4Affine($0) }+ return (quantized.flatMap(\.packed),+ quantized.flatMap(\.scales),+ quantized.flatMap(\.biases))+ }+ var bytes = [UInt8]()+ func append(_ values: [UInt8]) { bytes.append(contentsOf: values) }+ func append(_ values: [UInt16]) {+ for value in values {+ bytes.append(UInt8(truncatingIfNeeded: value))+ bytes.append(UInt8(truncatingIfNeeded: value >> 8))+ }+ }+ let gateValues = packed(gate)+ let upValues = packed(up)+ let downValues = packed(down)+ let gateW = UInt32(bytes.count); append(gateValues.weights)+ let gateS = UInt32(bytes.count); append(gateValues.scales)+ let gateB = UInt32(bytes.count); append(gateValues.biases)+ let upW = UInt32(bytes.count); append(upValues.weights)+ let upS = UInt32(bytes.count); append(upValues.scales)+ let upB = UInt32(bytes.count); append(upValues.biases)+ let downW = UInt32(bytes.count); append(downValues.weights)+ let downS = UInt32(bytes.count); append(downValues.scales)+ let downB = UInt32(bytes.count); append(downValues.biases)+ return RoutedBlob(+ bytes: bytes,+ offsets: MoEExpertOffsets(+ gateWOff: gateW, gateSOff: gateS, gateBOff: gateB,+ upWOff: upW, upSOff: upS, upBOff: upB,+ downWOff: downW, downSOff: downS, downBOff: downB))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/MoE/RouterTopKTests.swift b/Tests/TurboFieldfare/Core/Kernels/MoE/RouterTopKTests.swiftnew file mode 100644index 00000000..e9958a8b--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/MoE/RouterTopKTests.swift@@ -0,0 +1,161 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct RouterTopKTests {+ private static let experts = 16+ private static let dimension = 128+ private static let topK = 8++ private struct Result {+ let indices: [UInt32]+ let weights: [Float]+ }++ @Test func productionRouterMatchesReference() throws {+ var rng = SplitMix64(seed: 0xA5B6_1234)+ let weights = (0..<Self.experts).map { expert in+ (0..<Self.dimension).map { _ in+ rng.uniform(-0.05, 0.05) + Float(expert) * 0.01+ }+ }+ let hidden = (0..<Self.dimension).map { _ in rng.uniform(-1.0, 1.0) }+ let invSqrtD = 1.0 / Float(Self.dimension).squareRoot()+ let effectiveScale = (0..<Self.dimension).map { _ in+ rng.uniform(0.5, 1.5) * invSqrtD+ }+ let expertScale = (0..<Self.experts).map { _ in rng.uniform(0.6, 1.4) }++ let expected = Self.reference(weights: weights,+ hidden: hidden,+ effectiveScale: effectiveScale,+ expertScale: expertScale)+ let actual = try Self.run(weights: weights,+ hidden: hidden,+ effectiveScale: effectiveScale,+ expertScale: expertScale)+ #expect(actual.indices == expected.indices)+ let maxError = zip(actual.weights, expected.weights)+ .map { abs($0 - $1) }+ .max() ?? 0+ #expect(maxError < 5e-3)+ }++ @Test func productionRouterResolvesNearTieLikeReference() throws {+ var rng = SplitMix64(seed: 0x71E_0F4A)+ let pattern = (0..<Self.dimension).map { _ in rng.uniform(0.2, 1.0) }+ let hidden = (0..<Self.dimension).map { _ in rng.uniform(0.5, 1.5) }+ var gains = [Float](repeating: 0, count: Self.experts)+ for expert in 0..<7 { gains[expert] = 1.0 - Float(expert) * 0.05 }+ gains[7] = 0.5+ gains[8] = 0.5 * (1.0 + 1e-4)+ for expert in 9..<Self.experts {+ gains[expert] = 0.4 - Float(expert - 9) * 0.02+ }+ let weights = gains.map { gain in pattern.map { $0 * gain } }+ let effectiveScale = [Float](repeating: 1.0, count: Self.dimension)+ let expertScale = [Float](repeating: 1.0, count: Self.experts)++ let expected = Self.reference(weights: weights,+ hidden: hidden,+ effectiveScale: effectiveScale,+ expertScale: expertScale)+ let actual = try Self.run(weights: weights,+ hidden: hidden,+ effectiveScale: effectiveScale,+ expertScale: expertScale)+ #expect(actual.indices == expected.indices)+ }++ private static func reference(weights: [[Float]],+ hidden: [Float],+ effectiveScale: [Float],+ expertScale: [Float]) -> Result {+ let scaled = zip(hidden, effectiveScale).map { $0 * $1 }+ let rows = weights.map { Quantization.quantizeInt8Affine($0) }+ let logits = DequantInt8GemvRef.apply(weightRows: rows,+ x: scaled,+ n: Self.dimension)+ var paired: [(Float, UInt32)] = []+ paired.reserveCapacity(Self.experts)+ for expert in 0..<Self.experts {+ paired.append((logits[expert], UInt32(expert)))+ }+ paired.sort { lhs, rhs in+ lhs.0 == rhs.0 ? lhs.1 < rhs.1 : lhs.0 > rhs.0+ }+ let selected = Array(paired.prefix(Self.topK))+ let maximum = selected.first?.0 ?? 0+ let exponents = selected.map { exp($0.0 - maximum) }+ let sum = exponents.reduce(0, +)+ let outputWeights = zip(selected, exponents).map { item, value in+ value / sum * expertScale[Int(item.1)]+ }+ return Result(indices: selected.map { $0.1 }, weights: outputWeights)+ }++ private static func run(weights: [[Float]],+ hidden: [Float],+ effectiveScale: [Float],+ expertScale: [Float]) throws -> Result {+ let packedRows = weights.map { Quantization.quantizeInt8Affine($0) }+ let groupsPerRow = Self.dimension / Quantization.groupSize+ let packed = packedRows.flatMap(\.packed)+ let scales = packedRows.flatMap(\.scales)+ let biases = packedRows.flatMap(\.biases)+ precondition(scales.count == Self.experts * groupsPerRow)++ let context = try MetalContext()+ let kernel = try MoE(context: context)+ guard let weightBuffer = context.device.makeBuffer(+ bytes: packed, length: packed.count, options: .storageModeShared),+ let scaleBuffer = context.device.makeBuffer(+ bytes: scales,+ length: scales.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared),+ let biasBuffer = context.device.makeBuffer(+ bytes: biases,+ length: biases.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared),+ let hiddenBuffer = Fp16Buffer.make(context.device, values: hidden),+ let effectiveBuffer = context.device.makeBuffer(+ bytes: effectiveScale.map(Quantization.bf16Bits),+ length: effectiveScale.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared),+ let expertScaleBuffer = context.device.makeBuffer(+ bytes: expertScale.map(Quantization.bf16Bits),+ length: expertScale.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared),+ let indexBuffer = context.device.makeBuffer(+ length: Self.topK * MemoryLayout<UInt32>.stride,+ options: .storageModeShared),+ let outputWeightBuffer = Fp16Buffer.make(context.device, count: Self.topK),+ let commandBuffer = context.queue.makeCommandBuffer() else {+ throw CocoaError(.fileReadUnknown)+ }+ kernel.encodeRouterGemma4(+ commandBuffer: commandBuffer,+ weights: weightBuffer,+ scales: scaleBuffer,+ biases: biasBuffer,+ hidden: hiddenBuffer,+ effectiveScale: effectiveBuffer,+ perExpertScale: expertScaleBuffer,+ outIndices: indexBuffer,+ outWeights: outputWeightBuffer,+ numExperts: UInt32(Self.experts),+ d: UInt32(Self.dimension),+ topK: UInt32(Self.topK))+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ #expect(commandBuffer.error == nil)++ let indexPointer = indexBuffer.contents().bindMemory(+ to: UInt32.self, capacity: Self.topK)+ return Result(+ indices: (0..<Self.topK).map { indexPointer[$0] },+ weights: Fp16Buffer.read(outputWeightBuffer, count: Self.topK))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/MoE/SharedExpertInt8Tests.swift b/Tests/TurboFieldfare/Core/Kernels/MoE/SharedExpertInt8Tests.swiftnew file mode 100644index 00000000..eefbe9c4--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/MoE/SharedExpertInt8Tests.swift@@ -0,0 +1,113 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Validates the standalone 8-bit dense MLP wrapper used by Gemma 4 as the+/// "shared expert" parallel branch of its MoE:+///+/// y = down(gelu_pytorch_tanh(gate(x)) * up(x))+///+/// Reference composes DequantInt8GemvRef + gelu_pytorch_tanh + vDSP_vmul,+/// matching the math but with a different staging (bulk dequant rows, then+/// dotpr) so a bug in either side won't replicate.+@Suite struct SharedExpertInt8Tests {++ private struct Sizes {+ static let D = 128+ static let F = 64+ }++ private static func packMatrix(_ rows: [[Float]])+ -> (rows: [Quantization.Int8AffineRow],+ packed: [UInt8], scales: [UInt16], biases: [UInt16]) {+ let M = rows.count+ let N = rows[0].count+ let gpr = N / Quantization.groupSize+ var packed = [UInt8]( repeating: 0, count: M * N)+ var scales = [UInt16](repeating: 0, count: M * gpr)+ var biases = [UInt16](repeating: 0, count: M * gpr)+ var rowsOut: [Quantization.Int8AffineRow] = []+ rowsOut.reserveCapacity(M)+ for m in 0..<M {+ let q = Quantization.quantizeInt8Affine(rows[m])+ for i in 0..<N { packed[m * N + i] = q.packed[i] }+ for g in 0..<gpr {+ scales[m * gpr + g] = q.scales[g]+ biases[m * gpr + g] = q.biases[g]+ }+ rowsOut.append(q)+ }+ return (rowsOut, packed, scales, biases)+ }++ @Test func sharedExpertInt8_matchesReference_swaShape() throws {+ try Self.runSharedExpertInt8MatchesReference()+ }++ private static func runSharedExpertInt8MatchesReference() throws {+ var rng = SeedTree(0x601).key("shared-expert-int8")+ let xFp32 = (0..<Sizes.D).map { _ in rng.uniform(-0.4, 0.4) }+ let gate = (0..<Sizes.F).map { _ in (0..<Sizes.D).map { _ in rng.uniform(-0.4, 0.4) } }+ let up = (0..<Sizes.F).map { _ in (0..<Sizes.D).map { _ in rng.uniform(-0.4, 0.4) } }+ let down = (0..<Sizes.D).map { _ in (0..<Sizes.F).map { _ in rng.uniform(-0.4, 0.4) } }++ // Reference: dense MLP applied to x.+ let xFp16 = xFp32.map { Float(Float16($0)) }+ let gatePack = Self.packMatrix(gate)+ let upPack = Self.packMatrix(up)+ let downPack = Self.packMatrix(down)+ let gateOut = DequantInt8GemvRef.apply(weightRows: gatePack.rows, x: xFp16, n: Sizes.D)+ let upOut = DequantInt8GemvRef.apply(weightRows: upPack.rows, x: xFp16, n: Sizes.D)+ // gelu_pytorch_tanh + multiply (round through FP16 once to match the kernel's storage).+ let act: [Float] = zip(gateOut, upOut).map { g, u in+ let x3 = g * g * g+ let inner = 0.7978845608028654 * Double(g + 0.044715 * x3)+ let gelu = 0.5 * Double(g) * (1.0 + tanh(inner))+ return Float(Float16(Float(gelu) * u))+ }+ let yRef = DequantInt8GemvRef.apply(weightRows: downPack.rows, x: act, n: Sizes.F)++ // Kernel+ let ctx = try MetalContext()+ let wrapper = try SharedExpertInt8(context: ctx)++ guard let xBuf = Fp16Buffer.make(ctx.device, values: xFp32),+ let yBuf = Fp16Buffer.make(ctx.device, count: Sizes.D),+ let sa = Fp16Buffer.make(ctx.device, count: Sizes.F) else {+ Issue.record("alloc failed"); return+ }++ func pack(_ p: (rows: [Quantization.Int8AffineRow],+ packed: [UInt8], scales: [UInt16], biases: [UInt16]),+ rows: UInt32, cols: UInt32) -> SharedExpertInt8Proj {+ let wBuf = ctx.device.makeBuffer(bytes: p.packed,+ length: p.packed.count,+ options: .storageModeShared)!+ let sBuf = ctx.device.makeBuffer(bytes: p.scales,+ length: p.scales.count * 2,+ options: .storageModeShared)!+ let bBuf = ctx.device.makeBuffer(bytes: p.biases,+ length: p.biases.count * 2,+ options: .storageModeShared)!+ return SharedExpertInt8Proj(weights: wBuf, scales: sBuf, biases: bBuf,+ rows: rows, cols: cols)+ }+ let gateProj = pack(gatePack, rows: UInt32(Sizes.F), cols: UInt32(Sizes.D))+ let upProj = pack(upPack, rows: UInt32(Sizes.F), cols: UInt32(Sizes.D))+ let downProj = pack(downPack, rows: UInt32(Sizes.D), cols: UInt32(Sizes.F))++ let cb = ctx.queue.makeCommandBuffer()!+ try wrapper.encode(commandBuffer: cb,+ x: xBuf, gate: gateProj, up: upProj, down: downProj,+ y: yBuf,+ scratchAct: sa)+ cb.commit(); cb.waitUntilCompleted()++ let actual = Fp16Buffer.read(yBuf, count: Sizes.D)+ let rel = RelError.compute(actual: actual, reference: yRef)+ #expect(rel < Tolerance.quantInt8 * 4, "shared-expert int8 rel=\(rel)")+ }++}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillAffineTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillAffineTests.swiftnew file mode 100644index 00000000..42e165a6--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillAffineTests.swift@@ -0,0 +1,240 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillAffineTests {+ private static func packWeights(_ rows: [Quantization.Int4AffineRow])+ -> (packed: [UInt8], scales: [UInt16], biases: [UInt16])+ {+ let nRows = rows.count+ let rowBytes = rows[0].packed.count+ let groups = rows[0].scales.count+ var packed = [UInt8](repeating: 0, count: nRows * rowBytes)+ var scales = [UInt16](repeating: 0, count: nRows * groups)+ var biases = [UInt16](repeating: 0, count: nRows * groups)++ for row in 0..<nRows {+ for i in 0..<rowBytes {+ packed[row * rowBytes + i] = rows[row].packed[i]+ }+ for g in 0..<groups {+ scales[row * groups + g] = rows[row].scales[g]+ biases[row * groups + g] = rows[row].biases[g]+ }+ }+ return (packed, scales, biases)+ }++ private static func runQMMMatchesRepeatedGEMV(t: Int, n: Int, k: Int, seed: UInt64) throws {+ precondition(k % Quantization.groupSize == 0)+ var rng = SeedTree(seed).key("prefill-qmm-t\(t)-n\(n)-k\(k)")++ var rows: [Quantization.Int4AffineRow] = []+ rows.reserveCapacity(n)+ for _ in 0..<n {+ let raw = (0..<k).map { _ in rng.uniform(-0.5, 0.5) }+ rows.append(Quantization.quantizeInt4Affine(raw))+ }+ let (packed, scales, biases) = packWeights(rows)+ let x = (0..<(t * k)).map { _ in Float16(rng.uniform(-1.0, 1.0)) }++ let ctx = try MetalContext()+ let gemv = try DequantInt4GEMV(context: ctx)+ let qmm = try PrefillInt4QMM(context: ctx)++ guard let wBuf = ctx.device.makeBuffer(bytes: packed, length: packed.count, options: .storageModeShared),+ let sBuf = ctx.device.makeBuffer(bytes: scales,+ length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let bBuf = ctx.device.makeBuffer(bytes: biases,+ length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let gemvOut = Fp16Buffer.make(ctx.device, count: t * n),+ let qmmOut = Fp16Buffer.make(ctx.device, count: t * n) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<t {+ gemv.encode(commandBuffer: cb,+ weights: wBuf,+ scales: sBuf,+ biases: bBuf,+ x: xBuf,+ xOffset: row * k * MemoryLayout<Float16>.size,+ y: gemvOut,+ yOffset: row * n * MemoryLayout<Float16>.size,+ m: UInt32(n),+ n: UInt32(k))+ }+ qmm.encode(commandBuffer: cb,+ weights: wBuf,+ scales: sBuf,+ biases: bBuf,+ x: xBuf,+ y: qmmOut,+ t: t,+ n: n,+ k: k)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(gemvOut, count: t * n)+ let actual = Fp16Buffer.read(qmmOut, count: t * n)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ let rel = RelError.compute(actual: actual, reference: reference)+ #expect(maxAbs <= 1e-3, "shape T=\(t) N=\(n) K=\(k) maxAbs=\(maxAbs) rel=\(rel)")+ #expect(rel <= 1e-4, "shape T=\(t) N=\(n) K=\(k) rel=\(rel) maxAbs=\(maxAbs)")+ }++ private static func runPatternQMMMatchesRepeatedGEMV(t: Int,+ n: Int,+ k: Int,+ seed: UInt64,+ maxAbsTolerance: Float = 2e-2,+ relTolerance: Float = 2e-4) throws {+ precondition(k % Quantization.groupSize == 0)+ let groups = k / Quantization.groupSize+ var rng = SeedTree(seed).key("prefill-qmm-pattern-t\(t)-n\(n)-k\(k)")++ var packed = [UInt8](repeating: 0, count: n * k / 2)+ for i in packed.indices {+ packed[i] = UInt8((i &* 31 &+ Int(seed & 0xff)) & 0xff)+ }++ var scales = [UInt16](repeating: 0, count: n * groups)+ var biases = [UInt16](repeating: 0, count: n * groups)+ for row in 0..<n {+ for group in 0..<groups {+ let idx = row * groups + group+ let scale = 0.001 + Float((row + group) % 7) * 0.00025+ let bias = -0.012 + Float((row * 3 + group) % 11) * 0.002+ scales[idx] = Quantization.bf16Bits(scale)+ biases[idx] = Quantization.bf16Bits(bias)+ }+ }++ let x = (0..<(t * k)).map { _ in Float16(rng.uniform(-0.25, 0.25)) }++ let ctx = try MetalContext()+ let gemv = try DequantInt4GEMV(context: ctx)+ let qmm = try PrefillInt4QMM(context: ctx)++ guard let wBuf = ctx.device.makeBuffer(bytes: packed, length: packed.count, options: .storageModeShared),+ let sBuf = ctx.device.makeBuffer(bytes: scales,+ length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let bBuf = ctx.device.makeBuffer(bytes: biases,+ length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let gemvOut = Fp16Buffer.make(ctx.device, count: t * n),+ let qmmOut = Fp16Buffer.make(ctx.device, count: t * n) else {+ Issue.record("alloc failed for shape T=\(t) N=\(n) K=\(k)")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<t {+ gemv.encode(commandBuffer: cb,+ weights: wBuf,+ scales: sBuf,+ biases: bBuf,+ x: xBuf,+ xOffset: row * k * MemoryLayout<Float16>.size,+ y: gemvOut,+ yOffset: row * n * MemoryLayout<Float16>.size,+ m: UInt32(n),+ n: UInt32(k))+ }+ qmm.encode(commandBuffer: cb,+ weights: wBuf,+ scales: sBuf,+ biases: bBuf,+ x: xBuf,+ y: qmmOut,+ t: t,+ n: n,+ k: k)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(gemvOut, count: t * n)+ let actual = Fp16Buffer.read(qmmOut, count: t * n)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ let rel = RelError.compute(actual: actual, reference: reference)+ #expect(maxAbs <= maxAbsTolerance,+ "shape T=\(t) N=\(n) K=\(k) maxAbs=\(maxAbs) rel=\(rel)")+ #expect(rel <= relTolerance,+ "shape T=\(t) N=\(n) K=\(k) rel=\(rel) maxAbs=\(maxAbs)")+ }++ @Test func int4QMMMatchesRepeatedGEMV() throws {+ let shapes = [+ (t: 1, n: 64, k: 64),+ (t: 2, n: 129, k: 128),+ (t: 3, n: 65, k: 192),+ (t: 7, n: 256, k: 128),+ (t: 32, n: 64, k: 64),+ ]++ for (index, shape) in shapes.enumerated() {+ try Self.runQMMMatchesRepeatedGEMV(t: shape.t,+ n: shape.n,+ k: shape.k,+ seed: 0x6100 + UInt64(index))+ }+ }++ @Test func int4QMMProductionShapesMatchRepeatedGEMV() throws {+ let shapes = [+ (t: 1, n: 4096, k: 2816), // SWA q projection+ (t: 2, n: 2048, k: 2816), // SWA k/v projection+ (t: 2, n: 8192, k: 2816), // full q projection+ (t: 2, n: 2816, k: 8192), // full o/down projection family+ ]++ for (index, shape) in shapes.enumerated() {+ try Self.runPatternQMMMatchesRepeatedGEMV(t: shape.t,+ n: shape.n,+ k: shape.k,+ seed: 0x7100 + UInt64(index))+ }+ }++ @Test func int4QMMSelectedChunkShapesMatchRepeatedGEMV() throws {+ let shapes = [+ (n: 4096, k: 2816), // SWA q projection+ (n: 2048, k: 2816), // SWA k/v projection+ (n: 2816, k: 4096), // SWA o projection+ (n: 8192, k: 2816), // full q projection+ (n: 1024, k: 2816), // full k/v projection+ (n: 2816, k: 8192), // full o projection+ (n: 2112, k: 2816), // shared gate/up projection+ (n: 2816, k: 2112), // shared down projection+ (n: 704, k: 2816), // routed gate/up projection+ (n: 2816, k: 704), // routed down projection+ ]++ for (index, shape) in shapes.enumerated() {+ try Self.runPatternQMMMatchesRepeatedGEMV(t: 32,+ n: shape.n,+ k: shape.k,+ seed: 0x8100 + UInt64(index),+ maxAbsTolerance: 2e-4,+ relTolerance: 5e-4)+ }+ }++ @Test func int4QMMRejectsNonGroupAlignedK_contract() {+ // PrefillInt4QMM.encode uses the same precondition contract as+ // DequantInt4GEMV: K must be a multiple of Quantization.groupSize.+ // Swift Testing cannot catch precondition traps in-process, so this+ // documents the rejection contract without deliberately crashing.+ #expect(Quantization.groupSize == 64)+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillFinalRowHeadTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillFinalRowHeadTests.swiftnew file mode 100644index 00000000..b1a88fbd--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillFinalRowHeadTests.swift@@ -0,0 +1,114 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillFinalRowHeadTests {+ private static func packRows(_ rows: [Quantization.Int4AffineRow])+ -> (packed: [UInt8], scales: [UInt16], biases: [UInt16])+ {+ let rowBytes = rows[0].packed.count+ let groups = rows[0].scales.count+ var packed = [UInt8](repeating: 0, count: rows.count * rowBytes)+ var scales = [UInt16](repeating: 0, count: rows.count * groups)+ var biases = [UInt16](repeating: 0, count: rows.count * groups)++ for row in 0..<rows.count {+ for i in 0..<rowBytes {+ packed[row * rowBytes + i] = rows[row].packed[i]+ }+ for g in 0..<groups {+ scales[row * groups + g] = rows[row].scales[g]+ biases[row * groups + g] = rows[row].biases[g]+ }+ }+ return (packed, scales, biases)+ }++ @Test func finalRowHeadLogitsMatchesScalarOffsetPath() throws {+ let rows = 5+ let selectedRow = 3+ let d = 128+ let rowStride = d + 17+ let vocab = 96+ let eps: Float = 1e-6+ var rng = SeedTree(0xB501).key("prefill-final-row-head")++ var hidden = [Float16](repeating: 0, count: rows * rowStride)+ for row in 0..<rows {+ for i in 0..<d {+ hidden[row * rowStride + i] = Float16(rng.uniform(-1.0, 1.0))+ }+ }+ let normBits = (0..<d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let weightRows = (0..<vocab).map { _ -> Quantization.Int4AffineRow in+ let raw = (0..<d).map { _ in rng.uniform(-0.5, 0.5) }+ return Quantization.quantizeInt4Affine(raw)+ }+ let (packed, scales, biases) = Self.packRows(weightRows)++ let ctx = try MetalContext()+ let scalarNorm = try RMSNorm(context: ctx)+ let scalarHead = try DequantInt4GEMV(context: ctx)+ let finalRowHead = try PrefillFinalRowHeadInt4(context: ctx, maxD: d)++ guard let hiddenBuf = Fp16Buffer.make(ctx.device, halves: hidden),+ let normBuf = ctx.device.makeBuffer(bytes: normBits,+ length: normBits.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let wBuf = ctx.device.makeBuffer(bytes: packed,+ length: packed.count,+ options: .storageModeShared),+ let sBuf = ctx.device.makeBuffer(bytes: scales,+ length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let bBuf = ctx.device.makeBuffer(bytes: biases,+ length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let scalarNormed = Fp16Buffer.make(ctx.device, count: d),+ let scalarLogits = Fp16Buffer.make(ctx.device, count: vocab),+ let blockLogits = Fp16Buffer.make(ctx.device, count: vocab) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ scalarNorm.encodeBF16W(commandBuffer: cb,+ x: hiddenBuf,+ xOffset: selectedRow * rowStride * MemoryLayout<Float16>.size,+ weight: normBuf,+ out: scalarNormed,+ d: UInt32(d),+ eps: eps)+ scalarHead.encode(commandBuffer: cb,+ weights: wBuf,+ scales: sBuf,+ biases: bBuf,+ x: scalarNormed,+ y: scalarLogits,+ m: UInt32(vocab),+ n: UInt32(d))+ finalRowHead.encodeLogits(commandBuffer: cb,+ hiddenBlock: hiddenBuf,+ row: selectedRow,+ rowStrideElements: rowStride,+ normWeight: normBuf,+ weights: wBuf,+ scales: sBuf,+ biases: bBuf,+ logits: blockLogits,+ d: UInt32(d),+ vocab: UInt32(vocab),+ rmsEps: eps)+ cb.commit()+ cb.waitUntilCompleted()++ let scalar = Fp16Buffer.read(scalarLogits, count: vocab)+ let block = Fp16Buffer.read(blockLogits, count: vocab)+ let maxAbs = RelError.maxAbsDiff(block, scalar)+ let rel = RelError.compute(actual: block, reference: scalar)+ #expect(maxAbs <= 1e-3, "maxAbs=\(maxAbs) rel=\(rel)")+ #expect(rel <= 1e-4, "rel=\(rel) maxAbs=\(maxAbs)")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Binding.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Binding.swiftnew file mode 100644index 00000000..7d06123e--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Binding.swift@@ -0,0 +1,232 @@+import Metal+import Testing++@testable import TurboFieldfare++extension PrefillGroupedRoutedMoETests {+ @Test func streamedTileBindingMapsGlobalExpertsToLocalSlots() throws {+ let ctx = try MetalContext()+ let expertIDs = [3, 9, 17]+ let views = try Self.fakeTensorViews(device: ctx.device, count: expertIDs.count)+ let binding = try PrefillStreamedTileBinding(expertIDs: expertIDs, views: views)++ #expect(binding.localSlot(for: 3) == 0)+ #expect(binding.localSlot(for: 9) == 1)+ #expect(binding.localSlot(for: 3) == 0)+ #expect(binding.localSlot(for: 17) == 2)+ #expect(binding.localSlot(for: 5) == nil)++ let pairs = [+ Self.pair(token: 0, expert: 3, rank: 0),+ Self.pair(token: 0, expert: 9, rank: 1),+ Self.pair(token: 1, expert: 3, rank: 0),+ Self.pair(token: 1, expert: 17, rank: 1),+ ]+ try binding.validateCoversPairs(pairs, pairStart: 0, pairCount: pairs.count)+ }++ @Test func streamedTileBindingRejectsUnboundRouteExpert() throws {+ let ctx = try MetalContext()+ let binding = try PrefillStreamedTileBinding(+ expertIDs: [3, 9],+ views: Self.fakeTensorViews(device: ctx.device, count: 2))+ let pairs = [+ Self.pair(token: 0, expert: 3, rank: 0),+ Self.pair(token: 0, expert: 17, rank: 1),+ ]++ #expect {+ try binding.validateCoversPairs(pairs, pairStart: 0, pairCount: pairs.count)+ } throws: { error in+ guard case PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(let reason) = error else {+ return false+ }+ return reason.contains("17")+ }++ #expect {+ _ = try PrefillStreamedTileBinding(+ expertIDs: [3, 3],+ views: Self.fakeTensorViews(device: ctx.device, count: 2))+ } throws: { error in+ guard case PrefillGroupedRoutedMoEError.invalidStreamedTileBinding(let reason) = error else {+ return false+ }+ return reason.contains("duplicate")+ }+ }++ @Test func streamedTilePlanningNeverExceedsDefaultSlotCount() throws {+ let pairs = (0..<24).map { index in+ Self.pair(+ token: UInt32(index / 8),+ expert: UInt32(min(index, 19)),+ rank: UInt32(index % 8))+ }+ let routes = try PrefillMoEGrouping.groupTokenExpertPairs(+ pairs,+ queryCount: 3,+ topK: 8,+ numExperts: 128,+ tileExpertCount: 16)++ let firstTile = try PrefillStreamedTileBinding.expertIDs(forTile: 0, routes: routes)+ let secondTile = try PrefillStreamedTileBinding.expertIDs(forTile: 1, routes: routes)++ #expect(firstTile == Array(0..<16))+ #expect(secondTile == Array(16..<20))+ #expect(firstTile.count <= 16)+ #expect(secondTile.count <= 16)+ #expect(firstTile != Array(0..<20))+ #expect(secondTile != Array(0..<20))+ }++ @Test func streamedTileSlotLifetimeRejectsPlannedCacheSlotReuseBeforeCompletion() throws {+ let firstPlan = ExpertCachePlan(+ experts: [0, 1, 2, 3],+ assignedSlots: [0, 1, 2, 3],+ misses: [0, 1, 2, 3],+ hits: 0)+ let secondPlan = ExpertCachePlan(+ experts: [4, 5, 6, 7],+ assignedSlots: [0, 1, 2, 3],+ misses: [0, 1, 2, 3],+ hits: 0)+ var lifetime = PrefillStreamedTileSlotLifetime()++ try lifetime.begin(tileIndex: 0, plannedSlots: firstPlan.assignedSlots)+ #expect {+ try lifetime.begin(tileIndex: 1, plannedSlots: secondPlan.assignedSlots)+ } throws: { error in+ guard+ case PrefillStreamedTileLifetimeError.slotReuseBeforeCompletion(+ tileIndex: 1,+ conflictingTileIndex: 0,+ slots: [0, 1, 2, 3]) = error+ else {+ return false+ }+ return true+ }++ try lifetime.complete(tileIndex: 0)+ try lifetime.begin(tileIndex: 1, plannedSlots: secondPlan.assignedSlots)+ try lifetime.complete(tileIndex: 1)+ }++ @Test func streamedTileSlotLifetimeAllowsPinnedNonOverlappingSlots() throws {+ var lifetime = PrefillStreamedTileSlotLifetime()++ try lifetime.begin(tileIndex: 0, plannedSlots: [0, 1])+ try lifetime.begin(tileIndex: 1, plannedSlots: [2, 3])++ try lifetime.complete(tileIndex: 0)+ try lifetime.complete(tileIndex: 1)++ #expect {+ try lifetime.begin(tileIndex: 2, plannedSlots: [4, 4])+ } throws: { error in+ guard+ case PrefillStreamedTileLifetimeError.duplicateSlots(+ tileIndex: 2,+ slots: [4, 4]) = error+ else {+ return false+ }+ return true+ }+ }++ @Test func streamedTileSlotLifetimeAllowsSequentialReuseAfterCompletion() throws {+ var lifetime = PrefillStreamedTileSlotLifetime()+ let reusedSlots = [0, 1, 2, 3, 4, 5, 6, 7]++ for tile in 0..<4 {+ try lifetime.begin(tileIndex: tile, plannedSlots: reusedSlots)+ try lifetime.complete(tileIndex: tile)+ }+ }++ @Test func streamedTileFetchBindingUsesPreadPlanAndCacheHits() async throws {+ let dir = try ModelLoaderTests.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ streamingMode: .pread(slotCount: 16))+ let routes = try Self.tileFetchRoutes()++ let first = try await PrefillStreamedTileBinding.fetchBindingForTile(+ model: model,+ layer: 1,+ tileIndex: 0,+ routes: routes)+ let second = try await PrefillStreamedTileBinding.fetchBindingForTile(+ model: model,+ layer: 1,+ tileIndex: 0,+ routes: routes)++ #expect(first.expertIDs == [1, 3, 5])+ #expect(first.usedPlannedFetch)+ #expect(first.plannedHits == 0)+ #expect(first.plannedMissIndices == [0, 1, 2])+ #expect(first.plannedMissSlots == [0, 1, 2])+ #expect(second.usedPlannedFetch)+ #expect(second.plannedHits == 3)+ #expect(second.plannedMissIndices.isEmpty)+ #expect(second.plannedMissSlots.isEmpty)+ for result in [first, second] {+ #expect(result.binding.views.allSatisfy { $0.offset == 0 })+ try result.binding.validateCoversPairs(+ routes.sortedPairs,+ pairStart: 0,+ pairCount: routes.sortedPairs.count)+ for (index, expert) in result.expertIDs.enumerated() {+ let view = result.binding.views[index]+ #expect(Self.byte(view, at: 0) == 1)+ #expect(Self.byte(view, at: 1) == UInt8(expert))+ }+ }+ }++ @Test func streamedTileFetchBindingAvoidsInFlightPlannedSlots() async throws {+ let dir = try ModelLoaderTests.writeToySynthetic()+ defer { try? FileManager.default.removeItem(at: dir) }+ let device = try #require(MTLCreateSystemDefaultDevice())+ let model = try Model.load(+ directoryURL: dir,+ device: device,+ expecting: .gemma4Toy(),+ streamingMode: .pread(slotCount: 16))+ let routes = try Self.tileFetchRoutes()++ let first = try await PrefillStreamedTileBinding.fetchBindingForTile(+ model: model,+ layer: 1,+ tileIndex: 0,+ routes: routes)+ let second = try await PrefillStreamedTileBinding.fetchBindingForTile(+ model: model,+ layer: 1,+ tileIndex: 0,+ routes: routes,+ avoidingSlots: Set(first.plannedAssignedSlots))++ #expect(first.usedPlannedFetch)+ #expect(first.plannedAssignedSlots == [0, 1, 2])+ #expect(first.plannedMissSlots == [0, 1, 2])+ #expect(second.usedPlannedFetch)+ #expect(second.plannedAssignedSlots == [0, 1, 2])+ #expect(second.plannedHits == 3)+ #expect(second.plannedMissIndices.isEmpty)+ #expect(second.plannedMissSlots.isEmpty)+ try second.binding.validateCoversPairs(+ routes.sortedPairs,+ pairStart: 0,+ pairCount: routes.sortedPairs.count)+ }++}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Execution.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Execution.swiftnew file mode 100644index 00000000..3e85b781--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Execution.swift@@ -0,0 +1,105 @@+import Metal+import Testing+import TurboFieldfareValidationSupport++@testable import TurboFieldfare++extension PrefillGroupedRoutedMoETests {+ @Test func streamedBatchedMatchesReferenceAcrossPartialMicrobatch() throws {+ let d = 64+ let f = 64+ let rows = 3+ let topK = 2+ let routes = try PrefillMoEGrouping.groupTokenExpertPairs(+ [+ Self.pair(token: 0, expert: 2, rank: 0),+ Self.pair(token: 0, expert: 0, rank: 1),+ Self.pair(token: 1, expert: 1, rank: 0),+ Self.pair(token: 1, expert: 2, rank: 1),+ Self.pair(token: 2, expert: 0, rank: 0),+ Self.pair(token: 2, expert: 1, rank: 1),+ ],+ queryCount: rows,+ topK: topK,+ numExperts: 16,+ tileExpertCount: 16)+ let pool = Self.makeSyntheticExpertPool(numExperts: 16, d: d, f: f)+ let hidden = (0..<(rows * d)).map { i in+ Float16(Float((i % 17) - 8) * 0.01)+ }+ let expected = Self.cpuSyntheticRoutePartials(+ routes: routes,+ hidden: hidden,+ hiddenStride: d,+ pool: pool,+ topK: topK,+ d: d,+ f: f)++ let ctx = try MetalContext()+ let grouped = try PrefillGroupedRoutedMoE(context: ctx)+ guard let hiddenBuffer = Fp16Buffer.make(ctx.device, halves: hidden),+ let pairBuffer = ctx.device.makeBuffer(+ bytes: routes.sortedPairs,+ length: routes.sortedPairs.count * MemoryLayout<PrefillTokenExpertPair>.stride,+ options: .storageModeShared),+ let outputBuffer = Fp16Buffer.make(+ ctx.device,+ halves: [Float16](repeating: -77, count: rows * topK * d)),+ let activationScratch = ctx.device.makeBuffer(+ length: 3 * 4 * f * MemoryLayout<Float16>.stride,+ options: .storageModePrivate),+ let downScratch = ctx.device.makeBuffer(+ length: 4 * d * MemoryLayout<Float16>.stride,+ options: .storageModePrivate),+ let commandBuffer = ctx.queue.makeCommandBuffer()+ else {+ Issue.record("allocation failed")+ return+ }++ let expertIDs = Array(0..<16)+ let binding = try PrefillStreamedTileBinding(+ expertIDs: expertIDs,+ views: Self.streamedViewsWithNonzeroOffsets(+ device: ctx.device,+ pool: pool,+ expertIDs: expertIDs))+ let params = PrefillGroupedRoutedMoEStreamedParams(+ pairStart: 0,+ pairCount: UInt32(routes.sortedPairs.count),+ d: UInt32(d),+ routedIntermediate: UInt32(f),+ topK: UInt32(topK),+ hiddenStrideElements: UInt32(d),+ binding: binding,+ offsets: pool.offsets)+ let argumentBuffer = try grouped.makeStreamedArgumentBuffer(+ device: ctx.device,+ binding: binding)+ let microbatches = grouped.encodeStreamedBatched(+ commandBuffer: commandBuffer,+ hidden: hiddenBuffer,+ sortedPairs: pairBuffer,+ routePartials: outputBuffer,+ gateUpActScratch: activationScratch,+ downScratch: downScratch,+ argumentBuffer: argumentBuffer,+ binding: binding,+ params: params,+ pairMicrobatchRows: 4)++ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ if let error = commandBuffer.error { throw error }++ let actual = Fp16Buffer.readHalf(outputBuffer, count: rows * topK * d)+ let maxAbsoluteError = zip(actual, expected).reduce(Float(0)) {+ max($0, abs(Float($1.0) - Float($1.1)))+ }+ #expect(microbatches == 2)+ #expect(maxAbsoluteError <= 0.0015, "maxAbsoluteError=\(maxAbsoluteError)")+ #expect(binding.views.allSatisfy { $0.offset > 0 })+ }++}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Layout.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Layout.swiftnew file mode 100644index 00000000..3b669eda--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests+Layout.swift@@ -0,0 +1,49 @@+import Metal+import Testing++@testable import TurboFieldfare++extension PrefillGroupedRoutedMoETests {+ @Test func streamedParamsLayoutIsStable() {+ #expect(MemoryLayout<PrefillGroupedRoutedMoEStreamedParams>.size == 128)+ #expect(MemoryLayout<PrefillGroupedRoutedMoEStreamedParams>.stride == 128)+ #expect(MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.pairStart) == .some(0))+ #expect(MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.pairCount) == .some(4))+ #expect(MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.d) == .some(8))+ #expect(+ MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.routedIntermediate)+ == .some(12))+ #expect(MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.topK) == .some(16))+ #expect(+ MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.hiddenStrideElements)+ == .some(20))+ #expect(+ MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.liveExpertCount) == .some(24))+ #expect(+ MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.localExpert0) == .some(28))+ #expect(+ MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.localExpert15) == .some(88))+ #expect(MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.gateWOff) == .some(92))+ #expect(MemoryLayout.offset(of: \PrefillGroupedRoutedMoEStreamedParams.downBOff) == .some(124))+ }++ @Test func streamedMetadataAllocatesOnlySortedPairs() throws {+ let routes = try Self.measuredPressureRoutes()+ let ctx = try MetalContext()+ let grouped = try PrefillGroupedRoutedMoE(context: ctx)+ let buffers = try grouped.makeStreamedMetadataBuffers(device: ctx.device, routes: routes)+ let pairBytes = routes.sortedPairs.count * MemoryLayout<PrefillTokenExpertPair>.stride+ let omittedBytes =+ routes.groups.count * MemoryLayout<PrefillMoEGroup>.stride+ + routes.tiles.count * MemoryLayout<PrefillMoETile>.stride++ #expect(buffers.sortedPairs.storageMode == .shared)+ #expect(buffers.sortedPairs.length == pairBytes)+ #expect(omittedBytes > 0)++ let pairPtr = buffers.sortedPairs.contents()+ .bindMemory(to: PrefillTokenExpertPair.self, capacity: routes.sortedPairs.count)+ #expect(pairPtr[0] == routes.sortedPairs[0])+ #expect(pairPtr[routes.sortedPairs.count - 1] == routes.sortedPairs.last)+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests.swiftnew file mode 100644index 00000000..6252426f--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillGroupedRoutedMoETests.swift@@ -0,0 +1,304 @@+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillGroupedRoutedMoETests {+ static func measuredPressureRoutes() throws -> PrefillMoEGroupedRoutes {+ var expertAssignments: [UInt32] = []+ expertAssignments.reserveCapacity(256)+ for expert in 0..<16 {+ let count = expert < 5 ? 15 : 14+ expertAssignments.append(contentsOf: repeatElement(UInt32(expert), count: count))+ }+ expertAssignments.append(contentsOf: repeatElement(UInt32(16), count: 27))+ #expect(expertAssignments.count == 256)++ var pairs: [PrefillTokenExpertPair] = []+ pairs.reserveCapacity(256)+ for i in 0..<256 {+ pairs.append(Self.pair(token: UInt32(i / 8),+ expert: expertAssignments[i],+ rank: UInt32(i % 8)))+ }+ return try PrefillMoEGrouping.groupTokenExpertPairs(+ pairs,+ queryCount: 32,+ topK: 8,+ numExperts: 128,+ tileExpertCount: 16)+ }++ static func pair(token: UInt32, expert: UInt32, rank: UInt32) -> PrefillTokenExpertPair {+ PrefillTokenExpertPair(token: token,+ expert: expert,+ rank: rank,+ weight: Float16(0.125 + Float(rank) * 0.0625))+ }++ static func fakeTensorViews(device: MTLDevice, count: Int) throws -> [TensorView] {+ guard let buffer = device.makeBuffer(length: max(count, 1) * 64,+ options: .storageModeShared) else {+ throw PrefillGroupedRoutedMoEError.allocationFailed("fake tensor view buffer")+ }+ return (0..<count).map { index in+ TensorView(buffer: buffer,+ offset: UInt64(index * 64),+ length: 64,+ scaleOffset: 0,+ scaleLength: 0,+ biasOffset: 0,+ biasLength: 0,+ shape: (0, UInt32(index), 0, 0),+ dtype: 0)+ }+ }++ static func tileFetchRoutes() throws -> PrefillMoEGroupedRoutes {+ let pairs = [+ Self.pair(token: 0, expert: 3, rank: 0),+ Self.pair(token: 0, expert: 1, rank: 1),+ Self.pair(token: 1, expert: 5, rank: 0),+ Self.pair(token: 1, expert: 3, rank: 1),+ Self.pair(token: 2, expert: 1, rank: 0),+ Self.pair(token: 2, expert: 5, rank: 1),+ ]+ return try PrefillMoEGrouping.groupTokenExpertPairs(+ pairs,+ queryCount: 3,+ topK: 2,+ numExperts: 8,+ tileExpertCount: 3)+ }++ static func byte(_ view: TensorView, at relativeOffset: Int) -> UInt8 {+ view.buffer.contents()+ .advanced(by: Int(view.offset) + relativeOffset)+ .load(as: UInt8.self)+ }++ static func streamedViewsWithNonzeroOffsets(device: MTLDevice,+ pool: SyntheticExpertPool,+ expertIDs: [Int]) throws -> [TensorView] {+ try expertIDs.enumerated().map { index, expertID in+ let start = expertID * pool.stride+ let end = start + pool.stride+ let prefix = 64 + index * 16+ let suffix = 32+ var bytes = [UInt8](repeating: 0xA5, count: prefix)+ bytes.append(contentsOf: pool.bytes[start..<end])+ bytes.append(contentsOf: repeatElement(UInt8(0x5A), count: suffix))+ guard let buffer = device.makeBuffer(bytes: bytes,+ length: bytes.count,+ options: .storageModeShared) else {+ throw PrefillGroupedRoutedMoEError.allocationFailed("streamed expert \(expertID)")+ }+ return TensorView(buffer: buffer,+ offset: UInt64(prefix),+ length: UInt64(pool.stride),+ scaleOffset: 0,+ scaleLength: 0,+ biasOffset: 0,+ biasLength: 0,+ shape: (0, UInt32(expertID), 0, 0),+ dtype: 0)+ }+ }++ struct SyntheticExpertPool {+ let bytes: [UInt8]+ let offsets: MoEExpertOffsets+ let stride: Int+ }++ static func makeSyntheticExpertPool(numExperts: Int, d: Int, f: Int) -> SyntheticExpertPool {+ var allBytes: [UInt8] = []+ var offsets: MoEExpertOffsets?+ var stride = 0+ for expert in 0..<numExperts {+ var bytes: [UInt8] = []+ let gateWOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: f, cols: d, expert: expert, role: 0),+ to: &bytes,+ component: .packed)+ let gateSOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: f, cols: d, expert: expert, role: 0),+ to: &bytes,+ component: .scales)+ let gateBOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: f, cols: d, expert: expert, role: 0),+ to: &bytes,+ component: .biases)++ let upWOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: f, cols: d, expert: expert, role: 1),+ to: &bytes,+ component: .packed)+ let upSOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: f, cols: d, expert: expert, role: 1),+ to: &bytes,+ component: .scales)+ let upBOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: f, cols: d, expert: expert, role: 1),+ to: &bytes,+ component: .biases)++ let downWOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: d, cols: f, expert: expert, role: 2),+ to: &bytes,+ component: .packed)+ let downSOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: d, cols: f, expert: expert, role: 2),+ to: &bytes,+ component: .scales)+ let downBOff = UInt32(bytes.count)+ Self.appendProjection(rows: Self.syntheticRows(rows: d, cols: f, expert: expert, role: 2),+ to: &bytes,+ component: .biases)++ let currentOffsets = MoEExpertOffsets(gateWOff: gateWOff,+ gateSOff: gateSOff,+ gateBOff: gateBOff,+ upWOff: upWOff,+ upSOff: upSOff,+ upBOff: upBOff,+ downWOff: downWOff,+ downSOff: downSOff,+ downBOff: downBOff)+ if offsets == nil {+ offsets = currentOffsets+ stride = bytes.count+ } else {+ #expect(stride == bytes.count)+ #expect(offsets!.gateWOff == currentOffsets.gateWOff)+ #expect(offsets!.downBOff == currentOffsets.downBOff)+ }+ allBytes.append(contentsOf: bytes)+ }+ return SyntheticExpertPool(bytes: allBytes, offsets: offsets!, stride: stride)+ }++ enum ProjectionComponent {+ case packed+ case scales+ case biases+ }++ static func appendProjection(rows: [[Float]],+ to bytes: inout [UInt8],+ component: ProjectionComponent) {+ let quantized = rows.map { Quantization.quantizeInt4Affine($0) }+ switch component {+ case .packed:+ for row in quantized {+ bytes.append(contentsOf: row.packed)+ }+ case .scales:+ for row in quantized {+ Self.appendU16(row.scales, to: &bytes)+ }+ case .biases:+ for row in quantized {+ Self.appendU16(row.biases, to: &bytes)+ }+ }+ }++ static func syntheticRows(rows: Int, cols: Int, expert: Int, role: Int) -> [[Float]] {+ (0..<rows).map { row in+ (0..<cols).map { col in+ Float(expert + 1) * 0.001+ + Float(role + 1) * 0.003+ + Float((row % 7) - 3) * 0.0004+ + Float((col % 11) - 5) * 0.0002+ }+ }+ }++ static func appendU16(_ values: [UInt16], to bytes: inout [UInt8]) {+ for value in values {+ bytes.append(UInt8(truncatingIfNeeded: value))+ bytes.append(UInt8(truncatingIfNeeded: value >> 8))+ }+ }++ static func readU16(_ bytes: [UInt8], _ offset: Int) -> UInt16 {+ UInt16(bytes[offset]) | (UInt16(bytes[offset + 1]) << 8)+ }++ static func cpuSyntheticRoutePartials(routes: PrefillMoEGroupedRoutes,+ hidden: [Float16],+ hiddenStride: Int,+ pool: SyntheticExpertPool,+ topK: Int,+ d: Int,+ f: Int) -> [Float16] {+ var out = [Float16](repeating: -99, count: routes.queryCount * topK * d)+ for pair in routes.sortedPairs {+ let expertBase = Int(pair.expert) * pool.stride+ let xBase = Int(pair.token) * hiddenStride+ let x = (0..<d).map { Float(hidden[xBase + $0]) }+ var act = [Float16](repeating: 0, count: f)+ for row in 0..<f {+ let gate = Self.cpuInt4Dot(bytes: pool.bytes,+ base: expertBase,+ wOff: Int(pool.offsets.gateWOff),+ sOff: Int(pool.offsets.gateSOff),+ bOff: Int(pool.offsets.gateBOff),+ row: row,+ n: d,+ x: x)+ let up = Self.cpuInt4Dot(bytes: pool.bytes,+ base: expertBase,+ wOff: Int(pool.offsets.upWOff),+ sOff: Int(pool.offsets.upSOff),+ bOff: Int(pool.offsets.upBOff),+ row: row,+ n: d,+ x: x)+ act[row] = Float16(MoeRef.geluTanh([gate])[0] * up)+ }+ let actFloat = act.map { Float($0) }+ let outBase = (Int(pair.token) * topK + Int(pair.rank)) * d+ for row in 0..<d {+ let value = Self.cpuInt4Dot(bytes: pool.bytes,+ base: expertBase,+ wOff: Int(pool.offsets.downWOff),+ sOff: Int(pool.offsets.downSOff),+ bOff: Int(pool.offsets.downBOff),+ row: row,+ n: f,+ x: actFloat)+ out[outBase + row] = Float16(value)+ }+ }+ return out+ }++ static func cpuInt4Dot(bytes: [UInt8],+ base: Int,+ wOff: Int,+ sOff: Int,+ bOff: Int,+ row: Int,+ n: Int,+ x: [Float]) -> Float {+ let groups = n / Quantization.groupSize+ let rowBytes = n / 2+ let wRow = base + wOff + row * rowBytes+ let sRow = base + sOff + row * groups * MemoryLayout<UInt16>.stride+ let bRow = base + bOff + row * groups * MemoryLayout<UInt16>.stride+ var acc: Float = 0+ for group in 0..<groups {+ let scale = Quantization.bf16ToFloat(Self.readU16(bytes, sRow + group * 2))+ let bias = Quantization.bf16ToFloat(Self.readU16(bytes, bRow + group * 2))+ for k in 0..<Quantization.groupSize {+ let col = group * Quantization.groupSize + k+ let packed = bytes[wRow + col / 2]+ let q = (k & 1) == 0 ? Float(packed & 0x0F) : Float(packed >> 4)+ acc += (q * scale + bias) * x[col]+ }+ }+ return acc+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillLayerTailTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillLayerTailTests.swiftnew file mode 100644index 00000000..08e95d63--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillLayerTailTests.swift@@ -0,0 +1,156 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillLayerTailTests {+ private static let d = ArchConfig.gemma4_26B_A4B.hiddenSize+ private static let eps: Float = 1e-6++ @Test func blockLayerTailMatchesRepeatedFusedRows() throws {+ let rows = 3+ let h2Stride = Self.d + 9+ let h1Stride = Self.d + 13+ let hiddenStride = Self.d + 17+ var rng = SplitMix64(seed: 0x7A11_B10C)+ let h2 = Self.makeBlock(rows: rows,+ rowStride: h2Stride,+ usedPerRow: Self.d,+ rng: &rng,+ sentinel: -21.0)+ let h1 = Self.makeBlock(rows: rows,+ rowStride: h1Stride,+ usedPerRow: Self.d,+ rng: &rng,+ sentinel: -23.0)+ let hidden = Self.makeBlock(rows: rows,+ rowStride: hiddenStride,+ usedPerRow: Self.d,+ rng: &rng,+ sentinel: -25.0)+ let wPostFFN2 = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let wPostFFN = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let layerScalar = rng.uniform(0.75, 1.25)++ let ctx = try MetalContext()+ let fused = try FusedLayerTail(context: ctx)+ let block = try PrefillLayerTail(context: ctx)+ guard+ let wPostFFN2Buf = ctx.device.makeBuffer(bytes: wPostFFN2,+ length: wPostFFN2.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let wPostFFNBuf = ctx.device.makeBuffer(bytes: wPostFFN,+ length: wPostFFN.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let h2Block = Fp16Buffer.make(ctx.device, halves: h2),+ let h1Block = Fp16Buffer.make(ctx.device, halves: h1),+ let hiddenBlock = Fp16Buffer.make(ctx.device, halves: hidden)+ else {+ Issue.record("alloc failed")+ return+ }++ var hiddenRef = hidden+ for row in 0..<rows {+ let h2Row = Array(h2[(row * h2Stride)..<(row * h2Stride + Self.d)])+ let h1Row = Array(h1[(row * h1Stride)..<(row * h1Stride + Self.d)])+ let hiddenRow = Array(hidden[(row * hiddenStride)..<(row * hiddenStride + Self.d)])+ guard+ let h2Buf = Fp16Buffer.make(ctx.device, halves: h2Row),+ let h1Buf = Fp16Buffer.make(ctx.device, halves: h1Row),+ let hiddenBuf = Fp16Buffer.make(ctx.device, halves: hiddenRow)+ else {+ Issue.record("row alloc failed")+ return+ }+ let cb = ctx.queue.makeCommandBuffer()!+ fused.encode(commandBuffer: cb,+ h2: h2Buf,+ h1: h1Buf,+ hidden: hiddenBuf,+ postFFN2Weight: wPostFFN2Buf,+ postFFNWeight: wPostFFNBuf,+ d: UInt32(Self.d),+ eps: Self.eps,+ layerScalar: layerScalar)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ Issue.record("fused row command failed: \(err)")+ return+ }+ Self.copyUsed(Fp16Buffer.readHalf(hiddenBuf, count: Self.d),+ into: &hiddenRef,+ row: row,+ rowStride: hiddenStride)+ }++ let cb = ctx.queue.makeCommandBuffer()!+ block.encode(commandBuffer: cb,+ h2: h2Block,+ h1: h1Block,+ hidden: hiddenBlock,+ postFFN2Weight: wPostFFN2Buf,+ postFFNWeight: wPostFFNBuf,+ queryCount: UInt32(rows),+ d: UInt32(Self.d),+ h2StrideElements: UInt32(h2Stride),+ h1StrideElements: UInt32(h1Stride),+ hiddenStrideElements: UInt32(hiddenStride),+ eps: Self.eps,+ layerScalar: layerScalar)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ Issue.record("block command failed: \(err)")+ return+ }++ #expect(Fp16Buffer.readHalf(hiddenBlock, count: rows * hiddenStride) == hiddenRef)+ #expect(Fp16Buffer.readHalf(h2Block, count: rows * h2Stride) == h2)+ #expect(Fp16Buffer.readHalf(h1Block, count: rows * h1Stride) == h1)+ Self.assertPaddingUnchanged(hiddenBlock,+ original: hidden,+ rows: rows,+ rowStride: hiddenStride,+ usedPerRow: Self.d)+ }++ private static func makeBlock(rows: Int,+ rowStride: Int,+ usedPerRow: Int,+ rng: inout SplitMix64,+ sentinel: Float16) -> [Float16] {+ var values = [Float16](repeating: sentinel, count: rows * rowStride)+ for row in 0..<rows {+ for i in 0..<usedPerRow {+ values[row * rowStride + i] = Float16(rng.uniform(-1.0, 1.0))+ }+ }+ return values+ }++ private static func copyUsed(_ source: [Float16],+ into destination: inout [Float16],+ row: Int,+ rowStride: Int) {+ for i in 0..<source.count {+ destination[row * rowStride + i] = source[i]+ }+ }++ private static func assertPaddingUnchanged(_ buffer: MTLBuffer,+ original: [Float16],+ rows: Int,+ rowStride: Int,+ usedPerRow: Int) {+ let ptr = buffer.contents().bindMemory(to: Float16.self, capacity: rows * rowStride)+ for row in 0..<rows {+ for i in usedPerRow..<rowStride {+ #expect(ptr[row * rowStride + i] == original[row * rowStride + i],+ "padding changed at row=\(row) i=\(i)")+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillMoEGroupingTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillMoEGroupingTests.swiftnew file mode 100644index 00000000..a0d88aa5--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillMoEGroupingTests.swift@@ -0,0 +1,214 @@+import Testing+@testable import TurboFieldfare++@Suite struct PrefillMoEGroupingTests {+ @Test func groupingSortsPairsAndBuildsOffsetsCountsAndTiles() throws {+ let pairs = [+ Self.pair(token: 0, expert: 3, rank: 0, weightBits: 10),+ Self.pair(token: 0, expert: 1, rank: 1, weightBits: 11),+ Self.pair(token: 0, expert: 4, rank: 2, weightBits: 12),+ Self.pair(token: 1, expert: 1, rank: 0, weightBits: 13),+ Self.pair(token: 1, expert: 3, rank: 1, weightBits: 14),+ Self.pair(token: 1, expert: 2, rank: 2, weightBits: 15),+ Self.pair(token: 2, expert: 4, rank: 0, weightBits: 16),+ Self.pair(token: 2, expert: 3, rank: 1, weightBits: 17),+ Self.pair(token: 2, expert: 1, rank: 2, weightBits: 18),+ Self.pair(token: 3, expert: 5, rank: 0, weightBits: 19),+ Self.pair(token: 3, expert: 1, rank: 1, weightBits: 20),+ Self.pair(token: 3, expert: 4, rank: 2, weightBits: 21),+ ].reversed()++ let grouped = try PrefillMoEGrouping.groupTokenExpertPairs(+ Array(pairs),+ queryCount: 4,+ topK: 3,+ numExperts: 6,+ tileExpertCount: 2)++ #expect(grouped.sortedPairs.map { $0.expert } == [1, 1, 1, 1, 2, 3, 3, 3, 4, 4, 4, 5])+ #expect(grouped.sortedPairs.map { [$0.token, $0.rank] } == [+ [0, 1], [1, 0], [2, 2], [3, 1],+ [1, 2],+ [0, 0], [1, 1], [2, 1],+ [0, 2], [2, 0], [3, 2],+ [3, 0],+ ])+ #expect(grouped.perExpertOffsets == [UInt32.max, 0, 4, 5, 8, 11])+ #expect(grouped.perExpertCounts == [0, 4, 1, 3, 3, 1])+ #expect(grouped.groups == [+ PrefillMoEGroup(expert: 1, pairStart: 0, pairCount: 4),+ PrefillMoEGroup(expert: 2, pairStart: 4, pairCount: 1),+ PrefillMoEGroup(expert: 3, pairStart: 5, pairCount: 3),+ PrefillMoEGroup(expert: 4, pairStart: 8, pairCount: 3),+ PrefillMoEGroup(expert: 5, pairStart: 11, pairCount: 1),+ ])+ #expect(grouped.tiles == [+ PrefillMoETile(groupStart: 0, groupCount: 2, pairStart: 0, pairCount: 5),+ PrefillMoETile(groupStart: 2, groupCount: 2, pairStart: 5, pairCount: 6),+ PrefillMoETile(groupStart: 4, groupCount: 1, pairStart: 11, pairCount: 1),+ ])+ #expect(grouped.maxPairsPerExpert == 4)+ #expect(grouped.maxPairsPerTile == 6)+ #expect(grouped.maxLiveExpertsPerTile == 2)+ }++ @Test func groupingIsDeterministicAcrossInputOrderAndPreservesWeightBits() throws {+ let tokenMajor = [+ Self.pair(token: 0, expert: 2, rank: 0, weightBits: 101),+ Self.pair(token: 0, expert: 1, rank: 1, weightBits: 102),+ Self.pair(token: 1, expert: 2, rank: 0, weightBits: 103),+ Self.pair(token: 1, expert: 0, rank: 1, weightBits: 104),+ Self.pair(token: 2, expert: 1, rank: 0, weightBits: 105),+ Self.pair(token: 2, expert: 2, rank: 1, weightBits: 106),+ ]+ let shuffled = [tokenMajor[5], tokenMajor[1], tokenMajor[3],+ tokenMajor[0], tokenMajor[4], tokenMajor[2]]++ let a = try PrefillMoEGrouping.groupTokenExpertPairs(+ tokenMajor,+ queryCount: 3,+ topK: 2,+ numExperts: 3,+ tileExpertCount: 2)+ let b = try PrefillMoEGrouping.groupTokenExpertPairs(+ shuffled,+ queryCount: 3,+ topK: 2,+ numExperts: 3,+ tileExpertCount: 2)++ #expect(a == b)+ #expect(a.sortedPairs.map { $0.weightBitsAndReserved } == [104, 102, 105, 101, 103, 106])+ }++ @Test func groupingCanOrderTilesByExpertSortKeysWhileKeepingPairRangesContiguous() throws {+ let pairs = [+ Self.pair(token: 0, expert: 1, rank: 0, weightBits: 10),+ Self.pair(token: 0, expert: 2, rank: 1, weightBits: 20),+ Self.pair(token: 1, expert: 3, rank: 0, weightBits: 30),+ Self.pair(token: 1, expert: 1, rank: 1, weightBits: 11),+ Self.pair(token: 2, expert: 2, rank: 0, weightBits: 21),+ Self.pair(token: 2, expert: 3, rank: 1, weightBits: 31),+ ]++ let grouped = try PrefillMoEGrouping.groupTokenExpertPairs(+ pairs,+ queryCount: 3,+ topK: 2,+ numExperts: 4,+ tileExpertCount: 2,+ expertSortKeys: [0, 30, 10, 20])++ #expect(grouped.groups.map(\.expert) == [2, 3, 1])+ #expect(grouped.sortedPairs.map(\.expert) == [2, 2, 3, 3, 1, 1])+ #expect(grouped.perExpertOffsets == [UInt32.max, 4, 0, 2])+ #expect(grouped.tiles == [+ PrefillMoETile(groupStart: 0, groupCount: 2, pairStart: 0, pairCount: 4),+ PrefillMoETile(groupStart: 2, groupCount: 1, pairStart: 4, pairCount: 2),+ ])+ for tile in grouped.tiles {+ let slice = grouped.sortedPairs[Int(tile.pairStart)..<Int(tile.pairStart + tile.pairCount)]+ let tileExperts = grouped.groups[Int(tile.groupStart)..<Int(tile.groupStart + tile.groupCount)]+ .map(\.expert)+ #expect(Set(slice.map(\.expert)) == Set(tileExperts))+ }+ }++ @Test func groupingRejectsInvalidMetadataBeforeKernelUse() throws {+ #expect {+ _ = try PrefillMoEGrouping.groupTokenExpertPairs(+ [Self.pair(token: 0, expert: 0, rank: 0, weightBits: 1)],+ queryCount: 1,+ topK: 1,+ numExperts: 1,+ tileExpertCount: 17)+ } throws: { error in+ if case PrefillMoEGroupingError.invalidTileExpertCount(17) = error { return true }+ return false+ }++ #expect {+ _ = try PrefillMoEGrouping.groupTokenExpertPairs(+ [Self.pair(token: 0, expert: 2, rank: 0, weightBits: 1)],+ queryCount: 1,+ topK: 1,+ numExperts: 2,+ tileExpertCount: 1)+ } throws: { error in+ if case PrefillMoEGroupingError.expertOutOfRange(2) = error { return true }+ return false+ }++ #expect {+ _ = try PrefillMoEGrouping.groupTokenExpertPairs(+ [+ Self.pair(token: 0, expert: 0, rank: 0, weightBits: 1),+ Self.pair(token: 0, expert: 1, rank: 0, weightBits: 2),+ ],+ queryCount: 1,+ topK: 2,+ numExperts: 2,+ tileExpertCount: 1)+ } throws: { error in+ if case PrefillMoEGroupingError.duplicateTokenRank(token: 0, rank: 0) = error {+ return true+ }+ return false+ }++ #expect {+ _ = try PrefillMoEGrouping.groupTokenExpertPairs(+ [Self.pair(token: 0, expert: 0, rank: 0, weightBits: 1)],+ queryCount: 1,+ topK: 1,+ numExperts: 2,+ tileExpertCount: 1,+ expertSortKeys: [0])+ } throws: { error in+ if case PrefillMoEGroupingError.expertSortKeyCountMismatch(expected: 2, actual: 1) = error {+ return true+ }+ return false+ }+ }++ @Test func groupingToleratesRealTracePairPressureAtT32() throws {+ var pairs: [PrefillTokenExpertPair] = []+ pairs.reserveCapacity(256)+ for token in 0..<32 {+ for rank in 0..<8 {+ let expert = UInt32((token + rank * 7) % 74)+ pairs.append(Self.pair(token: UInt32(token),+ expert: expert,+ rank: UInt32(rank),+ weightBits: UInt32(token * 8 + rank)))+ }+ }++ let grouped = try PrefillMoEGrouping.groupTokenExpertPairs(+ pairs,+ queryCount: 32,+ topK: 8,+ numExperts: 128,+ tileExpertCount: 16)++ #expect(grouped.sortedPairs.count == 256)+ #expect(grouped.groups.count <= 74)+ #expect(grouped.maxLiveExpertsPerTile <= 16)+ #expect(grouped.maxPairsPerTile <= 256)+ for tile in grouped.tiles {+ #expect(tile.groupCount <= 16)+ #expect(tile.pairCount > 0)+ }+ }++ private static func pair(token: UInt32,+ expert: UInt32,+ rank: UInt32,+ weightBits: UInt32) -> PrefillTokenExpertPair {+ PrefillTokenExpertPair(token: token,+ expert: expert,+ rank: rank,+ weightBitsAndReserved: weightBits)+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillMoETests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillMoETests.swiftnew file mode 100644index 00000000..f170d111--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillMoETests.swift@@ -0,0 +1,74 @@+import Metal+import Testing++@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillMoETests {+ @Test func tokenMajorReduceMatchesCPUReference() throws {+ let rows = 3+ let topK = 8+ let d = 64+ var rng = SplitMix64(seed: 0x4D0E_2026)+ let partials = (0..<(rows * topK * d)).map { _ in Float16(rng.uniform(-2.0, 2.0)) }+ let weights = (0..<(rows * topK)).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let sentinel = [Float16](repeating: Float16(-19.0), count: rows * d)+ let expected = Self.cpuReduce(routePartials: partials,+ routeWeights: weights,+ rows: rows,+ topK: topK,+ d: d)++ let ctx = try MetalContext()+ let prefill = try PrefillMoE(context: ctx)+ guard let partialsBuf = Fp16Buffer.make(ctx.device, halves: partials),+ let weightsBuf = Fp16Buffer.make(ctx.device, halves: weights),+ let h2Buf = Fp16Buffer.make(ctx.device, halves: sentinel),+ let cb = ctx.queue.makeCommandBuffer() else {+ Issue.record("alloc failed")+ return+ }+ prefill.encodeReduceTokenMajor(commandBuffer: cb,+ routePartials: partialsBuf,+ routeWeights: weightsBuf,+ h2: h2Buf,+ queryCount: UInt32(rows),+ topK: UInt32(topK),+ d: UInt32(d))+ cb.commit()+ cb.waitUntilCompleted()+ #expect(cb.error == nil)++ let got = Fp16Buffer.readHalf(h2Buf, count: rows * d)+ Self.assertClose(got, expected, tolerance: 2e-3)+ }++ private static func cpuReduce(routePartials: [Float16],+ routeWeights: [Float16],+ rows: Int,+ topK: Int,+ d: Int) -> [Float16] {+ var out = [Float16](repeating: 0, count: rows * d)+ for token in 0..<rows {+ for column in 0..<d {+ var accumulator: Float = 0+ for rank in 0..<topK {+ let partialIndex = (token * topK + rank) * d + column+ accumulator += Float(routeWeights[token * topK + rank])+ * Float(routePartials[partialIndex])+ }+ out[token * d + column] = Float16(accumulator)+ }+ }+ return out+ }++ private static func assertClose(_ actual: [Float16],+ _ expected: [Float16],+ tolerance: Float) {+ let maxAbsoluteDifference = zip(actual, expected)+ .map { abs(Float($0) - Float($1)) }+ .max() ?? 0+ #expect(maxAbsoluteDifference <= tolerance, "maxAbsDiff=\(maxAbsoluteDifference)")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPerHeadNormTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPerHeadNormTests.swiftnew file mode 100644index 00000000..ba0e8510--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPerHeadNormTests.swift@@ -0,0 +1,163 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillPerHeadNormTests {+ private static func makeBlock(rows: Int,+ rowStride: Int,+ usedPerRow: Int,+ seed: UInt64,+ label: String) -> [Float16] {+ var rng = SeedTree(seed).key(label)+ var values = [Float16](repeating: Float16(-5.0), count: rows * rowStride)+ for row in 0..<rows {+ for i in 0..<usedPerRow {+ values[row * rowStride + i] = Float16(rng.uniform(-1.0, 1.0))+ }+ }+ return values+ }++ private static func assertPaddingUnchanged(_ buffer: MTLBuffer,+ original: [Float16],+ rows: Int,+ rowStride: Int,+ usedPerRow: Int) {+ let ptr = buffer.contents().bindMemory(to: Float16.self, capacity: rows * rowStride)+ for row in 0..<rows {+ for i in usedPerRow..<rowStride {+ #expect(ptr[row * rowStride + i] == original[row * rowStride + i],+ "padding changed at row=\(row) i=\(i)")+ }+ }+ }++ private static func runBF16Case(rows: Int,+ heads: Int,+ headDim: Int,+ seed: UInt64,+ label: String) throws {+ let used = heads * headDim+ let rowStride = used + 23+ let input = makeBlock(rows: rows,+ rowStride: rowStride,+ usedPerRow: used,+ seed: seed,+ label: label)+ var rng = SeedTree(seed).key("\(label)-weight")+ let weight = (0..<headDim).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }++ let ctx = try MetalContext()+ let scalar = try RMSNorm(context: ctx)+ let block = try PrefillPerHeadNorm(context: ctx)+ guard let weightBuf = ctx.device.makeBuffer(bytes: weight,+ length: weight.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let ref = Fp16Buffer.make(ctx.device, halves: input),+ let candidate = Fp16Buffer.make(ctx.device, halves: input) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ scalar.encodeBF16WPerHead(commandBuffer: cb,+ x: ref,+ xOffset: row * rowStride * MemoryLayout<Float16>.size,+ weight: weightBuf,+ out: ref,+ outOffset: row * rowStride * MemoryLayout<Float16>.size,+ headDim: UInt32(headDim),+ numHeads: heads,+ eps: 1e-6)+ }+ block.encodeBF16W(commandBuffer: cb,+ x: candidate,+ weight: weightBuf,+ out: candidate,+ queryCount: UInt32(rows),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ tokenStrideElements: UInt32(rowStride),+ eps: 1e-6)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(ref, count: rows * rowStride)+ let actual = Fp16Buffer.read(candidate, count: rows * rowStride)+ #expect(actual == reference, "block BF16 per-head norm must match repeated scalar per-token path for \(label)")+ assertPaddingUnchanged(candidate,+ original: input,+ rows: rows,+ rowStride: rowStride,+ usedPerRow: used)+ }++ private static func runNoScaleCase(rows: Int,+ heads: Int,+ headDim: Int,+ seed: UInt64,+ label: String) throws {+ let used = heads * headDim+ let rowStride = used + 17+ let input = makeBlock(rows: rows,+ rowStride: rowStride,+ usedPerRow: used,+ seed: seed,+ label: label)++ let ctx = try MetalContext()+ let scalar = try RMSNorm(context: ctx)+ let block = try PrefillPerHeadNorm(context: ctx)+ guard let ref = Fp16Buffer.make(ctx.device, halves: input),+ let candidate = Fp16Buffer.make(ctx.device, halves: input) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ scalar.encodeNoScalePerHead(commandBuffer: cb,+ x: ref,+ xOffset: row * rowStride * MemoryLayout<Float16>.size,+ out: ref,+ outOffset: row * rowStride * MemoryLayout<Float16>.size,+ headDim: UInt32(headDim),+ numHeads: heads,+ eps: 1e-6)+ }+ block.encodeNoScale(commandBuffer: cb,+ x: candidate,+ out: candidate,+ queryCount: UInt32(rows),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ tokenStrideElements: UInt32(rowStride),+ eps: 1e-6)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(ref, count: rows * rowStride)+ let actual = Fp16Buffer.read(candidate, count: rows * rowStride)+ #expect(actual == reference, "block no-scale per-head norm must match repeated scalar per-token path for \(label)")+ assertPaddingUnchanged(candidate,+ original: input,+ rows: rows,+ rowStride: rowStride,+ usedPerRow: used)+ }++ @Test func blockBF16PerHeadNormMatchesRepeatedScalarQKShapes() throws {+ try Self.runBF16Case(rows: 3, heads: 16, headDim: 256, seed: 0xB501, label: "swa-q")+ try Self.runBF16Case(rows: 3, heads: 8, headDim: 256, seed: 0xB502, label: "swa-k")+ try Self.runBF16Case(rows: 2, heads: 16, headDim: 512, seed: 0xB503, label: "full-q")+ try Self.runBF16Case(rows: 2, heads: 2, headDim: 512, seed: 0xB504, label: "full-k")+ }++ @Test func blockNoScalePerHeadNormMatchesRepeatedScalarVShapes() throws {+ try Self.runNoScaleCase(rows: 3, heads: 8, headDim: 256, seed: 0xB601, label: "swa-v")+ try Self.runNoScaleCase(rows: 2, heads: 2, headDim: 512, seed: 0xB602, label: "full-v")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPostAttentionSetupTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPostAttentionSetupTests.swiftnew file mode 100644index 00000000..8d088637--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPostAttentionSetupTests.swift@@ -0,0 +1,201 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillPostAttentionSetupTests {+ private static let d = ArchConfig.gemma4_26B_A4B.hiddenSize+ private static let eps: Float = 1e-6++ @Test func blockPostAttentionSetupMatchesRepeatedScalarFusedRows() throws {+ let rows = 3+ let hiddenStride = Self.d + 11+ let attnStride = Self.d + 17+ let outStride = Self.d + 23+ var rng = SplitMix64(seed: 0x5057_A77E)+ let hidden = Self.makeBlock(rows: rows,+ rowStride: hiddenStride,+ usedPerRow: Self.d,+ rng: &rng,+ sentinel: -11.0)+ let attn = Self.makeBlock(rows: rows,+ rowStride: attnStride,+ usedPerRow: Self.d,+ rng: &rng,+ sentinel: -13.0)+ let outSentinel = [Float16](repeating: Float16(-17.0), count: rows * outStride)+ let wPost = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let wPre = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let wPre2 = (0..<Self.d).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }++ let ctx = try MetalContext()+ let scalar = try FusedPostAttentionSetup(context: ctx)+ let block = try PrefillPostAttentionSetup(context: ctx)+ guard+ let wPostBuf = ctx.device.makeBuffer(bytes: wPost,+ length: wPost.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let wPreBuf = ctx.device.makeBuffer(bytes: wPre,+ length: wPre.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let wPre2Buf = ctx.device.makeBuffer(bytes: wPre2,+ length: wPre2.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let hiddenBlock = Fp16Buffer.make(ctx.device, halves: hidden),+ let attnBlock = Fp16Buffer.make(ctx.device, halves: attn),+ let denseBlock = Fp16Buffer.make(ctx.device, halves: outSentinel),+ let routedBlock = Fp16Buffer.make(ctx.device, halves: outSentinel),+ let routerBlock = Fp16Buffer.make(ctx.device, halves: outSentinel)+ else {+ Issue.record("alloc failed")+ return+ }++ var hiddenRef = hidden+ var denseRef = outSentinel+ var routedRef = outSentinel+ var routerRef = outSentinel++ for row in 0..<rows {+ let h = Array(hidden[(row * hiddenStride)..<(row * hiddenStride + Self.d)])+ let a = Array(attn[(row * attnStride)..<(row * attnStride + Self.d)])+ guard+ let hBuf = Fp16Buffer.make(ctx.device, halves: h),+ let aBuf = Fp16Buffer.make(ctx.device, halves: a),+ let denseBuf = Fp16Buffer.make(ctx.device, count: Self.d),+ let routedBuf = Fp16Buffer.make(ctx.device, count: Self.d),+ let routerBuf = Fp16Buffer.make(ctx.device, count: Self.d)+ else {+ Issue.record("row alloc failed")+ return+ }+ let cb = ctx.queue.makeCommandBuffer()!+ scalar.encode(commandBuffer: cb,+ hidden: hBuf,+ attn: aBuf,+ denseX: denseBuf,+ routedX: routedBuf,+ routerX: routerBuf,+ postAttentionWeight: wPostBuf,+ preFFNWeight: wPreBuf,+ preFFN2Weight: wPre2Buf,+ d: UInt32(Self.d),+ eps: Self.eps)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ Issue.record("scalar row command failed: \(err)")+ return+ }+ Self.copyUsed(Fp16Buffer.readHalf(hBuf, count: Self.d),+ into: &hiddenRef,+ row: row,+ rowStride: hiddenStride)+ Self.copyUsed(Fp16Buffer.readHalf(denseBuf, count: Self.d),+ into: &denseRef,+ row: row,+ rowStride: outStride)+ Self.copyUsed(Fp16Buffer.readHalf(routedBuf, count: Self.d),+ into: &routedRef,+ row: row,+ rowStride: outStride)+ Self.copyUsed(Fp16Buffer.readHalf(routerBuf, count: Self.d),+ into: &routerRef,+ row: row,+ rowStride: outStride)+ }++ let cb = ctx.queue.makeCommandBuffer()!+ block.encode(commandBuffer: cb,+ hidden: hiddenBlock,+ attn: attnBlock,+ denseX: denseBlock,+ routedX: routedBlock,+ routerX: routerBlock,+ postAttentionWeight: wPostBuf,+ preFFNWeight: wPreBuf,+ preFFN2Weight: wPre2Buf,+ queryCount: UInt32(rows),+ d: UInt32(Self.d),+ hiddenStrideElements: UInt32(hiddenStride),+ attnStrideElements: UInt32(attnStride),+ denseStrideElements: UInt32(outStride),+ routedStrideElements: UInt32(outStride),+ routerStrideElements: UInt32(outStride),+ eps: Self.eps)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ Issue.record("block command failed: \(err)")+ return+ }++ #expect(Fp16Buffer.readHalf(hiddenBlock, count: rows * hiddenStride) == hiddenRef)+ #expect(Fp16Buffer.readHalf(denseBlock, count: rows * outStride) == denseRef)+ #expect(Fp16Buffer.readHalf(routedBlock, count: rows * outStride) == routedRef)+ #expect(Fp16Buffer.readHalf(routerBlock, count: rows * outStride) == routerRef)+ Self.assertPaddingUnchanged(hiddenBlock,+ original: hidden,+ rows: rows,+ rowStride: hiddenStride,+ usedPerRow: Self.d)+ Self.assertPaddingUnchanged(attnBlock,+ original: attn,+ rows: rows,+ rowStride: attnStride,+ usedPerRow: Self.d)+ Self.assertPaddingUnchanged(denseBlock,+ original: outSentinel,+ rows: rows,+ rowStride: outStride,+ usedPerRow: Self.d)+ Self.assertPaddingUnchanged(routedBlock,+ original: outSentinel,+ rows: rows,+ rowStride: outStride,+ usedPerRow: Self.d)+ Self.assertPaddingUnchanged(routerBlock,+ original: outSentinel,+ rows: rows,+ rowStride: outStride,+ usedPerRow: Self.d)+ }++ private static func makeBlock(rows: Int,+ rowStride: Int,+ usedPerRow: Int,+ rng: inout SplitMix64,+ sentinel: Float16) -> [Float16] {+ var values = [Float16](repeating: sentinel, count: rows * rowStride)+ for row in 0..<rows {+ for i in 0..<usedPerRow {+ values[row * rowStride + i] = Float16(rng.uniform(-1.0, 1.0))+ }+ }+ return values+ }++ private static func copyUsed(_ source: [Float16],+ into destination: inout [Float16],+ row: Int,+ rowStride: Int) {+ for i in 0..<source.count {+ destination[row * rowStride + i] = source[i]+ }+ }++ private static func assertPaddingUnchanged(_ buffer: MTLBuffer,+ original: [Float16],+ rows: Int,+ rowStride: Int,+ usedPerRow: Int) {+ let ptr = buffer.contents().bindMemory(to: Float16.self, capacity: rows * rowStride)+ for row in 0..<rows {+ for i in usedPerRow..<rowStride {+ #expect(ptr[row * rowStride + i] == original[row * rowStride + i],+ "padding changed at row=\(row) i=\(i)")+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPrimitiveTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPrimitiveTests.swiftnew file mode 100644index 00000000..e10f3cf3--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillPrimitiveTests.swift@@ -0,0 +1,136 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillPrimitiveTests {+ private static let vocab = 16+ private static let d = 128+ private static let groupsPerRow = d / Quantization.groupSize++ private static func buildInt4Table(seed: UInt64) -> (packed: [UInt8], scales: [UInt16], biases: [UInt16]) {+ var rng = SeedTree(seed).key("prefill-int4-embed-table")+ var packed = [UInt8](repeating: 0, count: vocab * (d / 2))+ var scales = [UInt16](repeating: 0, count: vocab * groupsPerRow)+ var biases = [UInt16](repeating: 0, count: vocab * groupsPerRow)++ for v in 0..<vocab {+ let row = (0..<d).map { _ in rng.uniform(-1.0, 1.0) }+ let q = Quantization.quantizeInt4Affine(row)+ for i in 0..<(d / 2) {+ packed[v * (d / 2) + i] = q.packed[i]+ }+ for g in 0..<groupsPerRow {+ scales[v * groupsPerRow + g] = q.scales[g]+ biases[v * groupsPerRow + g] = q.biases[g]+ }+ }+ return (packed, scales, biases)+ }++ @Test func embedBlockMatchesPerTokenEmbed() throws {+ let (packed, scales, biases) = Self.buildInt4Table(seed: 0x5101)+ let tokens: [UInt32] = [3, 11, 2, 9, 14]+ let outScale = Float(Self.d).squareRoot()+ let ctx = try MetalContext()+ let scalar = try EmbedLookupInt4(context: ctx)+ let block = try PrefillEmbedLookupInt4(context: ctx)++ guard let tableBuf = ctx.device.makeBuffer(bytes: packed, length: packed.count, options: .storageModeShared),+ let scalesBuf = ctx.device.makeBuffer(bytes: scales,+ length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let biasesBuf = ctx.device.makeBuffer(bytes: biases,+ length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let tokenBuf = ctx.device.makeBuffer(bytes: tokens,+ length: tokens.count * MemoryLayout<UInt32>.size,+ options: .storageModeShared),+ let scalarOut = Fp16Buffer.make(ctx.device, count: tokens.count * Self.d),+ let blockOut = Fp16Buffer.make(ctx.device, count: tokens.count * Self.d) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for (row, token) in tokens.enumerated() {+ scalar.encode(commandBuffer: cb,+ table: tableBuf,+ scales: scalesBuf,+ biases: biasesBuf,+ out: scalarOut,+ outOffset: row * Self.d * MemoryLayout<Float16>.size,+ tokenId: token,+ d: UInt32(Self.d),+ outScale: outScale)+ }+ block.encode(commandBuffer: cb,+ table: tableBuf,+ scales: scalesBuf,+ biases: biasesBuf,+ tokens: tokenBuf,+ out: blockOut,+ t: UInt32(tokens.count),+ d: UInt32(Self.d),+ outScale: outScale)+ cb.commit()+ cb.waitUntilCompleted()++ let scalarRows = Fp16Buffer.read(scalarOut, count: tokens.count * Self.d)+ let blockRows = Fp16Buffer.read(blockOut, count: tokens.count * Self.d)+ #expect(blockRows == scalarRows)+ }++ @Test func blockRMSNormMatchesScalarRows() throws {+ let rows = 7+ let dim = 256+ let eps: Float = 1e-6+ var rng = SeedTree(0x5202).key("prefill-rms-block")+ let x = (0..<(rows * dim)).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let wBits = (0..<dim).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }++ let ctx = try MetalContext()+ let scalar = try RMSNorm(context: ctx)+ let block = try PrefillRMSNorm(context: ctx)+ guard let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let scalarOut = Fp16Buffer.make(ctx.device, count: rows * dim),+ let blockOut = Fp16Buffer.make(ctx.device, count: rows * dim),+ let wBuf = ctx.device.makeBuffer(length: wBits.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared) else {+ Issue.record("alloc failed")+ return+ }+ let wPtr = wBuf.contents().bindMemory(to: UInt16.self, capacity: wBits.count)+ for i in 0..<wBits.count { wPtr[i] = wBits[i] }++ let rowBytes = dim * MemoryLayout<Float16>.size+ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ scalar.encodeBF16W(commandBuffer: cb,+ x: xBuf,+ xOffset: row * rowBytes,+ weight: wBuf,+ out: scalarOut,+ outOffset: row * rowBytes,+ d: UInt32(dim),+ eps: eps)+ }+ block.encodeBF16W(commandBuffer: cb,+ x: xBuf,+ weight: wBuf,+ out: blockOut,+ t: UInt32(rows),+ d: UInt32(dim),+ eps: eps)+ cb.commit()+ cb.waitUntilCompleted()++ let scalarRows = Fp16Buffer.read(scalarOut, count: rows * dim)+ let blockRows = Fp16Buffer.read(blockOut, count: rows * dim)+ let maxAbs = RelError.maxAbsDiff(blockRows, scalarRows)+ let rel = RelError.compute(actual: blockRows, reference: scalarRows)+ #expect(maxAbs <= 1e-3, "maxAbs=\(maxAbs) rel=\(rel)")+ #expect(rel <= 1e-4, "rel=\(rel) maxAbs=\(maxAbs)")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillQKVEpilogueTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillQKVEpilogueTests.swiftnew file mode 100644index 00000000..aa000782--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillQKVEpilogueTests.swift@@ -0,0 +1,261 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillQKVEpilogueTests {+ @Test func blockQKVEpilogueMatchesRepeatedScalarSWA() throws {+ _ = try Self.expectMatchesRepeatedScalar(rows: 3,+ numQHeads: 16,+ numKVHeads: 8,+ headDim: 256,+ startPosition: 1023,+ theta: 10_000.0,+ rotatedPairs: 128,+ sharedKVRaw: false,+ seed: 0x7A50_5A01)+ }++ @Test func blockQKVEpiloguePreservesFullLayerSharedRawKVQuirk() throws {+ let result = try Self.expectMatchesRepeatedScalar(rows: 2,+ numQHeads: 16,+ numKVHeads: 2,+ headDim: 512,+ startPosition: 4095,+ theta: 1_000_000.0,+ rotatedPairs: 64,+ sharedKVRaw: true,+ seed: 0x7A50_F011)+ #expect(result.kUsed != result.vUsed,+ "full-layer K/V must diverge after K norm+RoPE and V no-scale norm")+ }++ private static func expectMatchesRepeatedScalar(rows: Int,+ numQHeads: Int,+ numKVHeads: Int,+ headDim: Int,+ startPosition: Int,+ theta: Float,+ rotatedPairs: UInt32,+ sharedKVRaw: Bool,+ seed: UInt64) throws -> (kUsed: [Float], vUsed: [Float]) {+ let qUsed = numQHeads * headDim+ let kvUsed = numKVHeads * headDim+ let qStride = qUsed + 13+ let kvStride = kvUsed + 17+ let q = Self.makeBlock(rows: rows,+ rowStride: qStride,+ usedPerRow: qUsed,+ seed: seed,+ label: "q")+ let k = Self.makeBlock(rows: rows,+ rowStride: kvStride,+ usedPerRow: kvUsed,+ seed: seed &+ 1,+ label: "k")+ let v = sharedKVRaw+ ? k+ : Self.makeBlock(rows: rows,+ rowStride: kvStride,+ usedPerRow: kvUsed,+ seed: seed &+ 2,+ label: "v")+ var rng = SeedTree(seed).key("norm-weights")+ let qWeight = (0..<headDim).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }+ let kWeight = (0..<headDim).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }++ let ctx = try MetalContext()+ let scalarNorm = try RMSNorm(context: ctx)+ let scalarRoPE = try RoPE(context: ctx)+ let block = try PrefillQKVEpilogue(context: ctx)+ guard+ let qWeightBuf = ctx.device.makeBuffer(bytes: qWeight,+ length: qWeight.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let kWeightBuf = ctx.device.makeBuffer(bytes: kWeight,+ length: kWeight.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let qRef = Fp16Buffer.make(ctx.device, halves: q),+ let kRef = Fp16Buffer.make(ctx.device, halves: k),+ let vRef = Fp16Buffer.make(ctx.device, halves: v),+ let qBlock = Fp16Buffer.make(ctx.device, halves: q),+ let kBlock = Fp16Buffer.make(ctx.device, halves: k),+ let vBlock = Fp16Buffer.make(ctx.device, halves: v)+ else {+ Issue.record("alloc failed")+ return ([], [])+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ let qOffset = row * qStride * MemoryLayout<Float16>.size+ let kvOffset = row * kvStride * MemoryLayout<Float16>.size+ scalarNorm.encodeBF16WPerHead(commandBuffer: cb,+ x: qRef,+ xOffset: qOffset,+ weight: qWeightBuf,+ out: qRef,+ outOffset: qOffset,+ headDim: UInt32(headDim),+ numHeads: numQHeads,+ eps: 1e-6)+ scalarNorm.encodeBF16WPerHead(commandBuffer: cb,+ x: kRef,+ xOffset: kvOffset,+ weight: kWeightBuf,+ out: kRef,+ outOffset: kvOffset,+ headDim: UInt32(headDim),+ numHeads: numKVHeads,+ eps: 1e-6)+ scalarNorm.encodeNoScalePerHead(commandBuffer: cb,+ x: vRef,+ xOffset: kvOffset,+ out: vRef,+ outOffset: kvOffset,+ headDim: UInt32(headDim),+ numHeads: numKVHeads,+ eps: 1e-6)+ if rotatedPairs * 2 == UInt32(headDim) {+ scalarRoPE.encodeDefaultNeox(commandBuffer: cb,+ data: qRef,+ dataOffset: qOffset,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(numQHeads),+ numTokens: 1,+ theta: theta)+ scalarRoPE.encodeDefaultNeox(commandBuffer: cb,+ data: kRef,+ dataOffset: kvOffset,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ numTokens: 1,+ theta: theta)+ } else {+ scalarRoPE.encodeProportionalNeox(commandBuffer: cb,+ data: qRef,+ dataOffset: qOffset,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(numQHeads),+ rotatedPairs: rotatedPairs,+ numTokens: 1,+ theta: theta)+ scalarRoPE.encodeProportionalNeox(commandBuffer: cb,+ data: kRef,+ dataOffset: kvOffset,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(numKVHeads),+ rotatedPairs: rotatedPairs,+ numTokens: 1,+ theta: theta)+ }+ }+ block.encode(commandBuffer: cb,+ q: qBlock,+ k: kBlock,+ v: vBlock,+ qWeight: qWeightBuf,+ kWeight: kWeightBuf,+ startPosition: UInt32(startPosition),+ queryCount: UInt32(rows),+ headDim: UInt32(headDim),+ numQHeads: UInt32(numQHeads),+ numKVHeads: UInt32(numKVHeads),+ qTokenStrideElements: UInt32(qStride),+ kvTokenStrideElements: UInt32(kvStride),+ theta: theta,+ rotatedPairs: rotatedPairs,+ eps: 1e-6)+ cb.commit()+ cb.waitUntilCompleted()+ if let err = cb.error {+ Issue.record("command buffer failed: \(err)")+ return ([], [])+ }++ Self.expectClose(Fp16Buffer.read(qBlock, count: rows * qStride),+ Fp16Buffer.read(qRef, count: rows * qStride),+ label: "Q")+ Self.expectClose(Fp16Buffer.read(kBlock, count: rows * kvStride),+ Fp16Buffer.read(kRef, count: rows * kvStride),+ label: "K")+ Self.expectClose(Fp16Buffer.read(vBlock, count: rows * kvStride),+ Fp16Buffer.read(vRef, count: rows * kvStride),+ label: "V")+ Self.assertPaddingUnchanged(qBlock,+ original: q,+ rows: rows,+ rowStride: qStride,+ usedPerRow: qUsed)+ Self.assertPaddingUnchanged(kBlock,+ original: k,+ rows: rows,+ rowStride: kvStride,+ usedPerRow: kvUsed)+ Self.assertPaddingUnchanged(vBlock,+ original: v,+ rows: rows,+ rowStride: kvStride,+ usedPerRow: kvUsed)++ let kActual = Fp16Buffer.read(kBlock, count: rows * kvStride)+ let vActual = Fp16Buffer.read(vBlock, count: rows * kvStride)+ return (Self.usedRows(kActual, rows: rows, rowStride: kvStride, usedPerRow: kvUsed),+ Self.usedRows(vActual, rows: rows, rowStride: kvStride, usedPerRow: kvUsed))+ }++ private static func makeBlock(rows: Int,+ rowStride: Int,+ usedPerRow: Int,+ seed: UInt64,+ label: String) -> [Float16] {+ var rng = SeedTree(seed).key("prefill-qkv-\(label)")+ var values = [Float16](repeating: Float16(-9.0), count: rows * rowStride)+ for row in 0..<rows {+ for i in 0..<usedPerRow {+ values[row * rowStride + i] = Float16(rng.uniform(-1.0, 1.0))+ }+ }+ return values+ }++ private static func usedRows(_ values: [Float],+ rows: Int,+ rowStride: Int,+ usedPerRow: Int) -> [Float] {+ var out: [Float] = []+ out.reserveCapacity(rows * usedPerRow)+ for row in 0..<rows {+ out.append(contentsOf: values[(row * rowStride)..<(row * rowStride + usedPerRow)])+ }+ return out+ }++ private static func expectClose(_ actual: [Float],+ _ reference: [Float],+ label: String) {+ let rel = RelError.compute(actual: actual, reference: reference)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ #expect(rel < Tolerance.fp16Reduction, "\(label) rel=\(rel) maxAbs=\(maxAbs)")+ #expect(maxAbs <= 1e-3, "\(label) maxAbs=\(maxAbs) rel=\(rel)")+ }++ private static func assertPaddingUnchanged(_ buffer: MTLBuffer,+ original: [Float16],+ rows: Int,+ rowStride: Int,+ usedPerRow: Int) {+ let ptr = buffer.contents().bindMemory(to: Float16.self, capacity: rows * rowStride)+ for row in 0..<rows {+ for i in usedPerRow..<rowStride {+ #expect(ptr[row * rowStride + i] == original[row * rowStride + i],+ "padding changed at row=\(row) i=\(i)")+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoPETests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoPETests.swiftnew file mode 100644index 00000000..58d301c3--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoPETests.swift@@ -0,0 +1,155 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillRoPETests {+ private static func makeBlock(rows: Int,+ rowStride: Int,+ usedPerRow: Int,+ seed: UInt64,+ label: String) -> [Float16] {+ var rng = SeedTree(seed).key(label)+ var values = [Float16](repeating: Float16(-7.0), count: rows * rowStride)+ for row in 0..<rows {+ for i in 0..<usedPerRow {+ values[row * rowStride + i] = Float16(rng.uniform(-1.0, 1.0))+ }+ }+ return values+ }++ private static func assertPaddingUnchanged(_ buffer: MTLBuffer,+ original: [Float16],+ rows: Int,+ rowStride: Int,+ usedPerRow: Int) {+ let ptr = buffer.contents().bindMemory(to: Float16.self, capacity: rows * rowStride)+ for row in 0..<rows {+ for i in usedPerRow..<rowStride {+ #expect(ptr[row * rowStride + i] == original[row * rowStride + i],+ "padding changed at row=\(row) i=\(i)")+ }+ }+ }++ @Test func blockDefaultNeoxMatchesRepeatedScalarAbsolutePositions() throws {+ let rows = 5+ let heads = 8+ let headDim = 256+ let used = heads * headDim+ let rowStride = used + 37+ let startPosition = 1023+ let theta: Float = 10_000.0+ let input = Self.makeBlock(rows: rows,+ rowStride: rowStride,+ usedPerRow: used,+ seed: 0xA501,+ label: "prefill-rope-swa")++ let ctx = try MetalContext()+ let scalar = try RoPE(context: ctx)+ let block = try PrefillRoPE(context: ctx)+ guard let ref = Fp16Buffer.make(ctx.device, halves: input),+ let candidate = Fp16Buffer.make(ctx.device, halves: input) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ scalar.encodeDefaultNeox(commandBuffer: cb,+ data: ref,+ dataOffset: row * rowStride * MemoryLayout<Float16>.size,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ numTokens: 1,+ theta: theta)+ }+ block.encodeDefaultNeox(commandBuffer: cb,+ data: candidate,+ startPosition: UInt32(startPosition),+ queryCount: UInt32(rows),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ tokenStrideElements: UInt32(rowStride),+ theta: theta)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(ref, count: rows * rowStride)+ let actual = Fp16Buffer.read(candidate, count: rows * rowStride)+ let rel = RelError.compute(actual: actual, reference: reference)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ #expect(rel < Tolerance.fp16Reduction, "block SWA RoPE rel=\(rel) maxAbs=\(maxAbs)")+ #expect(maxAbs <= 1e-3, "block SWA RoPE maxAbs=\(maxAbs) rel=\(rel)")+ Self.assertPaddingUnchanged(candidate,+ original: input,+ rows: rows,+ rowStride: rowStride,+ usedPerRow: used)+ }++ @Test func blockProportionalNeoxMatchesRepeatedScalarAbsolutePositions() throws {+ let rows = 4+ let heads = 2+ let headDim = 512+ let rotatedPairs = 64+ let used = heads * headDim+ let rowStride = used + 19+ let startPosition = 4095+ let theta: Float = 1_000_000.0+ let input = Self.makeBlock(rows: rows,+ rowStride: rowStride,+ usedPerRow: used,+ seed: 0xA502,+ label: "prefill-rope-full")++ let ctx = try MetalContext()+ let scalar = try RoPE(context: ctx)+ let block = try PrefillRoPE(context: ctx)+ guard let ref = Fp16Buffer.make(ctx.device, halves: input),+ let candidate = Fp16Buffer.make(ctx.device, halves: input) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ scalar.encodeProportionalNeox(commandBuffer: cb,+ data: ref,+ dataOffset: row * rowStride * MemoryLayout<Float16>.size,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ rotatedPairs: UInt32(rotatedPairs),+ numTokens: 1,+ theta: theta)+ }+ block.encodeProportionalNeox(commandBuffer: cb,+ data: candidate,+ startPosition: UInt32(startPosition),+ queryCount: UInt32(rows),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ rotatedPairs: UInt32(rotatedPairs),+ tokenStrideElements: UInt32(rowStride),+ theta: theta)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(ref, count: rows * rowStride)+ let actual = Fp16Buffer.read(candidate, count: rows * rowStride)+ let rel = RelError.compute(actual: actual, reference: reference)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ #expect(rel < Tolerance.fp16Reduction, "block full RoPE rel=\(rel) maxAbs=\(maxAbs)")+ #expect(maxAbs <= 1e-3, "block full RoPE maxAbs=\(maxAbs) rel=\(rel)")+ Self.assertPaddingUnchanged(candidate,+ original: input,+ rows: rows,+ rowStride: rowStride,+ usedPerRow: used)+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoutedTileSchedulerTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoutedTileSchedulerTests.swiftnew file mode 100644index 00000000..71795100--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoutedTileSchedulerTests.swift@@ -0,0 +1,85 @@+import Testing+@testable import TurboFieldfare++@Suite struct PrefillRoutedTileSchedulerTests {+ @Test func halfCacheIssuesFirstTileWithoutPendingWork() {+ let decision = PrefillRoutedTileScheduler().decide(+ PrefillRoutedTileSchedulerInput(hasPendingTile: false,+ pendingAssignedSlots: [],+ avoidingSlotPlanAvailable: false))++ #expect(decision == .issueWithoutPending)+ }++ @Test func halfCachePrefetchesWhenAvoidingSlotPlanExists() {+ let decision = PrefillRoutedTileScheduler().decide(+ PrefillRoutedTileSchedulerInput(hasPendingTile: true,+ pendingAssignedSlots: [3, 7, 8],+ avoidingSlotPlanAvailable: true))++ #expect(decision == .prefetchNext(avoidingSlots: [3, 7, 8]))+ }++ @Test func halfCacheDrainsWhenPendingTileHasNoAssignedSlots() {+ let decision = PrefillRoutedTileScheduler().decide(+ PrefillRoutedTileSchedulerInput(hasPendingTile: true,+ pendingAssignedSlots: [],+ avoidingSlotPlanAvailable: true))++ #expect(decision == .drainBeforeIssue(reason: .pendingTileHasNoAssignedSlots))+ }++ @Test func halfCacheDrainsWhenAvoidingSlotPlanIsUnavailable() {+ let decision = PrefillRoutedTileScheduler().decide(+ PrefillRoutedTileSchedulerInput(hasPendingTile: true,+ pendingAssignedSlots: [1, 2],+ avoidingSlotPlanAvailable: false))++ #expect(decision == .drainBeforeIssue(reason: .avoidingSlotPlanUnavailable))+ }++ @Test func schedulerAllowsSecondLookaheadWhenDepthBudgetAllowsIt() {+ let scheduler = PrefillRoutedTileScheduler(+ config: PrefillRoutedTileSchedulerConfig(maxPendingDepth: 2, tileExperts: 4))++ let decision = scheduler.decide(PrefillRoutedTileSchedulerInput(+ hasPendingTile: true,+ pendingDepth: 2,+ pendingAssignedSlots: [1, 2, 3, 4, 5, 6, 7, 8],+ avoidingSlotPlanAvailable: true))++ #expect(decision == .prefetchNext(avoidingSlots: [1, 2, 3, 4, 5, 6, 7, 8]))+ }++ @Test func schedulerDrainsAtConfiguredPendingDepth() {+ let decision = PrefillRoutedTileScheduler(+ config: PrefillRoutedTileSchedulerConfig(maxPendingDepth: 2, tileExperts: 4)).decide(+ PrefillRoutedTileSchedulerInput(hasPendingTile: true,+ pendingDepth: 3,+ pendingAssignedSlots: [1, 2],+ avoidingSlotPlanAvailable: true))++ #expect(decision == .drainBeforeIssue(reason: .maxPendingDepthReached))+ }++ @Test func schedulerConfigValidatesSlotBudget() {+ let defaultConfig = PrefillRoutedTileSchedulerConfig()+ let depthTwoFourExperts = PrefillRoutedTileSchedulerConfig(maxPendingDepth: 2, tileExperts: 4)+ let depthTwoEightExperts = PrefillRoutedTileSchedulerConfig(maxPendingDepth: 2, tileExperts: 8)++ #expect(defaultConfig.fitsSlotBudget(slotCount: 16))+ #expect(depthTwoFourExperts.fitsSlotBudget(slotCount: 16))+ #expect(!depthTwoEightExperts.fitsSlotBudget(slotCount: 16))+ }++ @Test func halfCachePreservesPendingSlotAvoidanceOrder() {+ let pendingSlots = [9, 1, 9, 3]+ let decision = PrefillRoutedTileScheduler().decide(+ PrefillRoutedTileSchedulerInput(hasPendingTile: true,+ pendingAssignedSlots: pendingSlots,+ avoidingSlotPlanAvailable: true))++ #expect(decision == .prefetchNext(avoidingSlots: pendingSlots))+ }++}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRouterTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRouterTests.swiftnew file mode 100644index 00000000..720d315f--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRouterTests.swift@@ -0,0 +1,336 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillRouterTests {+ private static let experts = 16+ private static let d = 128+ private static let topK = 8++ @Test func tokenExpertPairLayoutIsStable() {+ #expect(MemoryLayout<PrefillTokenExpertPair>.size == 16)+ #expect(MemoryLayout<PrefillTokenExpertPair>.stride == 16)+ #expect(MemoryLayout.offset(of: \PrefillTokenExpertPair.token) == .some(0))+ #expect(MemoryLayout.offset(of: \PrefillTokenExpertPair.expert) == .some(4))+ #expect(MemoryLayout.offset(of: \PrefillTokenExpertPair.rank) == .some(8))+ #expect(MemoryLayout.offset(of: \PrefillTokenExpertPair.weightBitsAndReserved) == .some(12))+ }++ @Test func tokenExpertPairsAreTokenMajor() {+ let weights: [Float16] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6].map { Float16($0) }+ let pairs = PrefillRouter.makeTokenExpertPairs(indices: [3, 1, 2, 4, 0, 5],+ weights: weights,+ queryCount: 2,+ topK: 3)+ #expect(pairs.map(\.token) == [0, 0, 0, 1, 1, 1])+ #expect(pairs.map(\.rank) == [0, 1, 2, 0, 1, 2])+ #expect(pairs.map(\.expert) == [3, 1, 2, 4, 0, 5])+ #expect(pairs.map { Float($0.weight) } == weights.map { Float($0) })+ }++ @Test func blockGemma4RouterMatchesRepeatedScalarRows() throws {+ var rng = SplitMix64(seed: 0x9A7E_2026)+ let rows = 3+ let hiddenStride = Self.d + 13+ let weights = Self.makeStableWeights(rng: &rng)+ let hidden = Self.makeHiddenBlock(rows: rows,+ rowStride: hiddenStride,+ d: Self.d,+ rng: &rng,+ sentinel: Float16(-31.0))+ let effectiveScale = (0..<Self.d).map { _ in+ rng.uniform(0.5, 1.5) / Float(Self.d).squareRoot()+ }+ let perExpertScale = (0..<Self.experts).map { _ in rng.uniform(0.6, 1.4) }++ let ctx = try MetalContext()+ let moe = try MoE(context: ctx)+ let prefill = try PrefillRouter(context: ctx)+ let buffers = try Self.makeBuffers(ctx: ctx,+ weights: weights,+ hidden: hidden,+ effectiveScale: effectiveScale,+ perExpertScale: perExpertScale,+ rows: rows)++ var expectedIndices = [UInt32]()+ var expectedWeights = [Float16]()+ for row in 0..<rows {+ let compactHidden = Array(hidden[(row * hiddenStride)..<(row * hiddenStride + Self.d)])+ let (idx, wt) = try Self.runScalarRouter(ctx: ctx,+ moe: moe,+ buffers: buffers,+ hiddenRow: compactHidden)+ expectedIndices.append(contentsOf: idx)+ expectedWeights.append(contentsOf: wt)+ }++ guard let cb = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to make command buffer")+ return+ }+ prefill.encodeGemma4Block(commandBuffer: cb,+ weights: buffers.weights,+ scales: buffers.scales,+ biases: buffers.biases,+ hidden: buffers.hidden,+ effectiveScale: buffers.effectiveScale,+ perExpertScale: buffers.perExpertScale,+ outIndices: buffers.blockIndices,+ outWeights: buffers.blockWeights,+ queryCount: UInt32(rows),+ numExperts: UInt32(Self.experts),+ d: UInt32(Self.d),+ topK: UInt32(Self.topK),+ hiddenStrideElements: UInt32(hiddenStride))+ cb.commit()+ cb.waitUntilCompleted()+ #expect(cb.error == nil)++ let gotIndices = Self.readUInt32(buffers.blockIndices, count: rows * Self.topK)+ let gotWeights = Fp16Buffer.readHalf(buffers.blockWeights, count: rows * Self.topK)+ #expect(gotIndices == expectedIndices)+ Self.assertWeightsClose(gotWeights, expectedWeights, tolerance: 5e-3)+ Self.assertPaddingUnchanged(buffer: buffers.hidden,+ original: hidden,+ rows: rows,+ rowStride: hiddenStride,+ used: Self.d)+ }++ @Test func blockGemma4RouterNearTieMatchesScalarPath() throws {+ let weights = Self.makeNearTieWeights()+ let hidden = [Float16](repeating: 1, count: Self.d)+ let effectiveScale = [Float](repeating: 1, count: Self.d)+ let perExpertScale = [Float](repeating: 1, count: Self.experts)+ let ctx = try MetalContext()+ let moe = try MoE(context: ctx)+ let prefill = try PrefillRouter(context: ctx)+ let buffers = try Self.makeBuffers(ctx: ctx,+ weights: weights,+ hidden: hidden,+ effectiveScale: effectiveScale,+ perExpertScale: perExpertScale,+ rows: 1)+ let (scalar, _) = try Self.runScalarRouter(ctx: ctx,+ moe: moe,+ buffers: buffers,+ hiddenRow: hidden)++ guard let cb = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to make command buffer")+ return+ }+ prefill.encodeGemma4Block(commandBuffer: cb,+ weights: buffers.weights,+ scales: buffers.scales,+ biases: buffers.biases,+ hidden: buffers.hidden,+ effectiveScale: buffers.effectiveScale,+ perExpertScale: buffers.perExpertScale,+ outIndices: buffers.blockIndices,+ outWeights: buffers.blockWeights,+ queryCount: 1,+ numExperts: UInt32(Self.experts),+ d: UInt32(Self.d),+ topK: UInt32(Self.topK),+ hiddenStrideElements: UInt32(Self.d))+ cb.commit()+ cb.waitUntilCompleted()+ #expect(cb.error == nil)++ let block = Self.readUInt32(buffers.blockIndices, count: Self.topK)+ #expect(block == scalar)+ }++ private struct RouterBuffers {+ let weights: MTLBuffer+ let scales: MTLBuffer+ let biases: MTLBuffer+ let hidden: MTLBuffer+ let effectiveScale: MTLBuffer+ let perExpertScale: MTLBuffer+ let blockIndices: MTLBuffer+ let blockWeights: MTLBuffer+ }++ private static func makeBuffers(ctx: MetalContext,+ weights: [[Float]],+ hidden: [Float16],+ effectiveScale: [Float],+ perExpertScale: [Float],+ rows: Int) throws -> RouterBuffers {+ let packed = packWeights(weights)+ let effBits = effectiveScale.map { Quantization.bf16Bits($0) }+ let pesBits = perExpertScale.map { Quantization.bf16Bits($0) }+ guard let wBuf = ctx.device.makeBuffer(bytes: packed.packed,+ length: packed.packed.count,+ options: .storageModeShared),+ let sBuf = ctx.device.makeBuffer(bytes: packed.scales,+ length: packed.scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let bBuf = ctx.device.makeBuffer(bytes: packed.biases,+ length: packed.biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let hBuf = ctx.device.makeBuffer(bytes: hidden,+ length: hidden.count * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let eBuf = ctx.device.makeBuffer(bytes: effBits,+ length: effBits.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let pBuf = ctx.device.makeBuffer(bytes: pesBits,+ length: pesBits.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let idxBuf = ctx.device.makeBuffer(length: rows * Self.topK * MemoryLayout<UInt32>.size,+ options: .storageModeShared),+ let wtBuf = ctx.device.makeBuffer(length: rows * Self.topK * MemoryLayout<Float16>.size,+ options: .storageModeShared) else {+ throw RouterTestError.allocationFailed+ }+ return RouterBuffers(weights: wBuf,+ scales: sBuf,+ biases: bBuf,+ hidden: hBuf,+ effectiveScale: eBuf,+ perExpertScale: pBuf,+ blockIndices: idxBuf,+ blockWeights: wtBuf)+ }++ private static func runScalarRouter(ctx: MetalContext,+ moe: MoE,+ buffers: RouterBuffers,+ hiddenRow: [Float16]) throws -> ([UInt32], [Float16]) {+ guard let hBuf = ctx.device.makeBuffer(bytes: hiddenRow,+ length: hiddenRow.count * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let idxBuf = ctx.device.makeBuffer(length: Self.topK * MemoryLayout<UInt32>.size,+ options: .storageModeShared),+ let wtBuf = ctx.device.makeBuffer(length: Self.topK * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let cb = ctx.queue.makeCommandBuffer() else {+ throw RouterTestError.allocationFailed+ }+ moe.encodeRouterGemma4(commandBuffer: cb,+ weights: buffers.weights,+ scales: buffers.scales,+ biases: buffers.biases,+ hidden: hBuf,+ effectiveScale: buffers.effectiveScale,+ perExpertScale: buffers.perExpertScale,+ outIndices: idxBuf,+ outWeights: wtBuf,+ numExperts: UInt32(Self.experts),+ d: UInt32(Self.d),+ topK: UInt32(Self.topK))+ cb.commit()+ cb.waitUntilCompleted()+ if let error = cb.error {+ throw error+ }+ return (readUInt32(idxBuf, count: Self.topK),+ Fp16Buffer.readHalf(wtBuf, count: Self.topK))+ }++ private static func makeStableWeights(rng: inout SplitMix64) -> [[Float]] {+ (0..<Self.experts).map { expert in+ let bias = Float(expert) * 0.015+ return (0..<Self.d).map { _ in rng.uniform(-0.04, 0.04) + bias }+ }+ }++ private static func makeNearTieWeights() -> [[Float]] {+ var weights = [[Float]](repeating: [Float](repeating: 0, count: Self.d),+ count: Self.experts)+ for expert in 0..<Self.experts {+ let gain: Float+ if expert < 7 {+ gain = 1.0 - Float(expert) * 0.05+ } else if expert == 7 {+ gain = 0.50+ } else if expert == 8 {+ gain = 0.50 * (1.0 + 1e-4)+ } else {+ gain = 0.40 - Float(expert - 9) * 0.02+ }+ for k in 0..<Self.d {+ let pattern = 0.25 + Float((k * 37 + 11) % 97) / 97.0+ weights[expert][k] = pattern * gain+ }+ }+ return weights+ }++ private static func makeHiddenBlock(rows: Int,+ rowStride: Int,+ d: Int,+ rng: inout SplitMix64,+ sentinel: Float16) -> [Float16] {+ var values = [Float16](repeating: sentinel, count: rows * rowStride)+ for row in 0..<rows {+ for i in 0..<d {+ values[row * rowStride + i] = Float16(rng.uniform(-1.0, 1.0))+ }+ }+ return values+ }++ private static func packWeights(_ weights: [[Float]])+ -> (packed: [UInt8], scales: [UInt16], biases: [UInt16])+ {+ let eCount = weights.count+ let d = weights[0].count+ let groupsPerRow = d / Quantization.groupSize+ var packed = [UInt8](repeating: 0, count: eCount * d)+ var scales = [UInt16](repeating: 0, count: eCount * groupsPerRow)+ var biases = [UInt16](repeating: 0, count: eCount * groupsPerRow)+ for e in 0..<eCount {+ let q = Quantization.quantizeInt8Affine(weights[e])+ for i in 0..<d {+ packed[e * d + i] = q.packed[i]+ }+ for g in 0..<groupsPerRow {+ scales[e * groupsPerRow + g] = q.scales[g]+ biases[e * groupsPerRow + g] = q.biases[g]+ }+ }+ return (packed, scales, biases)+ }++ private static func readUInt32(_ buffer: MTLBuffer, count: Int) -> [UInt32] {+ (0..<count).map {+ buffer.contents().load(fromByteOffset: $0 * MemoryLayout<UInt32>.size,+ as: UInt32.self)+ }+ }++ private static func assertWeightsClose(_ got: [Float16],+ _ expected: [Float16],+ tolerance: Float) {+ var maxAbs: Float = 0+ for i in got.indices {+ maxAbs = max(maxAbs, abs(Float(got[i]) - Float(expected[i])))+ }+ #expect(maxAbs <= tolerance, "route weight maxAbsDiff=\(maxAbs)")+ }++ private static func assertPaddingUnchanged(buffer: MTLBuffer,+ original: [Float16],+ rows: Int,+ rowStride: Int,+ used: Int) {+ let got = Fp16Buffer.readHalf(buffer, count: original.count)+ for row in 0..<rows {+ for i in used..<rowStride {+ let idx = row * rowStride + i+ #expect(got[idx] == original[idx], "padding changed at row \(row) element \(i)")+ }+ }+ }++ private enum RouterTestError: Error {+ case allocationFailed+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillSharedExpertTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillSharedExpertTests.swiftnew file mode 100644index 00000000..1461018f--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillSharedExpertTests.swift@@ -0,0 +1,301 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct PrefillSharedExpertTests {+ private static let rows = 4+ private static let d = 128+ private static let f = 64+ private static let xStride = 144+ private static let yStride = 137+ private static let sentinel = Float16(-7.25)++ @Test func blockSharedExpertMatchesRepeatedScalarRows() throws {+ try Self.runBlockSharedExpertMatchesRepeatedScalarRows()+ }++ @Test func sharedExpertPhaseSplitMatchesCurrentPrefillBlock() throws {+ var rng = SeedTree(0xC0FFEE).key("prefill-shared-expert-phase-split")+ let ctx = try MetalContext()+ let shared = try SharedExpertInt8(context: ctx)+ let prefill = try PrefillSharedExpert(context: ctx)++ let x = Self.makeInputBlock(rng: &rng)+ let gate = Self.makeWeights(rows: Self.f, cols: Self.d, rng: &rng)+ let up = Self.makeWeights(rows: Self.f, cols: Self.d, rng: &rng)+ let down = Self.makeWeights(rows: Self.d, cols: Self.f, rng: &rng)+ let yElements = Self.rows * Self.d++ guard let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let yRef = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),+ let ySplit = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),+ let scratchAct = Fp16Buffer.make(ctx.device, count: Self.rows * Self.f) else {+ Issue.record("buffer allocation failed")+ return+ }++ let gateProj = Self.makeProjection(ctx: ctx, packed: gate, rows: Self.f, cols: Self.d)+ let upProj = Self.makeProjection(ctx: ctx, packed: up, rows: Self.f, cols: Self.d)+ let downProj = Self.makeProjection(ctx: ctx, packed: down, rows: Self.d, cols: Self.f)+ let halfBytes = MemoryLayout<Float16>.stride++ let refCB = ctx.queue.makeCommandBuffer()!+ try prefill.encodeBlock(commandBuffer: refCB,+ x: xBuf,+ y: yRef,+ gate: gateProj,+ up: upProj,+ down: downProj,+ scratchAct: scratchAct,+ queryCount: Self.rows,+ d: Self.d,+ intermediate: Self.f,+ xStrideElements: Self.xStride,+ yStrideElements: Self.d)+ refCB.commit()+ refCB.waitUntilCompleted()+ #expect(refCB.error == nil)++ let splitCB = ctx.queue.makeCommandBuffer()!+ for row in 0..<Self.rows {+ try shared.encodePhase1(commandBuffer: splitCB,+ x: xBuf,+ xOffset: row * Self.xStride * halfBytes,+ gate: gateProj,+ up: upProj,+ scratchAct: scratchAct,+ scratchActOffset: row * Self.f * halfBytes)+ }+ for row in 0..<Self.rows {+ try shared.encodeDown(commandBuffer: splitCB,+ down: downProj,+ y: ySplit,+ yOffset: row * Self.d * halfBytes,+ scratchAct: scratchAct,+ scratchActOffset: row * Self.f * halfBytes)+ }+ splitCB.commit()+ splitCB.waitUntilCompleted()+ #expect(splitCB.error == nil)++ let ref = Fp16Buffer.readHalf(yRef, count: yElements)+ let got = Fp16Buffer.readHalf(ySplit, count: yElements)+ #expect(got == ref)+ }++ @Test func blockSharedExpertThenPostF1NormMatchesRepeatedScalarRows() throws {+ var rng = SeedTree(0xC0FFEE).key("prefill-shared-expert-postf1")+ let ctx = try MetalContext()+ let scalar = try SharedExpertInt8(context: ctx)+ let scalarRMS = try RMSNorm(context: ctx)+ let prefill = try PrefillSharedExpert(context: ctx)+ let prefillRMS = try PrefillRMSNorm(context: ctx)++ let x = Self.makeInputBlock(rng: &rng)+ let gate = Self.makeWeights(rows: Self.f, cols: Self.d, rng: &rng)+ let up = Self.makeWeights(rows: Self.f, cols: Self.d, rng: &rng)+ let down = Self.makeWeights(rows: Self.d, cols: Self.f, rng: &rng)+ let postF1 = Self.makeBF16Weights(rng: &rng)+ let yElements = Self.rows * Self.d++ guard let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let yRef = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),+ let yGot = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),+ let scratchAct = Fp16Buffer.make(ctx.device, count: Self.f),+ let postF1Buf = ctx.device.makeBuffer(bytes: postF1,+ length: postF1.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared) else {+ Issue.record("buffer allocation failed")+ return+ }++ let gateProj = Self.makeProjection(ctx: ctx, packed: gate, rows: Self.f, cols: Self.d)+ let upProj = Self.makeProjection(ctx: ctx, packed: up, rows: Self.f, cols: Self.d)+ let downProj = Self.makeProjection(ctx: ctx, packed: down, rows: Self.d, cols: Self.f)++ let halfBytes = MemoryLayout<Float16>.stride+ let refCB = ctx.queue.makeCommandBuffer()!+ for row in 0..<Self.rows {+ try scalar.encode(commandBuffer: refCB,+ x: xBuf,+ xOffset: row * Self.xStride * halfBytes,+ gate: gateProj,+ up: upProj,+ down: downProj,+ y: yRef,+ yOffset: row * Self.d * halfBytes,+ scratchAct: scratchAct)+ scalarRMS.encodeBF16W(commandBuffer: refCB,+ x: yRef,+ xOffset: row * Self.d * halfBytes,+ weight: postF1Buf,+ out: yRef,+ outOffset: row * Self.d * halfBytes,+ d: UInt32(Self.d),+ eps: 1e-6)+ }+ refCB.commit()+ refCB.waitUntilCompleted()+ #expect(refCB.error == nil)++ let gotCB = ctx.queue.makeCommandBuffer()!+ try prefill.encodeBlock(commandBuffer: gotCB,+ x: xBuf,+ y: yGot,+ gate: gateProj,+ up: upProj,+ down: downProj,+ scratchAct: scratchAct,+ queryCount: Self.rows,+ d: Self.d,+ intermediate: Self.f,+ xStrideElements: Self.xStride,+ yStrideElements: Self.d)+ prefillRMS.encodeBF16W(commandBuffer: gotCB,+ x: yGot,+ weight: postF1Buf,+ out: yGot,+ t: UInt32(Self.rows),+ d: UInt32(Self.d),+ eps: 1e-6)+ gotCB.commit()+ gotCB.waitUntilCompleted()+ #expect(gotCB.error == nil)++ let ref = Fp16Buffer.readHalf(yRef, count: yElements)+ let got = Fp16Buffer.readHalf(yGot, count: yElements)+ #expect(got == ref)+ }++ private static func runBlockSharedExpertMatchesRepeatedScalarRows() throws {+ var rng = SeedTree(0xC0FFEE).key("prefill-shared-expert")+ let ctx = try MetalContext()+ let scalar = try SharedExpertInt8(context: ctx)+ let prefill = try PrefillSharedExpert(context: ctx)++ let x = makeInputBlock(rng: &rng)+ let gate = makeWeights(rows: f, cols: d, rng: &rng)+ let up = makeWeights(rows: f, cols: d, rng: &rng)+ let down = makeWeights(rows: d, cols: f, rng: &rng)++ guard let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let yRef = Fp16Buffer.make(ctx.device, halves: Array(repeating: sentinel, count: rows * yStride)),+ let yGot = Fp16Buffer.make(ctx.device, halves: Array(repeating: sentinel, count: rows * yStride)),+ let scratchAct = Fp16Buffer.make(ctx.device, count: f) else {+ Issue.record("buffer allocation failed")+ return+ }++ let gateProj = makeProjection(ctx: ctx, packed: gate, rows: f, cols: d)+ let upProj = makeProjection(ctx: ctx, packed: up, rows: f, cols: d)+ let downProj = makeProjection(ctx: ctx, packed: down, rows: d, cols: f)++ let halfBytes = MemoryLayout<Float16>.stride+ let refCB = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ try scalar.encode(commandBuffer: refCB,+ x: xBuf,+ xOffset: row * xStride * halfBytes,+ gate: gateProj,+ up: upProj,+ down: downProj,+ y: yRef,+ yOffset: row * yStride * halfBytes,+ scratchAct: scratchAct)+ }+ refCB.commit()+ refCB.waitUntilCompleted()+ #expect(refCB.error == nil)++ let gotCB = ctx.queue.makeCommandBuffer()!+ try prefill.encodeBlock(commandBuffer: gotCB,+ x: xBuf,+ y: yGot,+ gate: gateProj,+ up: upProj,+ down: downProj,+ scratchAct: scratchAct,+ queryCount: rows,+ d: d,+ intermediate: f,+ xStrideElements: xStride,+ yStrideElements: yStride)+ gotCB.commit()+ gotCB.waitUntilCompleted()+ #expect(gotCB.error == nil)++ let ref = Fp16Buffer.readHalf(yRef, count: rows * yStride)+ let got = Fp16Buffer.readHalf(yGot, count: rows * yStride)+ #expect(got == ref)+ assertPaddingUnchanged(got)+ }++ private static func makeInputBlock(rng: inout SplitMix64) -> [Float16] {+ var block = Array(repeating: sentinel, count: rows * xStride)+ for row in 0..<rows {+ for col in 0..<d {+ block[row * xStride + col] = Float16(rng.uniform(-0.35, 0.35))+ }+ }+ return block+ }++ private static func makeWeights(rows: Int,+ cols: Int,+ rng: inout SplitMix64)+ -> (packed: [UInt8], scales: [UInt16], biases: [UInt16])+ {+ let groupsPerRow = cols / Quantization.groupSize+ var packed = [UInt8](repeating: 0, count: rows * cols)+ var scales = [UInt16](repeating: 0, count: rows * groupsPerRow)+ var biases = [UInt16](repeating: 0, count: rows * groupsPerRow)+ for row in 0..<rows {+ let values = (0..<cols).map { _ in rng.uniform(-0.4, 0.4) }+ let q = Quantization.quantizeInt8Affine(values)+ for col in 0..<cols {+ packed[row * cols + col] = q.packed[col]+ }+ for group in 0..<groupsPerRow {+ scales[row * groupsPerRow + group] = q.scales[group]+ biases[row * groupsPerRow + group] = q.biases[group]+ }+ }+ return (packed, scales, biases)+ }++ private static func makeBF16Weights(rng: inout SplitMix64) -> [UInt16] {+ (0..<d).map { _ in Quantization.bf16Bits(rng.uniform(0.75, 1.25)) }+ }++ private static func makeProjection(+ ctx: MetalContext,+ packed: (packed: [UInt8], scales: [UInt16], biases: [UInt16]),+ rows: Int,+ cols: Int+ ) -> SharedExpertInt8Proj {+ let w = ctx.device.makeBuffer(bytes: packed.packed,+ length: packed.packed.count,+ options: .storageModeShared)!+ let s = ctx.device.makeBuffer(bytes: packed.scales,+ length: packed.scales.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared)!+ let b = ctx.device.makeBuffer(bytes: packed.biases,+ length: packed.biases.count * MemoryLayout<UInt16>.stride,+ options: .storageModeShared)!+ return SharedExpertInt8Proj(weights: w,+ scales: s,+ biases: b,+ rows: UInt32(rows),+ cols: UInt32(cols))+ }++ private static func assertPaddingUnchanged(_ values: [Float16]) {+ for row in 0..<rows {+ for col in d..<yStride {+ #expect(values[row * yStride + col] == sentinel)+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Primitives/RMSNormTests.swift b/Tests/TurboFieldfare/Core/Kernels/Primitives/RMSNormTests.swiftnew file mode 100644index 00000000..7ad0e45a--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Primitives/RMSNormTests.swift@@ -0,0 +1,270 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Compares the Metal `rmsnorm` kernel against the Accelerate-based+/// `RmsNormRef`. The reference uses `vDSP_svesq` + `vDSP_vmul` + `vDSP_vsmul`+/// (Accelerate's pipeline). The kernel uses per-thread block reduction with+/// `simd_sum`. Different summation tree, different rounding chain — bugs in+/// either are unlikely to match the other.+///+/// The reference is itself unit-tested in `RMSNormReferenceTests`.+@Suite struct RMSNormTests {++ private static let eps: Float = 1e-6++ // Every Gemma 4 norm weight is BF16. The reference is+ // `RmsNormRef.apply` over weights that have been round-tripped through+ // BF16 (matching what the kernel reads from device memory).++ private static func runAndCompareBF16W(d: Int, seed: UInt64) throws {+ var rng = SeedTree(seed).key("rmsnorm-bf16w-d\(d)")+ let xFp32 = (0..<d).map { _ in rng.uniform(-1.0, 1.0) }+ let wFp32 = (0..<d).map { _ in rng.uniform(0.5, 1.5) }++ let xFp16 = xFp32.map { Float16($0) }+ let xRef = xFp16.map { Float($0) }+ let wBits = wFp32.map { Quantization.bf16Bits($0) }+ let wRef = wBits.map { Quantization.bf16ToFloat($0) }++ let ctx = try MetalContext()+ let kernel = try RMSNorm(context: ctx)++ guard let xBuf = Fp16Buffer.make(ctx.device, halves: xFp16),+ let yBuf = Fp16Buffer.make(ctx.device, count: d),+ let wBuf = ctx.device.makeBuffer(length: wBits.count * 2,+ options: .storageModeShared) else {+ Issue.record("alloc failed"); return+ }+ let wPtr = wBuf.contents().bindMemory(to: UInt16.self, capacity: wBits.count)+ for i in 0..<wBits.count { wPtr[i] = wBits[i] }++ let cb = ctx.queue.makeCommandBuffer()!+ kernel.encodeBF16W(commandBuffer: cb, x: xBuf, weight: wBuf, out: yBuf,+ d: UInt32(d), eps: eps)+ cb.commit(); cb.waitUntilCompleted()++ let ref = RmsNormRef.apply(x: xRef, weight: wRef, eps: eps)+ let actual = Fp16Buffer.read(yBuf, count: d)+ let relErr = RelError.compute(actual: actual, reference: ref)+ let maxAbs = RelError.maxAbsDiff(actual, ref)+ #expect(relErr < Tolerance.fp16Reduction,+ "BF16W D=\(d): relErr=\(relErr) maxAbsDiff=\(maxAbs)")+ }++ @Test func rmsNorm_bf16w_d256() throws {+ try Self.runAndCompareBF16W(d: 256, seed: 0xC3)+ }+ @Test func rmsNorm_bf16w_d2816() throws {+ try Self.runAndCompareBF16W(d: 2816, seed: 0xD4)+ }++ // MARK: - No-scale variant+ //+ // v_norm and the MoE router's internal norm omit the learnable weight:+ // y[i] = x[i] * rsqrt(mean(x^2) + eps). Reference is `RmsNormRef.apply`+ // with a unit weight buffer.++ private static func runAndCompareNoScale(d: Int, seed: UInt64) throws {+ var rng = SeedTree(seed).key("rmsnorm-noscale-d\(d)")+ let xFp32 = (0..<d).map { _ in rng.uniform(-1.0, 1.0) }+ let xFp16 = xFp32.map { Float16($0) }+ let xRef = xFp16.map { Float($0) }+ let unitW = [Float](repeating: 1.0, count: d)++ let ctx = try MetalContext()+ let kernel = try RMSNorm(context: ctx)++ guard let xBuf = Fp16Buffer.make(ctx.device, halves: xFp16),+ let yBuf = Fp16Buffer.make(ctx.device, count: d) else {+ Issue.record("alloc failed"); return+ }+ let cb = ctx.queue.makeCommandBuffer()!+ kernel.encodeNoScale(commandBuffer: cb, x: xBuf, out: yBuf,+ d: UInt32(d), eps: eps)+ cb.commit(); cb.waitUntilCompleted()++ let ref = RmsNormRef.apply(x: xRef, weight: unitW, eps: eps)+ let actual = Fp16Buffer.read(yBuf, count: d)+ let relErr = RelError.compute(actual: actual, reference: ref)+ let maxAbs = RelError.maxAbsDiff(actual, ref)+ #expect(relErr < Tolerance.fp16Reduction,+ "no-scale D=\(d): relErr=\(relErr) maxAbsDiff=\(maxAbs)")+ }++ @Test func rmsNorm_noScale_d256() throws {+ try Self.runAndCompareNoScale(d: 256, seed: 0xE5)+ }+ @Test func rmsNorm_noScale_d2816() throws {+ try Self.runAndCompareNoScale(d: 2816, seed: 0xF6)+ }++ // MARK: - Per-head dispatch coverage+ //+ // `RealForwardRunner.produce` applies Q/K/V norms per head by looping+ // `for h in 0..<numHeads { rms.encodeBF16W(x, xOffset: h * headDim * 2,+ // ..., out, outOffset: h * headDim * 2, d: headDim, ...) }`. An+ // off-by-one in the offset multiplier (e.g. forgetting the FP16+ // size-of factor) would silently swap or overlap per-head data.+ //+ // This test fills a [numHeads, headDim] buffer with each head set to+ // the constant `Float16(h + 1)`. After per-head norm with unit BF16+ // weights, each head's RMS is `(h+1)`, so the kernel output is+ // `(h+1) / RMS = 1.0` everywhere within the head's range. Sign+ // preservation (sign-of-input matches sign-of-output) catches a swap+ // that smuggles wrong-head values into the wrong slice.++ @Test func rmsNorm_perHead_offsetsCoverEachHeadInIsolation() throws {+ let numHeads = 16+ let headDim = 256+ let total = numHeads * headDim++ // Per-head constant: head h is all (h+1). RMS of a constant c is |c|,+ // so y = c / |c| * unitW = sign(c). Pick c = h + 1 > 0 → y = 1.+ var x = [Float16](repeating: 0, count: total)+ for h in 0..<numHeads {+ let c = Float16(h + 1)+ for k in 0..<headDim {+ x[h * headDim + k] = c+ }+ }+ let wBits = [UInt16](repeating: Quantization.bf16Bits(1.0), count: headDim)++ let ctx = try MetalContext()+ let kernel = try RMSNorm(context: ctx)+ guard let xBuf = Fp16Buffer.make(ctx.device, halves: x),+ let wBuf = ctx.device.makeBuffer(length: wBits.count * 2,+ options: .storageModeShared) else {+ Issue.record("alloc failed"); return+ }+ let wPtr = wBuf.contents().bindMemory(to: UInt16.self, capacity: wBits.count)+ for i in 0..<wBits.count { wPtr[i] = wBits[i] }++ // Mirror the runner's per-head dispatch loop literally.+ let headBytes = headDim * MemoryLayout<Float16>.size+ let cb = ctx.queue.makeCommandBuffer()!+ for h in 0..<numHeads {+ kernel.encodeBF16W(commandBuffer: cb,+ x: xBuf, xOffset: h * headBytes,+ weight: wBuf, weightOffset: 0,+ out: xBuf, outOffset: h * headBytes,+ d: UInt32(headDim), eps: 1e-6)+ }+ cb.commit(); cb.waitUntilCompleted()++ let out = Fp16Buffer.read(xBuf, count: total)+ for h in 0..<numHeads {+ for k in 0..<headDim {+ let v = Float(out[h * headDim + k])+ #expect(abs(v - 1.0) < 1e-2,+ "head \(h) idx \(k): expected ~1.0, got \(v) — per-head offset bug?")+ }+ }+ }++ /// Mirror of the K/V branch using the no-scale variant dispatched for V.+ /// Each head's output should normalize to ±1.+ @Test func rmsNorm_noScale_perHead_offsetsCoverEachHeadInIsolation() throws {+ let numKVL = 8+ let headDim = 256+ let total = numKVL * headDim+ var x = [Float16](repeating: 0, count: total)+ for h in 0..<numKVL {+ let c = Float16(h + 1)+ for k in 0..<headDim { x[h * headDim + k] = c }+ }++ let ctx = try MetalContext()+ let kernel = try RMSNorm(context: ctx)+ guard let xBuf = Fp16Buffer.make(ctx.device, halves: x) else {+ Issue.record("alloc failed"); return+ }++ let headBytes = headDim * MemoryLayout<Float16>.size+ let cb = ctx.queue.makeCommandBuffer()!+ for h in 0..<numKVL {+ kernel.encodeNoScale(commandBuffer: cb,+ x: xBuf, xOffset: h * headBytes,+ out: xBuf, outOffset: h * headBytes,+ d: UInt32(headDim), eps: 1e-6)+ }+ cb.commit(); cb.waitUntilCompleted()++ let out = Fp16Buffer.read(xBuf, count: total)+ for h in 0..<numKVL {+ for k in 0..<headDim {+ let v = Float(out[h * headDim + k])+ #expect(abs(v - 1.0) < 1e-2,+ "no-scale head \(h) idx \(k): \(v) — per-head offset bug?")+ }+ }+ }++ // MARK: - Batched per-head+ //+ // The coalesced `encodeBF16WPerHead` / `encodeNoScalePerHead` must produce+ // bytewise-equal output to the per-head loop they replace — same+ // rms_block_inv per head, just all heads in one dispatch. Random per-head+ // data so a cross-head bleed (wrong head offset in the grid) is caught.++ @Test func rmsNorm_bf16wPerHead_matchesLoop() throws {+ let numHeads = 16, headDim = 256, total = numHeads * headDim+ var rng = SeedTree(0x2B1).key("rmsnorm-perhead-bf16w")+ let x = (0..<total).map { _ in Float16(rng.uniform(-1.0, 1.0)) }+ let wBits = (0..<headDim).map { _ in Quantization.bf16Bits(rng.uniform(0.5, 1.5)) }++ let ctx = try MetalContext()+ let kernel = try RMSNorm(context: ctx)+ guard let wBuf = ctx.device.makeBuffer(length: headDim * 2, options: .storageModeShared),+ let loopOut = Fp16Buffer.make(ctx.device, halves: x),+ let batchOut = Fp16Buffer.make(ctx.device, halves: x) else {+ Issue.record("alloc failed"); return+ }+ let wPtr = wBuf.contents().bindMemory(to: UInt16.self, capacity: headDim)+ for i in 0..<headDim { wPtr[i] = wBits[i] }+ let headBytes = headDim * MemoryLayout<Float16>.size++ let cb = ctx.queue.makeCommandBuffer()!+ for h in 0..<numHeads {+ kernel.encodeBF16W(commandBuffer: cb, x: loopOut, xOffset: h * headBytes,+ weight: wBuf, out: loopOut, outOffset: h * headBytes,+ d: UInt32(headDim), eps: 1e-6)+ }+ kernel.encodeBF16WPerHead(commandBuffer: cb, x: batchOut, weight: wBuf, out: batchOut,+ headDim: UInt32(headDim), numHeads: numHeads, eps: 1e-6)+ cb.commit(); cb.waitUntilCompleted()++ let a = Fp16Buffer.read(loopOut, count: total)+ let b = Fp16Buffer.read(batchOut, count: total)+ #expect(a == b, "batched per-head BF16W must match the per-head loop bytewise")+ }++ @Test func rmsNorm_noScalePerHead_matchesLoop() throws {+ let numKVL = 8, headDim = 512, total = numKVL * headDim+ var rng = SeedTree(0x2C2).key("rmsnorm-perhead-noscale")+ let x = (0..<total).map { _ in Float16(rng.uniform(-1.0, 1.0)) }++ let ctx = try MetalContext()+ let kernel = try RMSNorm(context: ctx)+ guard let loopOut = Fp16Buffer.make(ctx.device, halves: x),+ let batchOut = Fp16Buffer.make(ctx.device, halves: x) else {+ Issue.record("alloc failed"); return+ }+ let headBytes = headDim * MemoryLayout<Float16>.size+ let cb = ctx.queue.makeCommandBuffer()!+ for h in 0..<numKVL {+ kernel.encodeNoScale(commandBuffer: cb, x: loopOut, xOffset: h * headBytes,+ out: loopOut, outOffset: h * headBytes,+ d: UInt32(headDim), eps: 1e-6)+ }+ kernel.encodeNoScalePerHead(commandBuffer: cb, x: batchOut, out: batchOut,+ headDim: UInt32(headDim), numHeads: numKVL, eps: 1e-6)+ cb.commit(); cb.waitUntilCompleted()++ let a = Fp16Buffer.read(loopOut, count: total)+ let b = Fp16Buffer.read(batchOut, count: total)+ #expect(a == b, "batched per-head no-scale must match the per-head loop bytewise")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Primitives/RoPETests.swift b/Tests/TurboFieldfare/Core/Kernels/Primitives/RoPETests.swiftnew file mode 100644index 00000000..e7311522--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Primitives/RoPETests.swift@@ -0,0 +1,110 @@+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct RoPETests {+ @Test func defaultNeoxMatchesSWAReference() throws {+ let tokens = 1+ let heads = 16+ let headDim = 256+ let position = 7+ let theta: Float = 10_000+ let count = tokens * heads * headDim+ let input = Self.randomInputs(count: count, seed: 0xF1, label: "rope-neox-default")+ let context = try MetalContext()+ let kernel = try RoPE(context: context)+ let buffer = try #require(Fp16Buffer.make(context.device, values: input))+ let commandBuffer = try #require(context.queue.makeCommandBuffer())++ kernel.encodeDefaultNeox(+ commandBuffer: commandBuffer,+ data: buffer,+ position: UInt32(position),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ numTokens: UInt32(tokens),+ theta: theta)+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()++ let actual = Fp16Buffer.read(buffer, count: count)+ let reference = RopeRef.applyNeox(+ input: input,+ numTokens: tokens,+ numHeads: heads,+ headDim: headDim,+ rotatedPairs: headDim / 2,+ position: position,+ theta: theta)+ let error = RelError.compute(actual: actual, reference: reference)+ #expect(error < Tolerance.fp16Reduction)+ }++ @Test func proportionalNeoxMatchesFullAttentionReference() throws {+ let tokens = 1+ let heads = 16+ let headDim = 512+ let rotatedPairs = 64+ let position = 11+ let theta: Float = 1_000_000+ let count = tokens * heads * headDim+ let input = Self.randomInputs(count: count, seed: 0xF3, label: "rope-neox-full")+ let context = try MetalContext()+ let kernel = try RoPE(context: context)+ let buffer = try #require(Fp16Buffer.make(context.device, values: input))+ let before = Array(UnsafeBufferPointer(+ start: buffer.contents().assumingMemoryBound(to: UInt8.self),+ count: count * MemoryLayout<Float16>.size))+ let commandBuffer = try #require(context.queue.makeCommandBuffer())++ kernel.encodeProportionalNeox(+ commandBuffer: commandBuffer,+ data: buffer,+ position: UInt32(position),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ rotatedPairs: UInt32(rotatedPairs),+ theta: theta)+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()++ let actual = Fp16Buffer.read(buffer, count: count)+ let reference = RopeRef.applyNeox(+ input: input,+ numTokens: tokens,+ numHeads: heads,+ headDim: headDim,+ rotatedPairs: rotatedPairs,+ position: position,+ theta: theta)+ let error = RelError.compute(actual: actual, reference: reference)+ #expect(error < Tolerance.fp16Reduction)++ let halfDim = headDim / 2+ let stride = MemoryLayout<Float16>.size+ let after = UnsafeBufferPointer(+ start: buffer.contents().assumingMemoryBound(to: UInt8.self),+ count: count * stride)+ for head in 0..<heads {+ let base = head * headDim * stride+ for index in rotatedPairs..<halfDim {+ let offset = base + index * stride+ #expect(after[offset] == before[offset])+ #expect(after[offset + 1] == before[offset + 1])+ }+ for index in (halfDim + rotatedPairs)..<headDim {+ let offset = base + index * stride+ #expect(after[offset] == before[offset])+ #expect(after[offset + 1] == before[offset + 1])+ }+ }+ }++ private static func randomInputs(count: Int,+ seed: UInt64,+ label: String) -> [Float] {+ var random = SeedTree(seed).key(label)+ return (0..<count).map { _ in random.uniform(-1, 1) }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Quant/DequantInt4GEMVTests.swift b/Tests/TurboFieldfare/Core/Kernels/Quant/DequantInt4GEMVTests.swiftnew file mode 100644index 00000000..85e87ef5--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Quant/DequantInt4GEMVTests.swift@@ -0,0 +1,129 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Compares the Metal `dequant_int4_gemv` kernel against `DequantInt4GemvRef`,+/// which bulk-dequantizes each row to FP32 and dots with `vDSP_dotpr`. The+/// kernel interleaves nibble unpack + per-group scale + bias + FMA inside one+/// inner loop per thread. Independent code shape, independent FP summation+/// order.+///+/// The reference is itself unit-tested in `DequantInt4GemvRefTests`.+@Suite struct DequantInt4GEMVTests {++ private static func packWeights(_ rows: [Quantization.Int4AffineRow])+ -> (packed: [UInt8], scales: [UInt16], biases: [UInt16])+ {+ let m = rows.count+ let n2 = rows[0].packed.count // N/2+ let s = rows[0].scales.count // N/groupSize+ var packed = [UInt8](repeating: 0, count: m * n2)+ var scales = [UInt16](repeating: 0, count: m * s)+ var biases = [UInt16](repeating: 0, count: m * s)+ for row in 0..<m {+ for i in 0..<n2 { packed[row * n2 + i] = rows[row].packed[i] }+ for i in 0..<s {+ scales[row * s + i] = rows[row].scales[i]+ biases[row * s + i] = rows[row].biases[i]+ }+ }+ return (packed, scales, biases)+ }++ /// `weightByteOffset` pads the packed-weight buffer by that many bytes and+ /// binds it at that offset, exercising the kernel at a live, non-zero base.+ /// A value of 2 reproduces the resident-layout case (BF16 scale/bias regions+ /// leave a 2-aligned-but-not-4-aligned weight offset) — the exact alignment+ /// the vectorized `ushort` load depends on and the offset-0 parity tests+ /// never touch (R2).+ private static func runAndCompare(m: Int, n: Int, seed: UInt64,+ weightByteOffset: Int = 0) throws {+ precondition(n % Quantization.groupSize == 0)+ // Keep the offset-zero fixtures stable when adding non-zero offset cases.+ let baseKey = "int4-gemv-kernel-m\(m)-n\(n)"+ let rngKey = weightByteOffset == 0 ? baseKey : "\(baseKey)-off\(weightByteOffset)"+ var rng = SeedTree(seed).key(rngKey)++ var rows: [Quantization.Int4AffineRow] = []+ rows.reserveCapacity(m)+ for _ in 0..<m {+ let raw = (0..<n).map { _ in rng.uniform(-0.5, 0.5) }+ rows.append(Quantization.quantizeInt4Affine(raw))+ }+ let (packed, scales, biases) = packWeights(rows)++ let xFp32 = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }+ let xFp16 = xFp32.map { Float16($0) }+ let xRef = xFp16.map { Float($0) }++ let ctx = try MetalContext()+ let kernel = try DequantInt4GEMV(context: ctx)++ // Copy the packed rows at +weightByteOffset inside a padded buffer so the+ // kernel reads them at a non-zero base, not the natural buffer start.+ var paddedPacked = [UInt8](repeating: 0, count: packed.count + weightByteOffset)+ for i in 0..<packed.count { paddedPacked[weightByteOffset + i] = packed[i] }++ guard let wBuf = ctx.device.makeBuffer(+ bytes: paddedPacked, length: paddedPacked.count, options: .storageModeShared),+ let sBuf = ctx.device.makeBuffer(+ bytes: scales, length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let bBuf = ctx.device.makeBuffer(+ bytes: biases, length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let xBuf = Fp16Buffer.make(ctx.device, halves: xFp16),+ let yBuf = Fp16Buffer.make(ctx.device, count: m) else {+ Issue.record("Failed to allocate buffers"); return+ }++ guard let cmd = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to make command buffer"); return+ }+ kernel.encode(commandBuffer: cmd,+ weights: wBuf, weightsOffset: weightByteOffset,+ scales: sBuf, biases: bBuf,+ x: xBuf, y: yBuf,+ m: UInt32(m), n: UInt32(n))+ cmd.commit()+ cmd.waitUntilCompleted()++ let ref = DequantInt4GemvRef.apply(weightRows: rows, x: xRef, n: n)+ let actual = Fp16Buffer.read(yBuf, count: m)++ let rel = RelError.compute(actual: actual, reference: ref)+ let maxAbs = RelError.maxAbsDiff(actual, ref)+ #expect(rel < Tolerance.fp16Reduction,+ "M=\(m) N=\(n): rel=\(rel) maxAbs=\(maxAbs)")+ }++ @Test func gemv_d128_n128() throws {+ try Self.runAndCompare(m: 128, n: 128, seed: 0xC1)+ }++ @Test func gemv_m1024_n2816() throws {+ try Self.runAndCompare(m: 1024, n: 2816, seed: 0xC2)+ }++ @Test func gemv_m64_n64() throws {+ try Self.runAndCompare(m: 64, n: 64, seed: 0xC3)+ }++ /// Binds the packed weights at a 2-aligned-but-NOT-4-aligned byte offset+ /// (+2), reproducing the resident layout where BF16 scale/bias regions leave+ /// the weight offset only 2-aligned. The vectorized kernel's `ushort` load+ /// must stay correct here; a `uint` load would be misaligned. N=2816 forces+ /// the vectorized loop rather than only the scalar tail.+ @Test func gemv_weightsAt2AlignedNot4AlignedOffset() throws {+ try Self.runAndCompare(m: 128, n: 2816, seed: 0xC4, weightByteOffset: 2)+ }++ @Test(arguments: [64, 65, 128, 129] as [Int],+ OffByMultiples.multiplesOfGroup.filter { $0 <= 512 })+ func gemv_sweep(m: Int, n: Int) throws {+ let seed: UInt64 = UInt64(m) &* 0x9E37 &+ UInt64(n)+ try Self.runAndCompare(m: m, n: n, seed: seed)+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Quant/DequantInt8GEMVTests.swift b/Tests/TurboFieldfare/Core/Kernels/Quant/DequantInt8GEMVTests.swiftnew file mode 100644index 00000000..78594668--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Quant/DequantInt8GEMVTests.swift@@ -0,0 +1,90 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Compares the Metal `dequant_int8_gemv` kernel against+/// `DequantInt8GemvRef`, which bulk-dequantizes each row to FP32 and dots+/// with `vDSP_dotpr`. Reference is unit-tested in `DequantInt8GemvRefTests`.+///+/// Covers:+/// * Router shape — M=128, N=2816+/// * lm_head sub-shape — M=1024, N=2816 (real lm_head is M=262144)+@Suite struct DequantInt8GEMVTests {++ private static func runAndCompare(m: Int, n: Int, seed: UInt64) throws -> Float {+ precondition(n % Quantization.groupSize == 0)+ let groupsPerRow = n / Quantization.groupSize+ var rng = SeedTree(seed).key("int8-gemv-m\(m)-n\(n)")++ var rows: [Quantization.Int8AffineRow] = []+ rows.reserveCapacity(m)+ for _ in 0..<m {+ let raw = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }+ rows.append(Quantization.quantizeInt8Affine(raw))+ }++ var packed = [UInt8](repeating: 0, count: m * n)+ var scales = [UInt16](repeating: 0, count: m * groupsPerRow)+ var biases = [UInt16](repeating: 0, count: m * groupsPerRow)+ for row in 0..<m {+ for i in 0..<n { packed[row * n + i] = rows[row].packed[i] }+ for g in 0..<groupsPerRow {+ scales[row * groupsPerRow + g] = rows[row].scales[g]+ biases[row * groupsPerRow + g] = rows[row].biases[g]+ }+ }++ let xFp32 = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }+ let xFp16 = xFp32.map { Float16($0) }+ let xRef = xFp16.map { Float($0) }++ let ctx = try MetalContext()+ let kernel = try DequantInt8GEMV(context: ctx)++ guard let wBuf = ctx.device.makeBuffer(+ bytes: packed, length: packed.count,+ options: .storageModeShared),+ let sBuf = ctx.device.makeBuffer(+ bytes: scales, length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let bBuf = ctx.device.makeBuffer(+ bytes: biases, length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let xBuf = Fp16Buffer.make(ctx.device, halves: xFp16),+ let yBuf = Fp16Buffer.make(ctx.device, count: m) else {+ Issue.record("Failed to allocate buffers"); return .infinity+ }+ guard let cmd = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to make command buffer"); return .infinity+ }+ kernel.encode(commandBuffer: cmd,+ weights: wBuf, scales: sBuf, biases: bBuf,+ x: xBuf, y: yBuf,+ m: UInt32(m), n: UInt32(n))+ cmd.commit()+ cmd.waitUntilCompleted()++ let ref = DequantInt8GemvRef.apply(weightRows: rows, x: xRef, n: n)+ let actual = Fp16Buffer.read(yBuf, count: m)+ return RelError.compute(actual: actual, reference: ref)+ }++ @Test func gemv_router_shape() throws {+ let rel = try Self.runAndCompare(m: 128, n: 2816, seed: 0x151)+ #expect(rel < Tolerance.fp16Reduction, "router rel=\(rel)")+ }++ @Test func gemv_lmHeadSubShape() throws {+ let rel = try Self.runAndCompare(m: 1024, n: 2816, seed: 0x152)+ #expect(rel < Tolerance.fp16Reduction, "lm_head sub-shape rel=\(rel)")+ }++ @Test(arguments: [128, 256, 1024] as [Int],+ OffByMultiples.multiplesOfGroup.filter { $0 <= 512 })+ func gemv_sweep(m: Int, n: Int) throws {+ let rel = try Self.runAndCompare(m: m, n: n, seed: UInt64(m * 1000 + n))+ #expect(rel < Tolerance.fp16Reduction, "M=\(m) N=\(n) rel=\(rel)")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Quant/EmbedLookupTests.swift b/Tests/TurboFieldfare/Core/Kernels/Quant/EmbedLookupTests.swiftnew file mode 100644index 00000000..e375797a--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Quant/EmbedLookupTests.swift@@ -0,0 +1,109 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Validates the tied 4-bit embedding lookup used by Gemma 4.+@Suite struct EmbedLookupTests {++ private struct Sizes {+ static let V = 16+ static let D = 128+ static let groupsPerRow = D / Quantization.groupSize+ }++ private static func buildTable4(seed: UInt64)+ -> (packed: [UInt8], scales: [UInt16], biases: [UInt16]) {+ var rng = SeedTree(seed).key("embed-lookup-int4-table")+ var rows: [[Float]] = []+ rows.reserveCapacity(Sizes.V)+ for _ in 0..<Sizes.V {+ rows.append((0..<Sizes.D).map { _ in rng.uniform(-1.0, 1.0) })+ }+ var packed = [UInt8]( repeating: 0, count: Sizes.V * (Sizes.D / 2))+ var scales = [UInt16](repeating: 0, count: Sizes.V * Sizes.groupsPerRow)+ var biases = [UInt16](repeating: 0, count: Sizes.V * Sizes.groupsPerRow)+ for v in 0..<Sizes.V {+ let q = Quantization.quantizeInt4Affine(rows[v])+ for i in 0..<(Sizes.D / 2) { packed[v * (Sizes.D / 2) + i] = q.packed[i] }+ for g in 0..<Sizes.groupsPerRow {+ scales[v * Sizes.groupsPerRow + g] = q.scales[g]+ biases[v * Sizes.groupsPerRow + g] = q.biases[g]+ }+ }+ return (packed, scales, biases)+ }++ @Test func embedLookupInt4_withSqrtDScale_matchesReference() throws {+ let (packed, scales, biases) = Self.buildTable4(seed: 0x131)+ let ctx = try MetalContext()+ let kernel = try EmbedLookupInt4(context: ctx)++ guard let tableBuf = ctx.device.makeBuffer(+ bytes: packed, length: packed.count,+ options: .storageModeShared),+ let scalesBuf = ctx.device.makeBuffer(+ bytes: scales, length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let biasesBuf = ctx.device.makeBuffer(+ bytes: biases, length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let outBuf = Fp16Buffer.make(ctx.device, count: Sizes.D) else {+ Issue.record("alloc failed"); return+ }+ let token: UInt32 = 9+ // sqrt(D) for the toy D=128 (5.65...). Mirrors the per-model sqrt(H)+ // scale; the kernel treats it as a runtime float.+ let outScale = Float(Sizes.D).squareRoot()++ let cb = ctx.queue.makeCommandBuffer()!+ kernel.encode(commandBuffer: cb,+ table: tableBuf, scales: scalesBuf, biases: biasesBuf,+ out: outBuf,+ tokenId: token, d: UInt32(Sizes.D),+ outScale: outScale)+ cb.commit(); cb.waitUntilCompleted()++ let ref = EmbedLookupRef.applyInt4(+ tablePacked: packed, tableScales: scales, tableBiases: biases,+ tokenId: Int(token), d: Sizes.D, outScale: outScale)+ let actual = Fp16Buffer.read(outBuf, count: Sizes.D)+ let rel = RelError.compute(actual: actual, reference: ref)+ #expect(rel < Tolerance.quantInt4, "rel=\(rel)")+ }++ /// outScale=1.0 must produce raw dequant (sanity for the disable path).+ @Test func embedLookupInt4_unitScale_matchesRawDequant() throws {+ let (packed, scales, biases) = Self.buildTable4(seed: 0x132)+ let ctx = try MetalContext()+ let kernel = try EmbedLookupInt4(context: ctx)++ guard let tableBuf = ctx.device.makeBuffer(+ bytes: packed, length: packed.count,+ options: .storageModeShared),+ let scalesBuf = ctx.device.makeBuffer(+ bytes: scales, length: scales.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let biasesBuf = ctx.device.makeBuffer(+ bytes: biases, length: biases.count * MemoryLayout<UInt16>.size,+ options: .storageModeShared),+ let outBuf = Fp16Buffer.make(ctx.device, count: Sizes.D) else {+ Issue.record("alloc failed"); return+ }+ let token: UInt32 = 2+ let cb = ctx.queue.makeCommandBuffer()!+ kernel.encode(commandBuffer: cb,+ table: tableBuf, scales: scalesBuf, biases: biasesBuf,+ out: outBuf,+ tokenId: token, d: UInt32(Sizes.D), outScale: 1.0)+ cb.commit(); cb.waitUntilCompleted()++ let ref = EmbedLookupRef.applyInt4(+ tablePacked: packed, tableScales: scales, tableBiases: biases,+ tokenId: Int(token), d: Sizes.D, outScale: 1.0)+ let actual = Fp16Buffer.read(outBuf, count: Sizes.D)+ let rel = RelError.compute(actual: actual, reference: ref)+ #expect(rel < Tolerance.quantInt4, "rel=\(rel)")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Sampling/LogitSoftcapSoftmaxTests.swift b/Tests/TurboFieldfare/Core/Kernels/Sampling/LogitSoftcapSoftmaxTests.swiftnew file mode 100644index 00000000..f04ba16a--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Sampling/LogitSoftcapSoftmaxTests.swift@@ -0,0 +1,87 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Compares the Metal `logit_softcap_softmax` kernel against+/// `LogitSoftcapSoftmaxRef`, an Accelerate-based two-pass reference (apply+/// softcap → find max → subtract → exp → divide by sum). The kernel does a+/// single-pass online safe softmax with the softcap fused into the (m, d)+/// running update. Different code paths through the same math.+@Suite struct LogitSoftcapSoftmaxTests {++ private static let softcap: Float = 30.0++ private static func runKernel(logitsFp16: [Float16], v: Int, softcap: Float) throws -> [Float] {+ let ctx = try MetalContext()+ let kernel = try LogitSoftcapSoftmax(context: ctx)++ guard let inBuf = Fp16Buffer.make(ctx.device, halves: logitsFp16),+ let outBuf = Fp16Buffer.make(ctx.device, count: v),+ let cmd = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to allocate Metal resources")+ return []+ }+ kernel.encode(commandBuffer: cmd,+ logits: inBuf, probs: outBuf,+ v: UInt32(v), softcap: softcap)+ cmd.commit()+ cmd.waitUntilCompleted()+ return Fp16Buffer.read(outBuf, count: v)+ }++ @Test func randomLogits_matchesReference() throws {+ let v = 2048+ var rng = SeedTree(0x131).key("softcap-softmax-random")+ let logitsFp32 = (0..<v).map { _ in rng.uniform(-50.0, 50.0) }+ let logitsFp16 = logitsFp32.map { Float16($0) }++ let gpu = try Self.runKernel(logitsFp16: logitsFp16, v: v, softcap: Self.softcap)+ let cpu = LogitSoftcapSoftmaxRef.apply(+ x: logitsFp16.map { Float($0) }, softcap: Self.softcap+ )++ // Probabilities at the extreme tail are near FP16 subnormal; use the+ // bounded-relative form so we don't blow up on c~0.+ let rel = RelError.boundedRel(actual: gpu, reference: cpu, absFloor: 1e-4)+ #expect(rel < Tolerance.fp16Reduction, "rel=\(rel)")++ // Probability axioms.+ let sum = gpu.reduce(0, +)+ #expect(abs(sum - 1.0) < Tolerance.fp16Reduction, "sum=\(sum)")+ }++ /// All logits identical → uniform 1/V distribution.+ @Test func uniformLogits_producesUniformProbs() throws {+ let v = 2048+ let logitsFp16 = [Float16](repeating: Float16(0.1234), count: v)++ let gpu = try Self.runKernel(logitsFp16: logitsFp16, v: v, softcap: Self.softcap)+ let expected: Float = 1.0 / Float(v)+ for i in 0..<v {+ #expect(abs(gpu[i] - expected) < 5e-4,+ "i=\(i) g=\(gpu[i]) expected=\(expected)")+ }+ }++ /// One logit far above the softcap, rest at zero. Softcap must pin the+ /// outlier — kernel must not let the un-capped 1000.0 leak through and+ /// overflow exp. Small softcap (5.0) so saturated prob is < 1.0.+ @Test func singleHugeLogit_isSoftcapped() throws {+ let v = 2048+ let smallSoftcap: Float = 5.0+ var logits = [Float](repeating: 0, count: v)+ logits[42] = 1000.0+ let logitsFp16 = logits.map { Float16($0) }++ let gpu = try Self.runKernel(logitsFp16: logitsFp16, v: v, softcap: smallSoftcap)+ let cpu = LogitSoftcapSoftmaxRef.apply(+ x: logitsFp16.map { Float($0) }, softcap: smallSoftcap+ )+ let g = gpu[42]+ let c = cpu[42]+ #expect(c < 0.5, "softcap reference should not saturate: c=\(c)")+ #expect(abs(g - c) / c < Tolerance.fp16Reduction, "g=\(g) c=\(c)")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTests.swift b/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTests.swiftnew file mode 100644index 00000000..f958571c--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTests.swift@@ -0,0 +1,150 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// `sample` kernel exercises. Inputs are pre-softmaxed FP16 probability+/// vectors (no upstream softmax needed) so the tests can hand-craft known+/// distributions and assert exact behaviour.+@Suite struct SampleTests {++ private static func makeProbs(_ values: [Float]) -> [Float16] {+ // Renormalize so the test inputs always sum to 1.0 exactly. The kernel+ // does not require a normalized input but the unit tests are clearer+ // when the inputs are actual probabilities.+ let sum = values.reduce(0, +)+ return values.map { Float16($0 / sum) }+ }++ private static func runSampler(probs: [Float16],+ temperature: Float,+ topK: UInt32,+ topP: Float,+ seed: UInt64) throws -> UInt32 {+ let ctx = try MetalContext()+ let kernel = try Sample(context: ctx)++ let v = probs.count+ guard let inBuf = ctx.device.makeBuffer(bytes: probs,+ length: v * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let outBuf = ctx.device.makeBuffer(length: MemoryLayout<UInt32>.size,+ options: .storageModeShared),+ let cmd = ctx.queue.makeCommandBuffer() else {+ Issue.record("Failed to allocate Metal resources")+ return UInt32.max+ }++ kernel.encode(commandBuffer: cmd,+ probs: inBuf, outToken: outBuf,+ v: UInt32(v),+ temperature: temperature,+ topK: topK, topP: topP, seed: seed)+ cmd.commit()+ cmd.waitUntilCompleted()++ return outBuf.contents().load(as: UInt32.self)+ }++ /// Temperature = 0 → argmax. We hand-place the max at a known index and+ /// expect that index back. Run at V=2048 to stress the cross-SIMD reduce.+ @Test func temperature_zero_picksArgmax() throws {+ let v = 2048+ var values = [Float](repeating: 0.01, count: v)+ values[1337] = 5.0 // clearly the argmax+ let probs = Self.makeProbs(values)++ let id = try Self.runSampler(probs: probs,+ temperature: 0.0,+ topK: 0, topP: 1.0,+ seed: 1)+ #expect(id == 1337, "got \(id)")+ }++ /// Identical seed must yield identical samples — the xorshift64 state is+ /// the only source of non-determinism in the stochastic path.+ @Test func seededRng_isDeterministic() throws {+ let v = 1024+ var rng = SeedTree(0x51A7_1003).key("sample-seeded-determinism")+ let values = (0..<v).map { _ in rng.uniform(0.0, 1.0) }+ let probs = Self.makeProbs(values)++ let seed: UInt64 = 0xDEADBEEFCAFEF00D+ let a = try Self.runSampler(probs: probs, temperature: 1.0,+ topK: 0, topP: 1.0, seed: seed)+ let b = try Self.runSampler(probs: probs, temperature: 1.0,+ topK: 0, topP: 1.0, seed: seed)+ #expect(a == b, "deterministic seed produced \(a) vs \(b)")++ // Different seed should (very probably) give a different draw on a+ // uniform-ish distribution. Allow equality once but expect divergence+ // across a small sweep.+ var sawDifferent = false+ for s: UInt64 in [42, 1337, 0xAABBCCDD, 0xFFFEDCBA] {+ let c = try Self.runSampler(probs: probs, temperature: 1.0,+ topK: 0, topP: 1.0, seed: s)+ if c != a { sawDifferent = true; break }+ }+ #expect(sawDifferent, "all seeds produced same id — RNG likely stuck")+ }++ /// Gumbel fast path (topK = 0, topP = 1): a spread distribution at high+ /// temperature must always return an in-range id at the CDF-underflow edge,+ /// and a sharply peaked one at low temperature must+ /// concentrate on the peak.+ @Test func gumbelFastPath_staysInRangeAndConcentrates() throws {+ let v = 4096+ var rng = SeedTree(0x51A7_1004).key("sample-gumbel-spread")+ let spread = Self.makeProbs((0..<v).map { _ in rng.uniform(0.5, 1.0) })+ for t in 0..<16 {+ let seed = (UInt64(t) &+ 1) &* 0x9E3779B97F4A7C15+ let id = try Self.runSampler(probs: spread, temperature: 2.0,+ topK: 0, topP: 1.0, seed: seed)+ #expect(id < UInt32(v), "trial \(t): out-of-range id \(id)")+ }++ var peaked = [Float](repeating: 0.0001, count: v)+ peaked[2049] = 0.9+ let probs = Self.makeProbs(peaked)+ var hits = 0+ for t in 0..<32 {+ let seed = (UInt64(t) &+ 1) &* 0x9E3779B97F4A7C15+ let id = try Self.runSampler(probs: probs, temperature: 0.3,+ topK: 0, topP: 1.0, seed: seed)+ if id == 2049 { hits += 1 }+ }+ // At T=0.3 the peak's re-sharpened mass is ~1 - 1e-9; any miss in 32+ // draws indicates a broken distribution, but allow one for FP slack.+ #expect(hits >= 31, "peak drawn \(hits)/32 times")+ }++ /// top_k = 4: the sampled token must be one of the top-4 indices, run+ /// across many trials. We hand-craft a distribution where the top-4 are+ /// well-separated from the rest.+ @Test func top_k_zerosOutMassOutsideTop() throws {+ let v = 1024+ var values = [Float](repeating: 0.0001, count: v)+ // Designated top-4 indices, with masses chosen so that even after+ // pow(p, 1/T) they dominate the long tail.+ let topIndices: [Int] = [10, 200, 500, 900]+ values[topIndices[0]] = 0.40+ values[topIndices[1]] = 0.30+ values[topIndices[2]] = 0.20+ values[topIndices[3]] = 0.10+ let probs = Self.makeProbs(values)+ let topSet = Set(topIndices.map { UInt32($0) })++ let trials = 32+ for t in 0..<trials {+ // Seed must be non-zero — xorshift64 has a fixed point at 0.+ let seed = (UInt64(t) &+ 1) &* 0x9E3779B97F4A7C15+ let id = try Self.runSampler(probs: probs,+ temperature: 1.0,+ topK: 4, topP: 1.0,+ seed: seed)+ #expect(topSet.contains(id),+ "trial \(t): id=\(id) not in top-4 \(topIndices)")+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTopK64Tests.swift b/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTopK64Tests.swiftnew file mode 100644index 00000000..619a4ed1--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTopK64Tests.swift@@ -0,0 +1,129 @@+import Metal+import Testing+@testable import TurboFieldfare++@Suite struct SampleTopK64Tests {+ @Test func truncationDefaultsDoNotDisableGreedyEligibility() {+ let config = GenerationConfig(temperature: 0, topK: 64, topP: 0.95)+ #expect(config.isPureGreedy)+ }++ @Test func generationConfigRejectsSamplerStatesTheKernelCannotHonor() throws {+ #expect(throws: GeneratorError.self) {+ try GenerationConfig(temperature: 1, topK: 257, topP: 0.95).validate()+ }+ #expect(throws: GeneratorError.self) {+ try GenerationConfig(temperature: 1, topK: nil, topP: 0.95).validate()+ }+ try GenerationConfig(temperature: 0, topK: nil, topP: 0.95).validate()+ }++ private final class Rig {+ let context: MetalContext+ let current: Sample+ let candidate: SampleTopK64+ let probs: MTLBuffer+ let currentOutput: MTLBuffer+ let candidateOutput: MTLBuffer+ let vocab: Int++ init(vocab: Int) throws {+ self.context = try MetalContext()+ self.current = try Sample(context: context)+ self.candidate = try SampleTopK64(context: context, vocab: vocab)+ self.vocab = vocab+ guard let probs = context.device.makeBuffer(+ length: vocab * MemoryLayout<Float16>.stride,+ options: .storageModeShared),+ let currentOutput = context.device.makeBuffer(+ length: MemoryLayout<UInt32>.stride,+ options: .storageModeShared),+ let candidateOutput = context.device.makeBuffer(+ length: MemoryLayout<UInt32>.stride,+ options: .storageModeShared)+ else {+ throw MetalError.noDevice+ }+ self.probs = probs+ self.currentOutput = currentOutput+ self.candidateOutput = candidateOutput+ }++ func write(_ values: (Int) -> Float) {+ let ptr = probs.contents().bindMemory(to: Float16.self, capacity: vocab)+ for i in 0..<vocab {+ ptr[i] = Float16(values(i))+ }+ }++ func draw(seed: UInt64,+ temperature: Float = 1.0,+ topP: Float) -> (current: UInt32, candidate: UInt32) {+ let cb = context.queue.makeCommandBuffer()!+ current.encode(commandBuffer: cb,+ probs: probs,+ outToken: currentOutput,+ v: UInt32(vocab),+ temperature: temperature,+ topK: 64,+ topP: topP,+ seed: seed)+ candidate.encode(commandBuffer: cb,+ probs: probs,+ outToken: candidateOutput,+ temperature: temperature,+ topP: topP,+ seed: seed)+ cb.commit()+ cb.waitUntilCompleted()+ return (currentOutput.contents().load(as: UInt32.self),+ candidateOutput.contents().load(as: UInt32.self))+ }+ }++ @Test func productionVocabularyMatchesCurrentSampler() throws {+ let rig = try Rig(vocab: 262_144)+ #expect(rig.candidate.scratchBytes == 139_264)+ rig.write { i in+ let mixed = UInt64(i) &* 6364136223846793005 &+ 1442695040888963407+ return Float(UInt32(mixed >> 40) + 1) * (1.0 / 16_777_217.0)+ }++ for temperature: Float in [0.7, 0.85, 1.0] {+ for seed: UInt64 in [1, 2, 0x1234_5678_9ABC_DEF0, UInt64.max] {+ let result = rig.draw(seed: seed, temperature: temperature, topP: 0.95)+ #expect(result.candidate == result.current,+ "temperature \(temperature), seed \(seed): candidate \(result.candidate), current \(result.current)")+ }+ }+ }++ @Test func tiesAndPartialTailMatchCurrentSampler() throws {+ let rig = try Rig(vocab: 1_003)+ rig.write { _ in 1.0 }++ for seed in UInt64(1)...UInt64(8) {+ let result = rig.draw(seed: seed, topP: 0.95)+ #expect(result.candidate == result.current,+ "seed \(seed): candidate \(result.candidate), current \(result.current)")+ #expect(result.candidate < 64)+ }+ }++ @Test func topPUsesFullVocabularyMassBeforeTopK() throws {+ let rig = try Rig(vocab: 1_003)+ rig.write { _ in 1.0 / 1_003.0 }++ // The full-distribution 0.95 nucleus is much wider than 64 tokens, so+ // mlx-lm's Top-P-then-Top-K chain leaves all Top-64 entries eligible.+ // The previous Top-K-renormalize-then-Top-P order kept only 61.+ var sawLastThree = false+ for seed in UInt64(1)...UInt64(256) {+ let result = rig.draw(seed: seed, topP: 0.95)+ #expect(result.candidate == result.current)+ #expect(result.candidate < 64)+ if result.candidate >= 61 { sawLastThree = true }+ }+ #expect(sawLastThree, "Top-P incorrectly truncated the renormalized Top-64 set")+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/TensorCore/MPPPrefillInt4QMMTests.swift b/Tests/TurboFieldfare/Core/Kernels/TensorCore/MPPPrefillInt4QMMTests.swiftnew file mode 100644index 00000000..cee4a514--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/TensorCore/MPPPrefillInt4QMMTests.swift@@ -0,0 +1,309 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct MPPPrefillInt4QMMTests {+ private struct Inputs {+ let packed: [UInt8]+ let scales: [UInt16]+ let biases: [UInt16]+ let x: [Float16]+ }++ private static func makeInputs(m: Int,+ n: Int,+ k: Int,+ adversarialAffine: Bool = false) -> Inputs {+ let groups = k / Quantization.groupSize+ var packed = [UInt8](repeating: 0, count: n * k / 2)+ for index in packed.indices {+ packed[index] = UInt8(truncatingIfNeeded: index &* 37 &+ 0x29)+ }+ var scales = [UInt16](repeating: 0, count: n * groups)+ var biases = [UInt16](repeating: 0, count: n * groups)+ let adversarialScales: [UInt16] = [+ Quantization.bf16Bits(0.001),+ Quantization.bf16Bits(-0.0015),+ 0x0001,+ 0x8001,+ ]+ let adversarialBiases: [UInt16] = [+ Quantization.bf16Bits(-0.01),+ Quantization.bf16Bits(0.006),+ 0x0001,+ 0x8001,+ ]+ for row in 0..<n {+ for group in 0..<groups {+ let index = row * groups + group+ if adversarialAffine {+ scales[index] = adversarialScales[(row + group) % adversarialScales.count]+ biases[index] = adversarialBiases[(row * 3 + group) % adversarialBiases.count]+ } else {+ scales[index] = Quantization.bf16Bits(+ 0.001 + Float((row + group) % 5) * 0.00025)+ biases[index] = Quantization.bf16Bits(+ -0.01 + Float((row * 3 + group) % 7) * 0.002)+ }+ }+ }+ var x = [Float16](repeating: 0, count: m * k)+ for index in x.indices {+ x[index] = Float16(Float((index * 11) % 29 - 14) / 64.0)+ }+ return Inputs(packed: packed, scales: scales, biases: biases, x: x)+ }++ private static func makeBuffer<T>(device: MTLDevice,+ values: [T],+ prefixBytes: Int = 0) -> MTLBuffer? {+ let byteCount = values.count * MemoryLayout<T>.stride+ guard let buffer = device.makeBuffer(length: prefixBytes + byteCount,+ options: .storageModeShared) else {+ return nil+ }+ values.withUnsafeBytes { bytes in+ guard let baseAddress = bytes.baseAddress else { return }+ buffer.contents().advanced(by: prefixBytes)+ .copyMemory(from: baseAddress, byteCount: byteCount)+ }+ return buffer+ }++ private static func cpuReference(_ inputs: Inputs,+ m: Int,+ n: Int,+ k: Int) -> [Float] {+ let groups = k / Quantization.groupSize+ let rowBytes = k / 2+ var output = [Float](repeating: 0, count: m * n)+ for token in 0..<m {+ for row in 0..<n {+ var accumulator: Float = 0+ for group in 0..<groups {+ let scale = Quantization.bf16ToFloat(inputs.scales[row * groups + group])+ let bias = Quantization.bf16ToFloat(inputs.biases[row * groups + group])+ for localK in 0..<Quantization.groupSize {+ let column = group * Quantization.groupSize + localK+ let byte = inputs.packed[row * rowBytes + column / 2]+ let q = column.isMultiple(of: 2) ? byte & 0x0f : byte >> 4+ let weight = Float(q) * scale + bias+ accumulator.addProduct(weight, Float(inputs.x[token * k + column]))+ }+ }+ output[token * n + row] = Float(Float16(accumulator))+ }+ }+ return output+ }++ @discardableResult+ private static func runShape(context: MetalContext,+ candidate: MPPPrefillInt4QMM,+ baseline: PrefillInt4QMM,+ m: Int,+ n: Int,+ k: Int,+ adversarialAffine: Bool = false,+ weightOffset: Int = 0,+ scaleOffset: Int = 0,+ biasOffset: Int = 0,+ compareCPUReference: Bool = false) throws+ -> MPPPrefillInt4QMM.Path {+ let inputs = makeInputs(m: m, n: n, k: k,+ adversarialAffine: adversarialAffine)+ guard let weights = makeBuffer(device: context.device,+ values: inputs.packed,+ prefixBytes: weightOffset),+ let scaleBuffer = makeBuffer(device: context.device,+ values: inputs.scales,+ prefixBytes: scaleOffset),+ let biasBuffer = makeBuffer(device: context.device,+ values: inputs.biases,+ prefixBytes: biasOffset),+ let input = Fp16Buffer.make(context.device, halves: inputs.x),+ let expectedBuffer = Fp16Buffer.make(context.device, count: m * n),+ let actualBuffer = Fp16Buffer.make(context.device, count: m * n),+ let commandBuffer = context.queue.makeCommandBuffer() else {+ Issue.record("buffer allocation failed")+ throw CocoaError(.fileReadUnknown)+ }++ baseline.encode(commandBuffer: commandBuffer,+ weights: weights,+ weightsOffset: weightOffset,+ scales: scaleBuffer,+ scalesOffset: scaleOffset,+ biases: biasBuffer,+ biasesOffset: biasOffset,+ x: input,+ y: expectedBuffer,+ t: m,+ n: n,+ k: k)+ let path = candidate.encode(commandBuffer: commandBuffer,+ weights: weights,+ weightsOffset: weightOffset,+ scales: scaleBuffer,+ scalesOffset: scaleOffset,+ biases: biasBuffer,+ biasesOffset: biasOffset,+ x: input,+ y: actualBuffer,+ m: m,+ n: n,+ k: k)+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ #expect(commandBuffer.error == nil)+ #expect(path == .affineThreadgroupF16)++ let baselineOutput = Fp16Buffer.read(expectedBuffer, count: m * n)+ let actual = Fp16Buffer.read(actualBuffer, count: m * n)+ let baselineMaxAbs = RelError.maxAbsDiff(actual, baselineOutput)+ let baselineRelative = RelError.compute(actual: actual, reference: baselineOutput)+ let byteExact = actual == baselineOutput+ #expect(baselineMaxAbs <= 0.03,+ "shape M=\(m) N=\(n) K=\(k) maxAbs=\(baselineMaxAbs) rel=\(baselineRelative) byteExact=\(byteExact)")+ #expect(baselineRelative <= 1e-3 || baselineMaxAbs <= 0.01,+ "shape M=\(m) N=\(n) K=\(k) maxAbs=\(baselineMaxAbs) rel=\(baselineRelative) byteExact=\(byteExact)")++ if compareCPUReference {+ let reference = cpuReference(inputs, m: m, n: n, k: k)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ let relative = RelError.compute(actual: actual, reference: reference)+ #expect(maxAbs <= 0.03,+ "CPU reference M=\(m) N=\(n) K=\(k) maxAbs=\(maxAbs) rel=\(relative)")+ #expect(relative <= 1e-3,+ "CPU reference M=\(m) N=\(n) K=\(k) maxAbs=\(maxAbs) rel=\(relative)")+ }+ return path+ }++ @Test func affineThreadgroupCandidateMatchesFP32AffineReference() throws {+ let context = try MetalContext()+ let candidate = MPPPrefillInt4QMM(context: context)+ let baseline = try PrefillInt4QMM(context: context)++ try Self.runShape(context: context, candidate: candidate, baseline: baseline,+ m: 64, n: 32, k: 64, compareCPUReference: true)+ try Self.runShape(context: context, candidate: candidate, baseline: baseline,+ m: 64, n: 32, k: 128, adversarialAffine: true,+ compareCPUReference: true)+ try Self.runShape(context: context, candidate: candidate, baseline: baseline,+ m: 17, n: 35, k: 64, compareCPUReference: true)+ try Self.runShape(+ context: context, candidate: candidate, baseline: baseline,+ m: 17, n: 35, k: 128, adversarialAffine: true,+ weightOffset: 13, scaleOffset: 2, biasOffset: 6,+ compareCPUReference: true)+ }++ @Test func selectedProductionAttentionShapesMatchCurrentPolicy() throws {+ let context = try MetalContext()+ let candidate = MPPPrefillInt4QMM(context: context)+ let baseline = try PrefillInt4QMM(context: context)+ let shapes = [+ (name: "swa-q", n: 4096, k: 2816),+ (name: "swa-kv", n: 2048, k: 2816),+ (name: "swa-o", n: 2816, k: 4096),+ (name: "full-q", n: 8192, k: 2816),+ (name: "full-kv", n: 1024, k: 2816),+ (name: "full-o", n: 2816, k: 8192),+ ]+ for m in [32, 128] {+ for shape in shapes {+ let path = try Self.runShape(+ context: context, candidate: candidate, baseline: baseline,+ m: m, n: shape.n, k: shape.k)+ #expect(path == .affineThreadgroupF16,+ "\(shape.name) M=\(m) unexpectedly fell back")+ }+ }+ }++ @Test func fullProductionShapeIsByteStableAcross32Dispatches() throws {+ let m = 32+ let n = 2816+ let k = 8192+ let outputElements = m * n+ let outputBytes = outputElements * MemoryLayout<Float16>.stride+ let inputs = Self.makeInputs(m: m, n: n, k: k)+ let context = try MetalContext()+ let candidate = MPPPrefillInt4QMM(context: context)+ guard let weights = Self.makeBuffer(device: context.device, values: inputs.packed),+ let scales = Self.makeBuffer(device: context.device, values: inputs.scales),+ let biases = Self.makeBuffer(device: context.device, values: inputs.biases),+ let input = Fp16Buffer.make(context.device, halves: inputs.x),+ let outputs = context.device.makeBuffer(length: outputBytes * 32,+ options: .storageModeShared),+ let commandBuffer = context.queue.makeCommandBuffer() else {+ Issue.record("buffer allocation failed")+ return+ }+ for run in 0..<32 {+ let path = candidate.encode(commandBuffer: commandBuffer,+ weights: weights,+ scales: scales,+ biases: biases,+ x: input,+ y: outputs,+ yOffset: run * outputBytes,+ m: m,+ n: n,+ k: k)+ #expect(path == .affineThreadgroupF16)+ }+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ #expect(commandBuffer.error == nil)++ let reference = outputs.contents().assumingMemoryBound(to: UInt16.self)+ for run in 1..<32 {+ let candidateOutput = outputs.contents()+ .advanced(by: run * outputBytes)+ .assumingMemoryBound(to: UInt16.self)+ var mismatch: Int?+ for index in 0..<outputElements where reference[index] != candidateOutput[index] {+ mismatch = index+ break+ }+ #expect(mismatch == nil, "dispatch \(run) first mismatch=\(mismatch ?? -1)")+ }+ }++ @Test func unsupportedOrUnalignedInputsReportFallback() throws {+ let context = try MetalContext()+ let candidate = MPPPrefillInt4QMM(context: context)+ guard let buffer = context.device.makeBuffer(length: 4096,+ options: .storageModeShared),+ let commandBuffer = context.queue.makeCommandBuffer() else {+ Issue.record("buffer allocation failed")+ return+ }+ let unsupportedShape = candidate.encode(commandBuffer: commandBuffer,+ weights: buffer,+ scales: buffer,+ biases: buffer,+ x: buffer,+ y: buffer,+ m: 1,+ n: 1,+ k: 65)+ let unalignedScale = candidate.encode(commandBuffer: commandBuffer,+ weights: buffer,+ weightsOffset: 1,+ scales: buffer,+ scalesOffset: 1,+ biases: buffer,+ x: buffer,+ y: buffer,+ m: 1,+ n: 1,+ k: 64)+ #expect(unsupportedShape == .unavailable)+ #expect(unalignedScale == .unavailable)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift b/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swiftnew file mode 100644index 00000000..9225a50c--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift@@ -0,0 +1,42 @@+import Testing+@testable import TurboFieldfare++@Suite struct RuntimeConfigurationTests {+ @Test func productionDefaultsAreStable() {+ let runtime = RuntimeConfiguration.production+ #expect(runtime.kvStorage == .fp16)+ #expect(runtime.fp16RingEnabled)+ #expect(runtime.expertCacheSlots == 16)+ #expect(runtime.expertCachePolicy == .lfu)+ #expect(runtime.rdadvisePolicy == .off)+ #expect(!runtime.rdadviseEnabled)+ #expect(runtime.prefillPolicy == .chunked)+ #expect(runtime.prefillChunkTokens == 128)+ #expect(runtime.headPath == .fusedRows)+ }++ @Test func retainedControlsReachTypedRuntime() {+ let runtime = RuntimeConfiguration(+ expertCacheSlots: 32,+ expertCachePolicy: .lru,+ rdadvisePolicy: .adaptive,+ prefillEnabled: false,+ prefillChunkTokens: 64,+ turboQuantKVEnabled: true,+ forceLogitsHead: true)+ #expect(runtime.expertCacheSlots == 32)+ #expect(runtime.modelExpertCachePolicy == .lru)+ #expect(runtime.rdadviseEnabled)+ #expect(runtime.prefillConfig == .off)+ #expect(runtime.turboQuantKVEnabled)+ #expect(runtime.kvStorage == .packedK4V4)+ #expect(runtime.headPath == .logits)+ }++ @Test(arguments: [32, 64, 128])+ func productionPrefillSupportsPublicChunkSizes(_ chunkTokens: Int) {+ let runtime = RuntimeConfiguration(prefillChunkTokens: chunkTokens)+ #expect(runtime.prefillConfig.mode == .chunked)+ #expect(runtime.prefillConfig.chunkTokens == chunkTokens)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Cancellation.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Cancellation.swiftnew file mode 100644index 00000000..bb6b3691--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Cancellation.swift@@ -0,0 +1,36 @@+import Foundation+import Metal+import Testing+import TurboFieldfareValidationSupport++@testable import TurboFieldfare++extension RawCompletionLoopTests {+ @Test func cancellationPropagatesMidDecode() async throws {+ let ctx = try MetalContext()+ let tok = try await GFTokenizer.load()+ let idA = tok.encode("a", addBOS: false).first!+ let producer = ScriptedLogitProducer(+ vocabSize: tok.vocabSize,+ step: automaton([idA, idA], end: idA))+ let promptIds = tok.encode("go", addBOS: true)+ let scratch = try RawCompletionScratch(context: ctx, vocab: tok.vocabSize)++ let task = Task {+ try await runRawCompletion(+ producer: producer, tokenizer: tok,+ promptIds: promptIds,+ config: GenerationConfig(maxNewTokens: 100_000, temperature: 0),+ context: ctx, scratch: scratch,+ prefillConfig: .off+ ) { progress in+ if case .token(let index, _, _) = progress, index == 2 {+ withUnsafeCurrentTask { $0?.cancel() }+ }+ }+ }+ await #expect(throws: CancellationError.self) {+ _ = try await task.value+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Chunked.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Chunked.swiftnew file mode 100644index 00000000..9c95e3b7--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Chunked.swift@@ -0,0 +1,131 @@+import Testing++@testable import TurboFieldfare++extension RawCompletionLoopTests {+ @Test func chunkedModeRequiresChunkedProducer() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let promptIDs = tokenizer.encode("one two three", addBOS: true)+ let producer = CountingProducer(+ vocabSize: tokenizer.vocabSize,+ step: automaton([tokenA], end: tokenizer.eosID))+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)++ do {+ _ = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ config: GenerationConfig(maxNewTokens: 4, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .production(chunkTokens: 32)) { _ in }+ Issue.record("expected chunked unsupported error")+ } catch let error as PrefillError {+ guard case .chunkedUnsupported(let reason) = error else {+ Issue.record("unexpected PrefillError \(error)")+ return+ }+ #expect(reason == PrefillError.chunkedRequiresChunkedRunnerReason)+ }++ #expect(producer.produceCalls == 0)+ }++ @Test func chunkedModeUsesChunkedRunnerEntryPoint() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let producer = ChunkedTestProducer(vocabSize: tokenizer.vocabSize, firstToken: tokenA)+ let promptIDs = tokenizer.encode("go", addBOS: true)+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)+ var prefills: [(Int, Int)] = []++ let result = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ config: GenerationConfig(maxNewTokens: 1, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .production(chunkTokens: 32)) { progress in+ if case .prefill(let done, let total) = progress {+ prefills.append((done, total))+ }+ }++ #expect(result.newTokens == 1)+ #expect(producer.chunkedCalls == 1)+ #expect(producer.produceCalls == 0)+ #expect(producer.lastOutputMode == .logits)+ #expect(producer.lastConfig == .production(chunkTokens: 32))+ #expect(prefills.count == 1)+ #expect(prefills.first?.0 == promptIDs.count)+ #expect(prefills.first?.1 == promptIDs.count)+ }++ @Test func chunkedLogitsSeedProducesFirstToken() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let producer = ChunkedTestProducer(vocabSize: tokenizer.vocabSize, firstToken: tokenA)+ let promptIDs = tokenizer.encode("go", addBOS: true)+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)+ var tokens: [Int32] = []++ let result = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ config: GenerationConfig(maxNewTokens: 1, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .production(chunkTokens: 32)) { progress in+ if case .token(_, let id, _) = progress {+ tokens.append(id)+ }+ }++ #expect(result.newTokens == 1)+ #expect(tokens == [tokenA])+ #expect(producer.chunkedCalls == 1)+ #expect(producer.produceCalls == 0)+ #expect(producer.lastOutputMode == .logits)+ }++ @Test func chunkedPrefillRejectsGreedySeedWhenLogitsRequested() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let producer = ChunkedTestProducer(+ vocabSize: tokenizer.vocabSize,+ firstToken: tokenA,+ seed: .greedyToken(UInt32(bitPattern: tokenA)))+ let promptIDs = tokenizer.encode("go", addBOS: true)+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)++ do {+ _ = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ config: GenerationConfig(maxNewTokens: 1, temperature: 0.7),+ context: context,+ scratch: scratch,+ prefillConfig: .production(chunkTokens: 32)) { _ in }+ Issue.record("expected unsupported chunked prefill seed")+ } catch let error as PrefillError {+ guard case .unsupportedPrefillSeed(let reason) = error else {+ Issue.record("unexpected PrefillError \(error)")+ return+ }+ #expect(reason.contains("RawCompletion chunked prefill requested logits"))+ }++ #expect(producer.chunkedCalls == 1)+ #expect(producer.produceCalls == 0)+ #expect(producer.lastOutputMode == .logits)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Prefill.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Prefill.swiftnew file mode 100644index 00000000..d257331d--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Prefill.swift@@ -0,0 +1,44 @@+import Testing++@testable import TurboFieldfare++extension RawCompletionLoopTests {+ @Test func prefillProgressCoversEveryPromptToken() async throws {+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let promptIDs = tokenizer.encode("one two three", addBOS: true)+ let (collected, result) = try await runLoop(+ seq: [tokenA],+ end: tokenizer.eosID,+ prompt: "one two three",+ config: GenerationConfig(maxNewTokens: 4, temperature: 0))++ #expect(result.prefillTokens == promptIDs.count)+ #expect(collected.prefills.count == promptIDs.count)+ #expect(collected.prefills.last?.0 == promptIDs.count)+ #expect(collected.prefills.allSatisfy { $0.1 == promptIDs.count })+ }++ @Test func disabledChunkedPrefillUsesScalarReplay() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let promptIDs = tokenizer.encode("one two three", addBOS: true)+ let producer = CountingProducer(+ vocabSize: tokenizer.vocabSize,+ step: automaton([tokenA], end: tokenizer.eosID))+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)++ _ = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ config: GenerationConfig(maxNewTokens: 4, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .off) { _ in }++ #expect(producer.resetCalls == 1)+ #expect(producer.produceCalls > promptIDs.count)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Stopping.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Stopping.swiftnew file mode 100644index 00000000..bb98561f--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Stopping.swift@@ -0,0 +1,51 @@+import Foundation+import Metal+import Testing++@testable import TurboFieldfare++extension RawCompletionLoopTests {+ @Test func stopsOnEOS() async throws {+ let tok = try await GFTokenizer.load()+ let idA = tok.encode("a", addBOS: false).first!+ let idB = tok.encode("b", addBOS: false).first!+ let (collected, result) = try await runLoop(+ seq: [idA, idB], end: tok.eosID,+ config: GenerationConfig(maxNewTokens: 50, temperature: 0))+ #expect(result.reason == .eos)+ #expect(result.newTokens == 3)+ #expect(collected.tokens.map(\.1) == [idA, idB])+ }++ @Test func stopsOnEndOfTurn() async throws {+ let tok = try await GFTokenizer.load()+ let idA = tok.encode("a", addBOS: false).first!+ let (_, result) = try await runLoop(+ seq: [idA], end: tok.endOfTurnID,+ config: GenerationConfig(maxNewTokens: 50, temperature: 0))+ #expect(result.reason == .endOfTurn)+ }++ @Test func stopsOnMaxTokensAndCountsExactly() async throws {+ let tok = try await GFTokenizer.load()+ let idA = tok.encode("a", addBOS: false).first!+ let (collected, result) = try await runLoop(+ seq: [idA, idA], end: idA,+ config: GenerationConfig(maxNewTokens: 5, temperature: 0))+ #expect(result.reason == .maxTokens)+ #expect(result.newTokens == 5)+ #expect(collected.tokens.count == 5)+ #expect(collected.tokens.map(\.0) == [0, 1, 2, 3, 4])+ }++ @Test func stopsOnStopString() async throws {+ let tok = try await GFTokenizer.load()+ let idA = tok.encode("a", addBOS: false).first!+ let textA = tok.decode([idA], skipSpecialTokens: true)+ let (_, result) = try await runLoop(+ seq: [idA, idA], end: idA,+ config: GenerationConfig(maxNewTokens: 50, temperature: 0, stopStrings: [textA]))+ #expect(result.reason == .stopString)+ }++}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Validation.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Validation.swiftnew file mode 100644index 00000000..5de59175--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Validation.swift@@ -0,0 +1,99 @@+import Testing++@testable import TurboFieldfare++extension RawCompletionLoopTests {+ @Test func rawCompletionRejectsContextOverflowBeforeReset() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let promptIDs = tokenizer.encode("one two three", addBOS: true)+ let producer = CountingProducer(+ vocabSize: tokenizer.vocabSize,+ maxContext: promptIDs.count,+ step: automaton([tokenA], end: tokenizer.eosID))+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)++ do {+ _ = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ config: GenerationConfig(maxNewTokens: 1, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .off) { _ in }+ Issue.record("expected context overflow")+ } catch let error as GeneratorError {+ guard case .contextOverflow(let prompt, let maxNew, let maxContext) = error else {+ Issue.record("unexpected GeneratorError \(error)")+ return+ }+ #expect(prompt == promptIDs.count)+ #expect(maxNew == 1)+ #expect(maxContext == promptIDs.count)+ }++ #expect(producer.resetCalls == 0)+ #expect(producer.produceCalls == 0)+ }++ @Test func rawCompletionRejectsZeroMaxNewBeforeReset() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let promptIDs = tokenizer.encode("one two three", addBOS: true)+ let producer = CountingProducer(+ vocabSize: tokenizer.vocabSize,+ step: automaton([tokenA], end: tokenizer.eosID))+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)++ do {+ _ = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: promptIDs,+ config: GenerationConfig(maxNewTokens: 0, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .off) { _ in }+ Issue.record("expected invalid generation config")+ } catch let error as GeneratorError {+ guard case .invalidGenerationConfig(let reason) = error else {+ Issue.record("unexpected GeneratorError \(error)")+ return+ }+ #expect(reason.contains("maxNewTokens"))+ }++ #expect(producer.resetCalls == 0)+ #expect(producer.produceCalls == 0)+ }++ @Test func rawCompletionRejectsEmptyPromptBeforeReset() async throws {+ let context = try MetalContext()+ let tokenizer = try await GFTokenizer.load()+ let tokenA = tokenizer.encode("a", addBOS: false).first!+ let producer = CountingProducer(+ vocabSize: tokenizer.vocabSize,+ step: automaton([tokenA], end: tokenizer.eosID))+ let scratch = try RawCompletionScratch(context: context, vocab: tokenizer.vocabSize)++ do {+ _ = try await runRawCompletion(+ producer: producer,+ tokenizer: tokenizer,+ promptIds: [],+ config: GenerationConfig(maxNewTokens: 1, temperature: 0),+ context: context,+ scratch: scratch,+ prefillConfig: .off) { _ in }+ Issue.record("expected empty prompt rejection")+ } catch let error as GeneratorError {+ #expect(error == .emptyPrompt)+ }++ #expect(producer.resetCalls == 0)+ #expect(producer.produceCalls == 0)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests.swiftnew file mode 100644index 00000000..2742fd1c--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests.swift@@ -0,0 +1,140 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// Shared raw-completion loop validation: stops, progress callbacks, tail+/// flush, and cancellation, via `ScriptedLogitProducer` (kernel-independent).+@Suite struct RawCompletionLoopTests {++ func automaton(_ seq: [Int32], end: Int32) -> @Sendable (Int32, Int) -> ScriptedLogitProducer.Step {+ let next: [Int32: Int32] = {+ var n: [Int32: Int32] = [:]+ for i in 0..<max(0, seq.count - 1) { n[seq[i]] = seq[i + 1] }+ if let last = seq.last { n[last] = end }+ return n+ }()+ let first = seq.first ?? end+ return { input, _ in .argmax(next[input] ?? first) }+ }++ struct Collected {+ var prefills: [(Int, Int)] = []+ var tokens: [(Int, Int32, String)] = []+ var tails: [String] = []+ }++ final class CountingProducer: LogitProducer, ContextWindowReporting, @unchecked Sendable {+ let vocabSize: Int+ let maxContext: Int+ private let step: @Sendable (Int32, Int) -> ScriptedLogitProducer.Step+ private var calls = 0+ private(set) var resetCalls = 0+ private(set) var produceCalls = 0++ init(vocabSize: Int,+ maxContext: Int = Int.max,+ step: @escaping @Sendable (Int32, Int) -> ScriptedLogitProducer.Step) {+ self.vocabSize = vocabSize+ self.maxContext = maxContext+ self.step = step+ }++ func reset() {+ resetCalls += 1+ calls = 0+ produceCalls = 0+ }++ func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws {+ produceCalls += 1+ let spec = step(token, calls)+ calls += 1+ let ptr = logits.contents().bindMemory(to: Float16.self, capacity: vocabSize)+ switch spec {+ case .argmax(let token):+ for i in 0..<vocabSize { ptr[i] = Float16(-30.0) }+ if Int(token) >= 0 && Int(token) < vocabSize {+ ptr[Int(token)] = Float16(30.0)+ }+ case .vector(let values):+ for i in 0..<vocabSize {+ ptr[i] = Float16(i < values.count ? values[i] : -30.0)+ }+ }+ }++ }++ final class ChunkedTestProducer: LogitProducer, ChunkedPrefillRunner, @unchecked Sendable {+ let vocabSize: Int+ private let firstToken: Int32+ private let seed: PrefillSeed+ private(set) var resetCalls = 0+ private(set) var produceCalls = 0+ private(set) var chunkedCalls = 0+ private(set) var lastOutputMode: PrefillOutputMode?+ private(set) var lastConfig: PrefillRuntimeConfig?++ init(vocabSize: Int,+ firstToken: Int32,+ seed: PrefillSeed = .logitsWritten) {+ self.vocabSize = vocabSize+ self.firstToken = firstToken+ self.seed = seed+ }++ func reset() {+ resetCalls += 1+ produceCalls = 0+ chunkedCalls = 0+ lastOutputMode = nil+ lastConfig = nil+ }++ func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws {+ produceCalls += 1+ }++ func prefillChunked(tokens: ArraySlice<Int32>,+ startPosition: Int,+ outputMode: PrefillOutputMode,+ config: PrefillRuntimeConfig,+ into logits: MTLBuffer,+ onProgress: (Int) -> Void) async throws -> PrefillResult {+ chunkedCalls += 1+ lastOutputMode = outputMode+ lastConfig = config+ let ptr = logits.contents().bindMemory(to: Float16.self, capacity: vocabSize)+ for i in 0..<vocabSize { ptr[i] = Float16(-30.0) }+ ptr[Int(firstToken)] = Float16(30.0)+ onProgress(tokens.count)+ return PrefillResult(newPosition: startPosition + tokens.count,+ seed: seed)+ }+ }++ func runLoop(seq: [Int32], end: Int32, prompt: String = "go",+ config: GenerationConfig) async throws -> (Collected, RawDecodeResult) {+ let ctx = try MetalContext()+ let tok = try await GFTokenizer.load()+ let producer = ScriptedLogitProducer(vocabSize: tok.vocabSize,+ step: automaton(seq, end: end))+ let promptIds = tok.encode(prompt, addBOS: true)+ let scratch = try RawCompletionScratch(context: ctx, vocab: tok.vocabSize)+ var collected = Collected()+ let result = try await runRawCompletion(producer: producer, tokenizer: tok,+ promptIds: promptIds, config: config,+ context: ctx, scratch: scratch,+ prefillConfig: .off) { progress in+ switch progress {+ case .prefill(let done, let total): collected.prefills.append((done, total))+ case .token(let index, let id, let delta): collected.tokens.append((index, id, delta))+ case .tail(let text): collected.tails.append(text)+ }+ }+ return (collected, result)+ }++}diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/SamplerTests.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/SamplerTests.swiftnew file mode 100644index 00000000..a4f9091d--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/SamplerTests.swift@@ -0,0 +1,202 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++/// `Sampler` exercises: greedy=argmax, seeded determinism + per-position+/// reproducibility, top-k / top-p truncation, repetition penalty, temperature+/// spread. Inputs are raw pre-softcap logits+/// (the sampler runs the softcap+softmax front-end itself).+@Suite struct SamplerTests {++ /// Reusable rig — one MetalContext + Sampler + buffers, shared across the+ /// many draws a single test makes (avoids recompiling the shader library+ /// per draw).+ private final class Rig {+ let ctx: MetalContext+ let sampler: Sampler+ let vocab: Int+ let logits: MTLBuffer+ let probs: MTLBuffer+ let outToken: MTLBuffer++ init(vocab: Int) throws {+ self.ctx = try MetalContext()+ self.sampler = try Sampler(context: ctx, vocab: vocab)+ self.vocab = vocab+ guard let l = ctx.device.makeBuffer(length: vocab * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let p = ctx.device.makeBuffer(length: vocab * MemoryLayout<Float16>.size,+ options: .storageModeShared),+ let o = ctx.device.makeBuffer(length: MemoryLayout<UInt32>.size,+ options: .storageModeShared) else {+ throw MetalError.noDevice+ }+ self.logits = l; self.probs = p; self.outToken = o+ }++ func writeLogits(_ values: [Float]) {+ let ptr = logits.contents().bindMemory(to: Float16.self, capacity: vocab)+ for i in 0..<vocab { ptr[i] = Float16(values[i]) }+ }++ @discardableResult+ func draw(_ values: [Float], config: GenerationConfig,+ position: Int = 0, history: [Int32] = []) -> (id: UInt32, path: SamplePath) {+ writeLogits(values)+ let cmd = ctx.queue.makeCommandBuffer()!+ let path = sampler.sample(commandBuffer: cmd, logits: logits, probs: probs,+ history: history, config: config,+ position: position, outToken: outToken)+ cmd.commit(); cmd.waitUntilCompleted()+ return (outToken.contents().load(as: UInt32.self), path)+ }+ }++ @Test func greedy_picksArgmax() throws {+ let v = 2048+ let rig = try Rig(vocab: v)+ var logits = [Float](repeating: 0.1, count: v)+ logits[1337] = 9.0+ let (id, path) = rig.draw(logits, config: GenerationConfig(temperature: 0))+ #expect(id == 1337, "got \(id)")+ #expect(path == .greedyGPU)+ }++ @Test func seeded_isDeterministicAtPosition() throws {+ let v = 1024+ let rig = try Rig(vocab: v)+ var rng = SeedTree(0x51A7_1005).key("sampler-position-determinism")+ let logits = (0..<v).map { _ in rng.uniform(-2, 2) }+ let cfg = GenerationConfig(temperature: 1.0, seed: 42)+ let a = rig.draw(logits, config: cfg, position: 3).id+ let b = rig.draw(logits, config: cfg, position: 3).id+ #expect(a == b, "same seed+position gave \(a) vs \(b)")+ #expect(rig.draw(logits, config: cfg, position: 0).path == .gpuSampled)+ }++ @Test func seeded_reproducibleAcrossPositions() throws {+ let v = 1024+ let rig = try Rig(vocab: v)+ var rng = SeedTree(0x51A7_1006).key("sampler-position-replay")+ let logits = (0..<v).map { _ in rng.uniform(-2, 2) }+ let cfg = GenerationConfig(temperature: 1.0, seed: 42)+ let run1 = (0..<5).map { rig.draw(logits, config: cfg, position: $0).id }+ let run2 = (0..<5).map { rig.draw(logits, config: cfg, position: $0).id }+ #expect(run1 == run2, "seed=42 not reproducible: \(run1) vs \(run2)")++ // A different seed should diverge on at least one position.+ let cfg43 = GenerationConfig(temperature: 1.0, seed: 43)+ let run3 = (0..<5).map { rig.draw(logits, config: cfg43, position: $0).id }+ #expect(run3 != run1, "seed 42 and 43 produced identical sequences")+ }++ @Test func topK_restrictsToTop() throws {+ let v = 1024+ let rig = try Rig(vocab: v)+ var logits = [Float](repeating: -8.0, count: v)+ let top: [Int] = [10, 200, 500, 900]+ logits[top[0]] = 4.0; logits[top[1]] = 3.0; logits[top[2]] = 2.0; logits[top[3]] = 1.0+ let topSet = Set(top.map { UInt32($0) })+ for t in 0..<32 {+ let cfg = GenerationConfig(temperature: 1.0, topK: 4, seed: UInt64(t) &+ 1)+ let id = rig.draw(logits, config: cfg, position: t).id+ #expect(topSet.contains(id), "trial \(t): id=\(id) outside top-4")+ }+ }++ @Test func topP_restrictsToNucleus() throws {+ let v = 512+ let rig = try Rig(vocab: v)+ // Two tokens hold ~99% of the mass after softmax.+ var logits = [Float](repeating: -10.0, count: v)+ logits[7] = 6.0+ logits[42] = 5.6+ let nucleus: Set<UInt32> = [7, 42]+ for t in 0..<32 {+ let cfg = GenerationConfig(temperature: 1.0, topP: 0.9, seed: UInt64(t) &+ 1)+ let id = rig.draw(logits, config: cfg, position: t).id+ #expect(nucleus.contains(id), "trial \(t): id=\(id) outside nucleus")+ }+ }++ @Test func repetitionPenalty_suppressesHistory() throws {+ let v = 64+ let rig = try Rig(vocab: v)+ // Large positive logits so penalty 2.0 (logit 8 -> 4) suppresses id 5+ // decisively post-softmax (~0.03x the others); flat logits of 1.0 only+ // scale its mass by ~0.6x, which the statistical bound below cannot+ // separate from noise.+ let logits = [Float](repeating: 8.0, count: v)+ let history: [Int32] = [5, 5, 5]+ var count5 = 0+ let trials = 200+ for t in 0..<trials {+ let cfg = GenerationConfig(temperature: 1.0, repetitionPenalty: 2.0, seed: UInt64(t) &+ 1)+ let (id, path) = rig.draw(logits, config: cfg, position: t, history: history)+ #expect(path == .hostPenalty)+ if id == 5 { count5 += 1 }+ }+ // Uniform would pick 5 about trials/v times; suppression should push it+ // well below that. Generous bound to avoid flakiness.+ let uniformExpect = Double(trials) / Double(v)+ #expect(Double(count5) < 0.5 * uniformExpect, "id 5 chosen \(count5) times (uniform≈\(uniformExpect))")+ }++ /// Saturated-logit suppression: real Gemma 4 raw logits reach the+ /// hundreds, deep in softcap-tanh saturation. The penalty must act on the+ /// post-softcap value — applied to the raw logit it moves the capped+ /// result by ~nothing and the penalty silently no-ops (the repetition-loop+ /// regression this pins).+ @Test func repetitionPenalty_bitesOnSaturatedLogits() throws {+ let v = 64+ let rig = try Rig(vocab: v)+ // All raw logits deep in tanh saturation; id 5 is the model's strong+ // favorite and also the repeated-history token.+ var logits = [Float](repeating: 300.0, count: v)+ logits[5] = 400.0+ let history: [Int32] = [5]+ var count5 = 0+ let trials = 64+ for t in 0..<trials {+ let cfg = GenerationConfig(temperature: 1.0, repetitionPenalty: 1.3, seed: UInt64(t) &+ 1)+ let (id, path) = rig.draw(logits, config: cfg, position: t, history: history)+ #expect(path == .hostPenalty)+ if id == 5 { count5 += 1 }+ }+ // Post-softcap both land near the 30 cap; penalty 1.3 drops id 5 to+ // ~23, ~e^-7 of the others — it should essentially never win. The raw+ // pre-fix math left id 5 the argmax favorite at >half the draws.+ #expect(count5 < trials / 8, "saturated id 5 drawn \(count5)/\(trials) despite penalty")+ }++ /// Temperature spread: a logit sharp enough that greedy would always pick+ /// index 0 should, under raised temperature, distribute mass across many+ /// tokens. Exercised through the enumerated top-k path (`topK == v`).+ /// The `topK == 0` branch is the Gumbel-max fast path (argmax over noised+ /// log-probs), which cannot return an out-of-range id by construction.+ @Test func raisedTemperature_spreadsMass() throws {+ let v = 32+ let rig = try Rig(vocab: v)+ var logits = [Float](repeating: 0.0, count: v)+ logits[0] = 8.0+ var counts = [Int](repeating: 0, count: v)+ let trials = 1600+ for t in 0..<trials {+ let cfg = GenerationConfig(temperature: 2.0, topK: v, seed: UInt64(t) &+ 1)+ let raw = rig.draw(logits, config: cfg, position: t).id+ let id = Int(raw)+ guard id >= 0 && id < v else { Issue.record("id \(raw) (0x\(String(raw, radix: 16))) out of range v=\(v)"); continue }+ counts[id] += 1+ }+ let maxShare = Double(counts.max() ?? trials) / Double(trials)+ let distinct = counts.filter { $0 > 0 }.count+ // Greedy would give a top-token share of 1.0; raised temperature must+ // pull it well below that. (Bound kept loose — this asserts spread, not+ // a precise distribution.)+ #expect(maxShare < 0.7, "top token share \(maxShare) — temperature did not spread mass")+ #expect(distinct > v / 4, "only \(distinct)/\(v) tokens drawn — too concentrated")+ }++}diff --git a/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swiftnew file mode 100644index 00000000..3b738da6--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift@@ -0,0 +1,212 @@+import Testing+import Foundation+import Metal+@testable import TurboFieldfare++/// Tests `KVCacheManager` shape, growth, separate K/V storage, FP16 SWA ring,+/// packed storage, and reset semantics against the Gemma 4 config.+@Suite struct KVCacheManagerTests {++ private let config = ArchConfig.gemma4_26B_A4B++ private func makeManager(maxContext: Int,+ storageMode: KVCacheStorageMode = .fp16,+ fp16RingEnabled: Bool = false,+ fp16RingCapacityOverride: Int? = nil) throws -> (MetalContext, KVCacheManager) {+ let ctx = try MetalContext()+ let kv = try KVCacheManager(device: ctx.device,+ config: config,+ maxContext: maxContext,+ storageMode: storageMode,+ fp16RingEnabled: fp16RingEnabled,+ slidingWindow: config.slidingWindow,+ maxPrefillChunkTokens: 128,+ fp16RingCapacityOverride: fp16RingCapacityOverride)+ return (ctx, kv)+ }++ @Test func defaultStorageMode_isFP16() throws {+ let (_, kv) = try makeManager(maxContext: 16)+ #expect(kv.storageMode == .fp16)+ #expect(kv.turboQuantLayout(layer: 0) == nil)+ }++ @Test func strideAndBufferSizes_matchConfig() throws {+ let (_, kv) = try makeManager(maxContext: 128)++ // SWA: numKVHeads(8) * headDim(256) * 2 = 4096 B/token.+ // Full: numFullKVHeads(2) * fullHeadDim(512) * 2 = 2048 B/token.+ #expect(kv.kRange(layer: 0, start: 0, count: 1).stride == 8 * 256 * 2)+ #expect(kv.kRange(layer: 5, start: 0, count: 1).stride == 2 * 512 * 2)+ #expect(kv.keyBuffer(layer: 0, validTokenCount: 0).length == 128 * 4096)+ #expect(kv.keyBuffer(layer: 5, validTokenCount: 0).length == 128 * 2048)+ }++ @Test func linearGrowth_tracksAdvance() throws {+ let (_, kv) = try makeManager(maxContext: 128)+ #expect(kv.position == 0)+ for n in 1...100 {+ kv.advance()+ #expect(kv.position == n)+ }+ }++ /// Full layers share the raw k_proj output, then diverge: K runs k_norm ++ /// RoPE while V runs no-scale v_norm without RoPE. They therefore require+ /// separate cache slots.+ @Test func fullLayer_separatesKAndVBuffers() throws {+ let (_, kv) = try makeManager(maxContext: 16)+ let k = kv.keyBuffer(layer: 5, validTokenCount: 0)+ let v = kv.valueBuffer(layer: 5, validTokenCount: 0)+ #expect(k !== v, "full-layer K and V must NOT alias")+ let ks = kv.kSlot(layer: 5, position: 3)+ let vs = kv.vSlot(layer: 5, position: 3)+ #expect(ks.buffer !== vs.buffer, "full-layer K/V slots must NOT alias")+ // Offsets are still per-position-strided in both buffers.+ #expect(ks.offset == vs.offset)+ }++ @Test func swaLayer_hasSeparateKVBuffers() throws {+ let (_, kv) = try makeManager(maxContext: 16)+ #expect(kv.keyBuffer(layer: 0, validTokenCount: 0)+ !== kv.valueBuffer(layer: 0, validTokenCount: 0))+ }++ @Test func slotOffsets_areLinear() throws {+ let (_, kv) = try makeManager(maxContext: 128)+ #expect(kv.kSlot(layer: 0, position: 0).offset == 0)+ #expect(kv.kSlot(layer: 0, position: 3).offset == 3 * 4096)+ #expect(kv.vSlot(layer: 5, position: 7).offset == 7 * 2048)+ }++ @Test func fp16Ring_capsSWALayersAndLeavesFullLayersLinear() throws {+ let (_, kv) = try makeManager(maxContext: 4096,+ fp16RingEnabled: true)++ #expect(kv.fp16RingEnabled)+ #expect(kv.capacity(layer: 0) == 1152)+ #expect(kv.ringCapacity(layer: 0) == 1152)+ #expect(kv.keyBuffer(layer: 0, validTokenCount: 0).length == 1152 * 4096)+ #expect(kv.capacity(layer: 5) == 4096)+ #expect(kv.ringCapacity(layer: 5) == 0)+ #expect(kv.keyBuffer(layer: 5, validTokenCount: 0).length == 4096 * 2048)+ }++ @Test func fp16Ring_shortSessionCapsSWAToMaxContext() throws {+ let (_, kv) = try makeManager(maxContext: 256,+ fp16RingEnabled: true)++ #expect(kv.fp16RingEnabled)+ #expect(kv.capacity(layer: 0) == 256)+ #expect(kv.ringCapacity(layer: 0) == 256)+ #expect(kv.keyBuffer(layer: 0, validTokenCount: 0).length == 256 * 4096)+ #expect(kv.capacity(layer: 5) == 256)+ #expect(kv.ringCapacity(layer: 5) == 0)+ #expect(kv.keyBuffer(layer: 5, validTokenCount: 0).length == 256 * 2048)+ }++ @Test func fp16Ring_slotOffsetsWrapOnlyForSWALayers() throws {+ let (_, kv) = try makeManager(maxContext: 128,+ fp16RingEnabled: true,+ fp16RingCapacityOverride: 32)++ #expect(kv.kSlot(layer: 0, position: 0).offset == 0)+ #expect(kv.kSlot(layer: 0, position: 31).offset == 31 * 4096)+ #expect(kv.kSlot(layer: 0, position: 32).offset == 0)+ #expect(kv.vSlot(layer: 0, position: 35).offset == 3 * 4096)++ #expect(kv.kSlot(layer: 5, position: 35).offset == 35 * 2048)+ #expect(kv.vSlot(layer: 5, position: 35).offset == 35 * 2048)+ }++ @Test func fp16Ring_rangesMustNotWrap() throws {+ let (_, kv) = try makeManager(maxContext: 128,+ fp16RingEnabled: true,+ fp16RingCapacityOverride: 32)++ let k = kv.kRange(layer: 0, start: 28, count: 4)+ #expect(k.offset == 28 * 4096)+ let v = kv.vRange(layer: 0, start: 32, count: 3)+ #expect(v.offset == 0)+ }++ @Test func rangeSlotsHaveLinearOffsets() throws {+ let (_, kv) = try makeManager(maxContext: 128)+ let swaStride = kv.kRange(layer: 0, start: 0, count: 1).stride+ let fullStride = kv.vRange(layer: 5, start: 0, count: 1).stride++ let k = kv.kRange(layer: 0, start: 7, count: 3)+ let v = kv.vRange(layer: 5, start: 11, count: 5)++ #expect(k.offset == 7 * swaStride)+ #expect(k.stride == swaStride)+ #expect(v.offset == 11 * fullStride)+ #expect(v.stride == fullStride)+ #expect(k.buffer === kv.keyBuffer(layer: 0, validTokenCount: 0))+ #expect(v.buffer === kv.valueBuffer(layer: 5, validTokenCount: 0))+ }++ @Test func advanceByCountTracksCursor() throws {+ let (_, kv) = try makeManager(maxContext: 128)+ kv.advance(by: 31)+ #expect(kv.position == 31)+ kv.advance(by: 0)+ #expect(kv.position == 31)+ kv.advance()+ #expect(kv.position == 32)+ }++ @Test func reset_clearsPosition() throws {+ let (_, kv) = try makeManager(maxContext: 128)+ for _ in 0..<100 { kv.advance() }+ #expect(kv.position == 100)+ kv.reset()+ #expect(kv.position == 0)+ // Cursor reusable after reset.+ kv.advance()+ #expect(kv.position == 1)+ }++ @Test func turboQuantStorage_usesPackedLayerLayouts() throws {+ let (_, kv) = try makeManager(maxContext: 128,+ storageMode: .turboQuant(.k4v4NormCorrected))++ #expect(kv.storageMode == .turboQuant(.k4v4NormCorrected))++ let swa = try #require(kv.turboQuantLayout(layer: 0))+ #expect(swa.key.bytesPerToken == 1_040)+ #expect(swa.value.bytesPerToken == 1_040)+ #expect(kv.quantizedKeyBuffer(layer: 0, validTokenCount: 0).length == 128 * 1_040)+ #expect(kv.quantizedValueBuffer(layer: 0, validTokenCount: 0).length == 128 * 1_040)++ let full = try #require(kv.turboQuantLayout(layer: 5))+ #expect(full.key.bytesPerToken == 516)+ #expect(full.value.bytesPerToken == 516)+ #expect(kv.quantizedKeyBuffer(layer: 5, validTokenCount: 0).length == 128 * 516)+ #expect(kv.quantizedValueBuffer(layer: 5, validTokenCount: 0).length == 128 * 516)+ }++ @Test func turboQuantSlots_areLinearByRoleStride() throws {+ let (_, kv) = try makeManager(maxContext: 128,+ storageMode: .turboQuant(.k4v4NormCorrected))++ let swa = try #require(kv.turboQuantLayout(layer: 0))+ #expect(swa.key.bytesPerToken == 1_040)+ #expect(swa.value.bytesPerToken == 1_040)++ let k0 = kv.quantizedKeySlot(layer: 0, position: 3)+ let v0 = kv.quantizedValueSlot(layer: 0, position: 3)+ #expect(k0.offset == 3 * swa.key.bytesPerToken)+ #expect(v0.offset == 3 * swa.value.bytesPerToken)+ #expect(k0.buffer !== v0.buffer)+ }++ @Test func turboQuantReset_clearsPosition() throws {+ let (_, kv) = try makeManager(maxContext: 128,+ storageMode: .turboQuant(.k4v4NormCorrected))+ for _ in 0..<9 { kv.advance() }+ #expect(kv.position == 9)+ kv.reset()+ #expect(kv.position == 0)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/KVCache/TurboQuantKVLayoutTests.swift b/Tests/TurboFieldfare/Core/Runtime/KVCache/TurboQuantKVLayoutTests.swiftnew file mode 100644index 00000000..5ecbe029--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/KVCache/TurboQuantKVLayoutTests.swift@@ -0,0 +1,44 @@+import Testing++@testable import TurboFieldfare++@Suite struct TurboQuantKVLayoutTests {+ @Test func swaLayoutUsesPackedK4V4Storage() {+ let layout = TurboQuantKVLayout.layer(mode: .k4v4NormCorrected,+ headDim: 256,+ numKVHeads: 8,+ capacity: 4)++ #expect(layout.key.packedOffsetPerHead == 0)+ #expect(layout.key.scaleOffsetPerHead == 128)+ #expect(layout.key.bytesPerHead == 130)+ #expect(layout.key.bytesPerToken == 1_040)+ #expect(layout.key.bytesPerToken + layout.value.bytesPerToken == 2_080)+ #expect(4 * (layout.key.bytesPerToken + layout.value.bytesPerToken) == 8_320)+ }++ @Test func fullAttentionLayoutUsesPackedK4V4Storage() {+ let layout = TurboQuantKVLayout.layer(mode: .k4v4NormCorrected,+ headDim: 512,+ numKVHeads: 2,+ capacity: 4)++ #expect(layout.key.scaleOffsetPerHead == 256)+ #expect(layout.key.bytesPerHead == 258)+ #expect(layout.key.bytesPerToken == 516)+ #expect(layout.value.bytesPerToken == 516)+ #expect(layout.key.bytesPerToken + layout.value.bytesPerToken == 1_032)+ #expect(4 * (layout.key.bytesPerToken + layout.value.bytesPerToken) == 4_128)+ }++ @Test func offsetsFollowTokenAndHeadStrides() {+ let layout = TurboQuantKVLayout.layer(mode: .k4v4NormCorrected,+ headDim: 256,+ numKVHeads: 8,+ capacity: 8)+ let headBase = 2 * 1_040 + 3 * 130++ #expect(headBase + layout.key.packedOffsetPerHead == headBase)+ #expect(headBase + layout.key.scaleOffsetPerHead == headBase + 128)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swiftnew file mode 100644index 00000000..d94a918f--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift@@ -0,0 +1,84 @@+import Testing+import Metal+@testable import TurboFieldfare++@Suite struct PrefillChunkScratchTests {+ @Test func gemma4T32LayoutMatchesTask7ScratchContract() {+ let layout = PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 32)++ #expect(layout.chunkTokens == 32)+ #expect(layout.hiddenElements == 32 * 2816)+ #expect(layout.normedElements == 32 * 2816)+ #expect(layout.qElements == 32 * 8192)+ #expect(layout.kStageElements == 32 * 2048)+ #expect(layout.vStageElements == 32 * 2048)+ #expect(layout.attentionOutputElements == 32 * 8192)+ #expect(layout.denseXElements == 32 * 2816)+ #expect(layout.routedXElements == 32 * 2816)+ #expect(layout.routerXElements == 32 * 2816)+ #expect(layout.h1Elements == 32 * 2816)+ #expect(layout.h2Elements == 32 * 2816)+ #expect(layout.routePartialElements == 32 * 8 * 2816)+ #expect(layout.routeIDElements == 32 * 8)+ #expect(layout.routeWeightElements == 32 * 8)+ #expect(layout.sharedExpertActScratchElements == 2112)+ #expect(layout.routedPairMicrobatchRows == 32)+ #expect(layout.routedGateUpActElements == 3 * 32 * 704)+ #expect(layout.routedDownOutputElements == 32 * 2816)++ let worksheetT32UpperBound = Int(4.5 * 1_048_576.0)+ #expect(layout.totalPersistentBytes <= worksheetT32UpperBound)+ }++ @Test func layoutClampsChunkSizeToRuntimeBounds() {+ #expect(PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 0).chunkTokens == 1)+ #expect(PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 512).chunkTokens == 128)+ }++ @Test func allocationUsesPrivateScratchAndSharedRouteMetadata() throws {+ let ctx = try MetalContext()+ let toy = ArchConfig(hiddenSize: 64,+ intermediateSize: 48,+ moeIntermediateSize: 16,+ numHeads: 4,+ numKVHeads: 2,+ numFullKVHeads: 1,+ headDim: 16,+ fullHeadDim: 32,+ vocabSize: 128,+ slidingWindow: 16,+ finalLogitSoftcap: 30.0,+ ropeTheta: 10_000,+ fullRopeTheta: 1_000_000,+ partialRotaryFactor: 0.25,+ numLayers: 2,+ numExperts: 8,+ topKExperts: 2,+ tieWordEmbeddings: true,+ attentionKEqV: true,+ fullAttentionLayerMask: [0, 1],+ hiddenActivation: "gelu_pytorch_tanh")+ let layout = PrefillChunkScratchLayout(config: toy, chunkTokens: 4)++ let scratch = try PrefillChunkScratchBuffers.allocate(device: ctx.device, layout: layout)++ #expect(scratch.layout == layout)+ #expect(scratch.hidden.length == layout.hiddenElements * MemoryLayout<Float16>.stride)+ #expect(scratch.denseX.length == layout.denseXElements * MemoryLayout<Float16>.stride)+ #expect(scratch.routedX.length == layout.routedXElements * MemoryLayout<Float16>.stride)+ #expect(scratch.routerX.length == layout.routerXElements * MemoryLayout<Float16>.stride)+ #expect(scratch.routePartials.length == layout.routePartialElements * MemoryLayout<Float16>.stride)+ #expect(scratch.routeIDs.length == layout.routeIDElements * MemoryLayout<UInt32>.stride)+ #expect(scratch.routeWeights.length == layout.routeWeightElements * MemoryLayout<Float16>.stride)+ #expect(scratch.routedGateUpActScratch.length == layout.routedGateUpActElements * MemoryLayout<Float16>.stride)+ #expect(scratch.routedDownScratch.length == layout.routedDownOutputElements * MemoryLayout<Float16>.stride)+ #expect(scratch.hidden.storageMode == MTLStorageMode.private)+ #expect(scratch.denseX.storageMode == MTLStorageMode.private)+ #expect(scratch.routedX.storageMode == MTLStorageMode.private)+ #expect(scratch.routerX.storageMode == MTLStorageMode.private)+ #expect(scratch.routedGateUpActScratch.storageMode == MTLStorageMode.private)+ #expect(scratch.routedDownScratch.storageMode == MTLStorageMode.private)+ #expect(scratch.routeIDs.storageMode == MTLStorageMode.shared)+ #expect(scratch.routeWeights.storageMode == MTLStorageMode.shared)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillRuntimeConfigTests.swift b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillRuntimeConfigTests.swiftnew file mode 100644index 00000000..fd2c88d1--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillRuntimeConfigTests.swift@@ -0,0 +1,37 @@+import Testing+@testable import TurboFieldfare++@Suite struct PrefillRuntimeConfigTests {+ @Test(arguments: [32, 64, 128])+ func productionUsesCompleteChunkedPath(_ chunkTokens: Int) throws {+ let config = PrefillRuntimeConfig.production(chunkTokens: chunkTokens)+ #expect(config.mode == .chunked)+ #expect(config.chunkTokens == chunkTokens)+ }++ @Test func offDisablesChunkedPrefill() {+ let config = PrefillRuntimeConfig.off+ #expect(config.mode == .off)+ #expect(!config.enabled)+ }++ @Test func plannerUsesConfiguredChunkSize() {+ let spans = PrefillChunkPlanner.spans(+ tokenCount: 130,+ startPosition: 7,+ config: .production(chunkTokens: 64))+ #expect(spans.map(\.tokenCount) == [64, 64, 2])+ #expect(spans.map(\.startPosition) == [7, 71, 135])+ }++ @Test func diagnosticsPreserveUnknownValues() {+ let diagnostics = PrefillExecutionDiagnostics(+ config: .production(chunkTokens: 128),+ executedMode: .unsupported,+ kvStorageMode: nil,+ unsupportedReason: "unavailable")+ #expect(diagnostics.kvStorageMode == nil)+ #expect(diagnostics.chunkCompleteness == .unsupported)+ #expect(diagnostics.unsupportedReason == "unavailable")+ }+}diff --git a/Tests/TurboFieldfare/Core/Tokenization/TokenizerLoadCoordinatorTests.swift b/Tests/TurboFieldfare/Core/Tokenization/TokenizerLoadCoordinatorTests.swiftnew file mode 100644index 00000000..14615f6c--- /dev/null+++ b/Tests/TurboFieldfare/Core/Tokenization/TokenizerLoadCoordinatorTests.swift@@ -0,0 +1,77 @@+import Foundation+import Testing+@testable import TurboFieldfare++@Suite("Tokenizer load coordinator")+struct TokenizerLoadCoordinatorTests {+ @Test("Concurrent loads return equivalent tokenizer metadata")+ func concurrentLoadsShareLoadedTokenizer() async throws {+ let tokenizers = try await withThrowingTaskGroup(of: GFTokenizer.self) { group in+ for _ in 0..<8 {+ group.addTask {+ try await GFTokenizer.load()+ }+ }++ var loaded: [GFTokenizer] = []+ loaded.reserveCapacity(8)+ for try await tokenizer in group {+ loaded.append(tokenizer)+ }+ return loaded+ }++ #expect(tokenizers.count == 8)+ let first = try #require(tokenizers.first)+ for tokenizer in tokenizers {+ #expect(tokenizer.bosID == first.bosID)+ #expect(tokenizer.eosID == first.eosID)+ #expect(tokenizer.padID == first.padID)+ #expect(tokenizer.endOfTurnID == first.endOfTurnID)+ #expect(tokenizer.encode("The capital of France is", addBOS: true)+ == first.encode("The capital of France is", addBOS: true))+ }+ }++ @Test("Consecutive loads reuse the completed process cache")+ func consecutiveLoadsReuseCompletedTask() async throws {+ let first = try await GFTokenizer.load()+ let second = try await GFTokenizer.load()++ #expect(second.bosID == first.bosID)+ #expect(second.eosID == first.eosID)+ #expect(second.endOfTurnID == first.endOfTurnID)+ #expect(second.decode(first.encode("cache check", addBOS: false)) == "cache check")+ }++ @Test("Model tokenizer sidecar is discovered")+ func modelTokenizerSidecarIsDiscovered() throws {+ let root = try temporaryDirectory()+ let model = root.appendingPathComponent("model.gturbo", isDirectory: true)+ let modelTokenizer = model.appendingPathComponent("tokenizer", isDirectory: true)+ try FileManager.default.createDirectory(at: modelTokenizer, withIntermediateDirectories: true)+ try Data("{}".utf8).write(to: modelTokenizer.appendingPathComponent("tokenizer.json"))++ let resolved = GFTokenizer.tokenizerFolder(forModelDirectory: model)++ #expect(resolved == modelTokenizer.standardizedFileURL)+ }++ @Test("Missing model tokenizer sidecar returns nil")+ func missingModelTokenizerSidecarReturnsNil() throws {+ let root = try temporaryDirectory()+ let model = root.appendingPathComponent("model.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(at: model, withIntermediateDirectories: true)++ let resolved = GFTokenizer.tokenizerFolder(forModelDirectory: model)++ #expect(resolved == nil)+ }++ private func temporaryDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("gf-tokenizer-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ return url+ }+}diff --git a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swiftnew file mode 100644index 00000000..efe364b8--- /dev/null+++ b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift@@ -0,0 +1,175 @@+import Foundation+import Testing+@testable import TurboFieldfare++/// First run downloads the Gemma 4 IT tokenizer (~32 MB) from Hugging Face+/// Hub to `~/.cache/huggingface/`. Subsequent runs are offline.+@Suite("Tokenizer")+struct TokenizerTests {+ let tok: GFTokenizer++ init() async throws {+ self.tok = try await GFTokenizer.load()+ }++ // MARK: - Special tokens++ @Test("Special token IDs are distinct and within vocab")+ func specialTokensDistinct() {+ let ids: [Int32] = [tok.bosID, tok.eosID, tok.padID, tok.endOfTurnID]+ #expect(Set(ids).count == 4, "expected 4 distinct special token IDs, got \(ids)")+ for id in ids {+ #expect(id >= 0)+ #expect(id < Int32(tok.vocabSize))+ }+ }++ @Test("Stop-token set covers EOS and end-of-turn")+ func stopTokens() {+ #expect(tok.stopTokenIDs.contains(tok.eosID))+ #expect(tok.stopTokenIDs.contains(tok.endOfTurnID))+ #expect(tok.stopTokenIDs.count == 2)+ }++ // MARK: - Encode / decode++ @Test("Round-trip ASCII", arguments: [+ "Hello, world.",+ "The quick brown fox jumps over the lazy dog.",+ "code: let x = 42; // comment",+ "numbers 0 1 2 3 4 5 6 7 8 9",+ ])+ func roundTripASCII(_ text: String) {+ let ids = tok.encode(text, addBOS: false)+ #expect(tok.decode(ids) == text)+ }++ @Test("Round-trip multi-byte UTF-8", arguments: [+ "你好,世界。",+ "漢字",+ "🦝 raccoon emoji",+ "mixed 漢 and 🦝 and a",+ "Здравствуй",+ ])+ func roundTripMultibyte(_ text: String) {+ let ids = tok.encode(text, addBOS: false)+ #expect(tok.decode(ids) == text)+ }++ @Test("BOS is added when requested and absent otherwise")+ func bosPrepend() {+ let withBOS = tok.encode("x", addBOS: true)+ let without = tok.encode("x", addBOS: false)+ #expect(withBOS.first == tok.bosID)+ #expect(without.first != tok.bosID)+ #expect(withBOS.count == without.count + 1)+ #expect(Array(withBOS.dropFirst()) == without)+ }++ @Test("Empty string encodes to BOS-only or empty")+ func encodeEmpty() {+ let none = tok.encode("", addBOS: false)+ #expect(none.isEmpty)+ let bos = tok.encode("", addBOS: true)+ #expect(bos == [tok.bosID])+ }++ @Test("Decoding strips special tokens when requested")+ func decodeStripsSpecial() {+ let ids = tok.encode("hi", addBOS: true)+ #expect(ids.first == tok.bosID)+ let withoutSpecial = tok.decode(ids, skipSpecialTokens: true)+ #expect(withoutSpecial == "hi")+ }++ // MARK: - Streaming detokenizer++ @Test("Streaming detokenizer reassembles ASCII")+ func streamingASCII() {+ let target = "Hello, world."+ assertStreams(target)+ }++ @Test("Streaming detokenizer reassembles multi-byte UTF-8", arguments: [+ "漢字",+ "你好",+ "🦝🦝🦝",+ "mixed 漢 and 🦝",+ "Здравствуй мир",+ "ends with emoji 🦝",+ "🦝 starts with emoji",+ "🦝 middle 漢 end",+ ])+ func streamingMultibyte(_ target: String) {+ assertStreams(target)+ }++ @Test("Streaming detokenizer never emits replacement chars")+ func streamingNoMojibake() {+ let ids = tok.encode("mixed 漢 and 🦝 text", addBOS: false)+ var detok = GFDetokenizer(tokenizer: tok)+ for id in ids {+ let delta = detok.push(id)+ #expect(!delta.unicodeScalars.contains("\u{FFFD}"),+ "delta contained replacement char: '\(delta)'")+ }+ let tail = detok.flush()+ #expect(!tail.unicodeScalars.contains("\u{FFFD}"))+ }++ @Test("Streaming detokenizer preserves long mixed output", arguments: [+ "The quick brown fox jumps over the lazy dog. 0123456789\n",+ "\u{E000}\u{E001}\u{E002}\u{E003}\u{E004}\u{E005}\u{E006}\u{E007}",+ "TurboFieldfare 漢字 Здравствуй 🦝 café Ελληνικά \u{E000}\n",+ ])+ func streamingLongOutput(_ seed: String) {+ var text = seed+ var ids = tok.encode(text, addBOS: false)+ while ids.count < 256 {+ text += seed+ ids = tok.encode(text, addBOS: false)+ }++ let prefix = Array(ids.prefix(256))+ var detok = GFDetokenizer(tokenizer: tok)+ var assembled = ""+ for id in prefix {+ assembled += detok.push(id)+ }+ assembled += detok.flush()+ #expect(assembled == tok.decode(prefix))+ #expect(!assembled.unicodeScalars.contains("\u{FFFD}"))+ }++ @Test("Flush with no tokens yields empty string")+ func streamingEmpty() {+ var detok = GFDetokenizer(tokenizer: tok)+ #expect(detok.flush() == "")+ }++ @Test("Single-token push works for in-vocab characters")+ func streamingSingleToken() {+ // "漢字" is a single in-vocab token (verified empirically).+ var detok = GFDetokenizer(tokenizer: tok)+ let ids = tok.encode("漢字", addBOS: false)+ var assembled = ""+ for id in ids {+ assembled += detok.push(id)+ }+ assembled += detok.flush()+ #expect(assembled == "漢字")+ }++ // MARK: - Helpers++ private func assertStreams(_ target: String) {+ let ids = tok.encode(target, addBOS: false)+ var detok = GFDetokenizer(tokenizer: tok)+ var assembled = ""+ for id in ids {+ assembled += detok.push(id)+ }+ assembled += detok.flush()+ #expect(assembled == target, "stream reassembly mismatch: got '\(assembled)' want '\(target)'")+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/AttentionReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/AttentionReferenceTests.swiftnew file mode 100644index 00000000..ac5050b1--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/AttentionReferenceTests.swift@@ -0,0 +1,78 @@+import Testing+import Foundation+import TurboFieldfareValidationSupport++@Suite struct AttentionReferenceTests {+ /// Independent reference: scalar per-element accumulation, no vDSP.+ /// Same math, no Accelerate.+ private static func scalarRef(+ q: [Float], k: [Float], v: [Float],+ headDim: Int, numQHeads: Int, numKVHeads: Int,+ seqLen: Int, window: Int?+ ) -> [Float] {+ let groupSize = numQHeads / numKVHeads+ let scale = 1.0 / Float(headDim).squareRoot()+ let kvStart: Int = (window.map { w in max(0, seqLen - w) }) ?? 0+ var out = [Float](repeating: 0, count: numQHeads * headDim)+ for qh in 0..<numQHeads {+ let kvHead = qh / groupSize+ let qBase = qh * headDim+ var scores = [Float](repeating: 0, count: seqLen)+ var mx: Float = -.greatestFiniteMagnitude+ for p in kvStart..<seqLen {+ var s: Float = 0+ let kBase = (p * numKVHeads + kvHead) * headDim+ for d in 0..<headDim { s += q[qBase + d] * k[kBase + d] }+ s *= scale+ scores[p] = s+ if s > mx { mx = s }+ }+ var sumExp: Float = 0+ for p in kvStart..<seqLen {+ scores[p] = Foundation.exp(scores[p] - mx)+ sumExp += scores[p]+ }+ let invSum = 1.0 / sumExp+ for d in 0..<headDim {+ var acc: Float = 0+ for p in kvStart..<seqLen {+ let vBase = (p * numKVHeads + kvHead) * headDim+ acc += scores[p] * invSum * v[vBase + d]+ }+ out[qh * headDim + d] = acc+ }+ }+ return out+ }++ @Test("vDSP ref matches scalar", arguments: [+ (Int(64), 4, 2, 128, Int?(64), UInt64(0x161)),+ (Int(64), 4, 2, 32, Int?(128), UInt64(0x162)),+ (Int(64), 8, 1, 128, Int?(nil), UInt64(0x163)),+ (Int(128), 8, 4, 64, Int?(nil), UInt64(0x164)),+ ])+ func vDSPMatchesScalar(+ headDim: Int, numQHeads: Int, numKVHeads: Int,+ seqLen: Int, window: Int?, seed: UInt64+ ) {+ var rng = SeedTree(seed).key("attention-ref-h\(numQHeads)-d\(headDim)-T\(seqLen)")+ let qCount = numQHeads * headDim+ let kvCount = seqLen * numKVHeads * headDim+ let q = (0..<qCount).map { _ in rng.uniform(-0.5, 0.5) }+ let k = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }+ let v = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }++ let vdsp = AttentionRef.apply(+ q: q, k: k, v: v,+ headDim: headDim, numQHeads: numQHeads,+ numKVHeads: numKVHeads, seqLen: seqLen, window: window+ )+ let scalar = Self.scalarRef(+ q: q, k: k, v: v,+ headDim: headDim, numQHeads: numQHeads,+ numKVHeads: numKVHeads, seqLen: seqLen, window: window+ )+ let rel = RelError.compute(actual: vdsp, reference: scalar)+ #expect(rel < Tolerance.identity, "rel=\(rel)")+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/DequantInt4GEMVReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/DequantInt4GEMVReferenceTests.swiftnew file mode 100644index 00000000..1b75aaef--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/DequantInt4GEMVReferenceTests.swift@@ -0,0 +1,77 @@+import Testing+import Foundation+import TurboFieldfare+import TurboFieldfareValidationSupport++/// Validates `DequantInt4GemvRef.apply` against a scalar reference that+/// dequantizes inline (per-element nibble unpack + scalar accumulate).+/// vDSP path and scalar path must agree to `Tolerance.identity`.+///+/// Also pins the affine quantization round-trip bound: per-group worst-case+/// rounding is `scale/2` (codebook step) plus the BF16 rounding of the scale+/// and bias.+@Suite struct DequantInt4GEMVReferenceTests {++ /// Scalar reference: dequantize inline, scalar accumulate. No vDSP.+ private static func scalarRef(+ weightRows: [Quantization.Int4AffineRow],+ x: [Float],+ n: Int+ ) -> [Float] {+ let m = weightRows.count+ var y = [Float](repeating: 0, count: m)+ for row in 0..<m {+ let w = Quantization.dequantizeInt4Affine(weightRows[row], n: n)+ var sum: Float = 0+ for i in 0..<n { sum += w[i] * x[i] }+ y[row] = sum+ }+ return y+ }++ @Test("vDSP ref matches scalar ref", arguments: [+ (4, 128, UInt64(0xF1)),+ (8, 256, UInt64(0xF2)),+ (16, 512, UInt64(0xF3)),+ (32, 2816, UInt64(0xF4)),+ ])+ func vDSPMatchesScalar(m: Int, n: Int, seed: UInt64) {+ var rng = SeedTree(seed).key("int4-gemv-ref-m\(m)-n\(n)")+ var rows: [Quantization.Int4AffineRow] = []+ rows.reserveCapacity(m)+ for _ in 0..<m {+ let raw = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }+ rows.append(Quantization.quantizeInt4Affine(raw))+ }+ let x = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }++ let vdsp = DequantInt4GemvRef.apply(weightRows: rows, x: x, n: n)+ let scalar = Self.scalarRef(weightRows: rows, x: x, n: n)++ let rel = RelError.compute(actual: vdsp, reference: scalar)+ #expect(rel < Tolerance.identity, "M=\(m) N=\(n) rel=\(rel)")+ }++ /// INT4 affine round-trip: error bounded by one codebook step `scale`.+ /// Rounding into `q ∈ [0..15]` contributes scale/2 and BF16 rounding of+ /// scale/bias contributes at most ulp(BF16(scale)) * 15 — both absorbed+ /// by `scale + small`.+ @Test("INT4 affine round-trip stays within derived bound", arguments: [128, 256, 2816])+ func quantizationDerivedBound(n: Int) {+ var rng = SeedTree(0xF5).key("int4-affine-roundtrip-n\(n)")+ let raw = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }+ let q = Quantization.quantizeInt4Affine(raw)+ let recovered = Quantization.dequantizeInt4Affine(q, n: n)++ let groups = n / Quantization.groupSize+ for g in 0..<groups {+ let scale = Quantization.bf16ToFloat(q.scales[g])+ let bound = scale + 1e-4+ for k in 0..<Quantization.groupSize {+ let i = g * Quantization.groupSize + k+ #expect(abs(recovered[i] - raw[i]) <= bound,+ "group=\(g) k=\(k) diff=\(abs(recovered[i] - raw[i])) bound=\(bound)")+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/DequantInt8GEMVReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/DequantInt8GEMVReferenceTests.swiftnew file mode 100644index 00000000..b83af4f8--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/DequantInt8GEMVReferenceTests.swift@@ -0,0 +1,66 @@+import Testing+import Foundation+import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct DequantInt8GEMVReferenceTests {+ private static func scalarRef(+ weightRows: [Quantization.Int8AffineRow],+ x: [Float],+ n: Int+ ) -> [Float] {+ let m = weightRows.count+ var y = [Float](repeating: 0, count: m)+ for row in 0..<m {+ let w = Quantization.dequantizeInt8Affine(weightRows[row], n: n)+ var sum: Float = 0+ for i in 0..<n { sum += w[i] * x[i] }+ y[row] = sum+ }+ return y+ }++ @Test("vDSP ref matches scalar", arguments: [+ (4, 128, UInt64(0x141)),+ (8, 256, UInt64(0x142)),+ (16, 512, UInt64(0x143)),+ (128, 2816, UInt64(0x144)),+ ])+ func vDSPMatchesScalar(m: Int, n: Int, seed: UInt64) {+ var rng = SeedTree(seed).key("int8-gemv-ref-m\(m)-n\(n)")+ var rows: [Quantization.Int8AffineRow] = []+ rows.reserveCapacity(m)+ for _ in 0..<m {+ let raw = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }+ rows.append(Quantization.quantizeInt8Affine(raw))+ }+ let x = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }++ let vdsp = DequantInt8GemvRef.apply(weightRows: rows, x: x, n: n)+ let scalar = Self.scalarRef(weightRows: rows, x: x, n: n)++ let rel = RelError.compute(actual: vdsp, reference: scalar)+ #expect(rel < Tolerance.identity, "M=\(m) N=\(n) rel=\(rel)")+ }++ /// INT8 affine round-trip bound. Codebook step `scale` covers the ±0.5 LSB+ /// rounding plus BF16 rounding of scale/bias.+ @Test("INT8 affine round-trip stays within derived bound", arguments: [128, 256, 2816])+ func quantizationDerivedBound(n: Int) {+ var rng = SeedTree(0x145).key("int8-affine-roundtrip-n\(n)")+ let raw = (0..<n).map { _ in rng.uniform(-1.0, 1.0) }+ let q = Quantization.quantizeInt8Affine(raw)+ let recovered = Quantization.dequantizeInt8Affine(q, n: n)++ let groups = n / Quantization.groupSize+ for g in 0..<groups {+ let scale = Quantization.bf16ToFloat(q.scales[g])+ let bound = scale + 1e-4+ for k in 0..<Quantization.groupSize {+ let i = g * Quantization.groupSize + k+ #expect(abs(recovered[i] - raw[i]) <= bound,+ "group=\(g) k=\(k) diff=\(abs(recovered[i] - raw[i])) bound=\(bound)")+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/EmbedLookupReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/EmbedLookupReferenceTests.swiftnew file mode 100644index 00000000..0d27b1b2--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/EmbedLookupReferenceTests.swift@@ -0,0 +1,44 @@+import Testing+import Foundation+import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct EmbedLookupReferenceTests {+ @Test("Lookup matches direct dequant of the same row", arguments: [+ (Int(16), 128, UInt64(0x10B)),+ (Int(32), 256, UInt64(0x10C)),+ (Int(64), 512, UInt64(0x10D)),+ ])+ func lookupMatchesDirectDequant(v: Int, d: Int, seed: UInt64) {+ var rng = SeedTree(seed).key("embed-lookup-v\(v)-d\(d)")+ var rows: [[Float]] = []+ rows.reserveCapacity(v)+ for _ in 0..<v {+ rows.append((0..<d).map { _ in rng.uniform(-1.0, 1.0) })+ }++ let groupsPerRow = d / Quantization.groupSize+ var packed = [UInt8]( repeating: 0, count: v * d)+ var scales = [UInt16](repeating: 0, count: v * groupsPerRow)+ var biases = [UInt16](repeating: 0, count: v * groupsPerRow)+ for token in 0..<v {+ let q = Quantization.quantizeInt8Affine(rows[token])+ for i in 0..<d { packed[token * d + i] = q.packed[i] }+ for g in 0..<groupsPerRow {+ scales[token * groupsPerRow + g] = q.scales[g]+ biases[token * groupsPerRow + g] = q.biases[g]+ }+ }++ for token in [0, v / 2, v - 1] {+ let viaRef = EmbedLookupRef.apply(+ tablePacked: packed, tableScales: scales, tableBiases: biases,+ tokenId: token, d: d+ )+ let q = Quantization.quantizeInt8Affine(rows[token])+ let viaDirect = Quantization.dequantizeInt8Affine(q, n: d)+ let rel = RelError.compute(actual: viaRef, reference: viaDirect)+ #expect(rel < Tolerance.identity, "v=\(v) d=\(d) token=\(token) rel=\(rel)")+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/LogitSoftcapSoftmaxReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/LogitSoftcapSoftmaxReferenceTests.swiftnew file mode 100644index 00000000..f591db06--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/LogitSoftcapSoftmaxReferenceTests.swift@@ -0,0 +1,47 @@+import Testing+import Foundation+import TurboFieldfareValidationSupport++@Suite struct LogitSoftcapSoftmaxReferenceTests {+ /// Scalar reference: explicit per-element softcap, then explicit+ /// max/exp/sum/divide. No vDSP / vForce / cblas.+ private static func scalarRef(x: [Float], softcap: Float) -> [Float] {+ let v = x.count+ var capped = [Float](repeating: 0, count: v)+ for i in 0..<v {+ capped[i] = softcap * Foundation.tanh(x[i] / softcap)+ }+ var mx = -Float.infinity+ for v in capped { if v > mx { mx = v } }+ var es = [Float](repeating: 0, count: v)+ var sum: Float = 0+ for i in 0..<v {+ let e = Foundation.exp(capped[i] - mx)+ es[i] = e+ sum += e+ }+ return es.map { $0 / sum }+ }++ @Test("Accelerate ref matches scalar", arguments: [+ (128, Float(30.0), UInt64(0x10E)),+ (1024, Float(30.0), UInt64(0x10F)),+ (4096, Float(30.0), UInt64(0x110)),+ ])+ func acceleratedMatchesScalar(v: Int, softcap: Float, seed: UInt64) {+ var rng = SeedTree(seed).key("softcap-softmax-v\(v)")+ // Wide-range logits — exercises both the cap and the softmax tails.+ let x = (0..<v).map { _ in rng.uniform(-100.0, 100.0) }++ let accel = LogitSoftcapSoftmaxRef.apply(x: x, softcap: softcap)+ let scalar = Self.scalarRef(x: x, softcap: softcap)++ let rel = RelError.compute(actual: accel, reference: scalar)+ #expect(rel < Tolerance.identity, "V=\(v) rel=\(rel)")++ // Probability axioms.+ let sum = accel.reduce(0, +)+ #expect(abs(sum - 1.0) < 1e-4, "softmax sum=\(sum)")+ for p in accel { #expect(p >= 0 && p <= 1, "out-of-range prob \(p)") }+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/MoEReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/MoEReferenceTests.swiftnew file mode 100644index 00000000..9adab682--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/MoEReferenceTests.swift@@ -0,0 +1,41 @@+import Testing+import Foundation+import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct MoEReferenceTests {+ @Test("gelu_pytorch_tanh matches scalar definition")+ func geluConstantsCorrect() {+ // Compare against the literal Gemma 4 / PyTorch reference points.+ let y = MoeRef.geluTanh([0.0, 1.0, -1.0, 2.0])+ #expect(abs(y[0]) < 1e-7, "y(0)=\(y[0])")+ let expectedAt1: Float = 0.5 * (1 + Foundation.tanh(0.7978845608028654 * (1 + 0.044715)))+ #expect(abs(y[1] - expectedAt1) < 1e-5, "y(1)=\(y[1]) expected=\(expectedAt1)")+ #expect(y[1] > 0)+ #expect(y[2] < 0)+ #expect(y[3] > y[1])+ }++ @Test("FFN runs without divergence on small shape")+ func ffnRunsOnSmallShape() {+ let d = 128, f = 64+ var rng = SeedTree(0x181).key("moe-ref-ffn")+ func randRow() -> Quantization.Int4AffineRow {+ let raw = (0..<d).map { _ in rng.uniform(-0.3, 0.3) }+ return Quantization.quantizeInt4Affine(raw)+ }+ func randDownRow() -> Quantization.Int4AffineRow {+ let raw = (0..<f).map { _ in rng.uniform(-0.3, 0.3) }+ return Quantization.quantizeInt4Affine(raw)+ }+ let gate = (0..<f).map { _ in randRow() }+ let up = (0..<f).map { _ in randRow() }+ let down = (0..<d).map { _ in randDownRow() }+ let x = (0..<d).map { _ in rng.uniform(-0.3, 0.3) }++ let y = MoeRef.runFFN(gateRows: gate, upRows: up, downRows: down,+ x: x, d: d, f: f)+ #expect(y.count == d)+ for v in y { #expect(v.isFinite) }+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/RMSNormReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/RMSNormReferenceTests.swiftnew file mode 100644index 00000000..4eb16640--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/RMSNormReferenceTests.swift@@ -0,0 +1,58 @@+import Testing+import Foundation+import TurboFieldfareValidationSupport++/// Cross-validates `RmsNormRef.apply` (Accelerate-vector form) against a+/// second formulation written from scratch as a scalar loop. The point isn't+/// to prove the kernel right — it's to prove the *reference* right, so the+/// kernel test below has a trustworthy comparator.+///+/// The scalar formulation shares no code path with Accelerate. Both must+/// agree to `Tolerance.identity`.+@Suite struct RMSNormReferenceTests {++ /// Independent scalar reference. Different summation order than both+ /// the kernel and the Accelerate reference.+ private static func scalarRef(x: [Float], weight: [Float], eps: Float) -> [Float] {+ let d = x.count+ var sumSq: Float = 0+ for v in x { sumSq += v * v }+ let inv = 1.0 / (sumSq / Float(d) + eps).squareRoot()+ return zip(x, weight).map { $0 * inv * $1 }+ }++ @Test("Accelerate ref matches scalar ref", arguments: [+ (256, UInt64(0xA1)),+ (512, UInt64(0xB2)),+ (2816, UInt64(0xC3)),+ ])+ func acceleratedMatchesScalar(d: Int, seed: UInt64) {+ var rng = SeedTree(seed).key("rmsnorm-ref")+ let x = (0..<d).map { _ in rng.uniform(-1.0, 1.0) }+ let w = (0..<d).map { _ in rng.uniform(0.5, 1.5) }+ let eps: Float = 1e-6++ let accel = RmsNormRef.apply(x: x, weight: w, eps: eps)+ let scalar = Self.scalarRef(x: x, weight: w, eps: eps)++ let relErr = RelError.compute(actual: accel, reference: scalar)+ #expect(relErr < Tolerance.identity,+ "D=\(d): relErr=\(relErr)")+ }++ @Test("Reference handles zero-mean small magnitudes")+ func smallMagnitudes() {+ let x: [Float] = [1e-4, -1e-4, 2e-4, -2e-4, 1e-4, -1e-4, 2e-4, -2e-4]+ let w: [Float] = Array(repeating: 1.0, count: x.count)+ let y = RmsNormRef.apply(x: x, weight: w, eps: 1e-6)+ #expect(y.count == x.count)+ for v in y { #expect(v.isFinite) }+ }++ @Test("Reference rejects mismatched lengths")+ func mismatchedLengthsTrap() async {+ // Documentation-only: this would precondition-fail. We can't catch+ // preconditions in Swift Testing, but we record the contract here.+ let _ = (RmsNormRef.apply, "precondition on x.count == weight.count")+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/RoPEReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/RoPEReferenceTests.swiftnew file mode 100644index 00000000..44851074--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/RoPEReferenceTests.swift@@ -0,0 +1,101 @@+import Testing+import Foundation+import TurboFieldfareValidationSupport++/// Cross-validates `RopeRef.apply` against an independent reference+/// formulation that recomputes `cos`/`sin` per pair inline (no table+/// caching). Both must agree to `Tolerance.identity`.+@Suite struct RoPEReferenceTests {++ /// Inline-trig reference. No precomputed tables, no Accelerate.+ private static func scalarRef(input: [Float],+ numTokens: Int,+ numHeads: Int,+ headDim: Int,+ rotaryDim: Int,+ position: Int,+ theta: Float) -> [Float] {+ var out = input+ let pairs = rotaryDim / 2+ for t in 0..<numTokens {+ for h in 0..<numHeads {+ let base = (t * numHeads + h) * headDim+ for k in 0..<pairs {+ let exponent = -Float(2 * k) / Float(rotaryDim)+ let freq = powf(theta, exponent)+ let angle = Float(position) * freq+ let c = cosf(angle)+ let s = sinf(angle)+ let i0 = base + 2 * k+ let i1 = i0 + 1+ let x0 = input[i0]+ let x1 = input[i1]+ out[i0] = x0 * c - x1 * s+ out[i1] = x0 * s + x1 * c+ }+ }+ }+ return out+ }++ @Test("vForce ref matches scalar ref",+ arguments: [+ (1, 16, 256, 256, 7, Float(10_000), UInt64(0xD1)),+ (4, 8, 256, 256, 33, Float(10_000), UInt64(0xD2)),+ (1, 16, 512, 128, 11, Float(1_000_000), UInt64(0xD3)),+ (2, 4, 64, 64, 5, Float(10_000), UInt64(0xD4)),+ ])+ func vForceMatchesScalar(+ numTokens: Int,+ numHeads: Int,+ headDim: Int,+ rotaryDim: Int,+ position: Int,+ theta: Float,+ seed: UInt64+ ) {+ var rng = SeedTree(seed).key("rope-ref-h\(numHeads)-d\(headDim)")+ let count = numTokens * numHeads * headDim+ let input = (0..<count).map { _ in rng.uniform(-1.0, 1.0) }++ let vforce = RopeRef.apply(+ input: input,+ numTokens: numTokens, numHeads: numHeads,+ headDim: headDim, rotaryDim: rotaryDim,+ position: position, theta: theta+ )+ let scalar = Self.scalarRef(+ input: input,+ numTokens: numTokens, numHeads: numHeads,+ headDim: headDim, rotaryDim: rotaryDim,+ position: position, theta: theta+ )++ let rel = RelError.compute(actual: vforce, reference: scalar)+ #expect(rel < Tolerance.identity, "rel err = \(rel)")+ }++ @Test("Partial rotation leaves passthrough region byte-identical")+ func partialPassthroughUntouched() {+ var rng = SeedTree(0xD5).key("rope-passthrough")+ let numTokens = 2, numHeads = 4, headDim = 64, rotaryDim = 32+ let count = numTokens * numHeads * headDim+ let input = (0..<count).map { _ in rng.uniform(-1.0, 1.0) }++ let out = RopeRef.apply(+ input: input,+ numTokens: numTokens, numHeads: numHeads,+ headDim: headDim, rotaryDim: rotaryDim,+ position: 9, theta: 10_000+ )+ for t in 0..<numTokens {+ for h in 0..<numHeads {+ let base = (t * numHeads + h) * headDim+ for i in rotaryDim..<headDim {+ #expect(out[base + i] == input[base + i],+ "passthrough drifted at t=\(t) h=\(h) i=\(i)")+ }+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Validation/Reference/WHTReferenceTests.swift b/Tests/TurboFieldfare/Core/Validation/Reference/WHTReferenceTests.swiftnew file mode 100644index 00000000..318205b5--- /dev/null+++ b/Tests/TurboFieldfare/Core/Validation/Reference/WHTReferenceTests.swift@@ -0,0 +1,46 @@+import Testing+import Foundation+import TurboFieldfareValidationSupport++@Suite struct WHTReferenceTests {+ /// Independent iterative WHT — different control flow from recursive ref.+ private static func iterativeWht(_ x: [Float]) -> [Float] {+ let d = x.count+ var y = x+ let invSqrt2: Float = 1.0 / Float(2.0).squareRoot()+ var stride = 1+ while stride < d {+ var i = 0+ while i < d {+ for k in 0..<stride {+ let a = y[i + k]+ let b = y[i + k + stride]+ y[i + k] = (a + b) * invSqrt2+ y[i + k + stride] = (a - b) * invSqrt2+ }+ i += stride * 2+ }+ stride *= 2+ }+ return y+ }++ @Test("Recursive WHT matches iterative", arguments: [128, 256, 512])+ func recursiveMatchesIterative(d: Int) {+ var rng = SeedTree(0x1A1).key("wht-ref-d\(d)")+ let x = (0..<d).map { _ in rng.uniform(-1.0, 1.0) }+ let rec = WhtRef.apply(x)+ let itr = Self.iterativeWht(x)+ let rel = RelError.compute(actual: rec, reference: itr)+ #expect(rel < Tolerance.identity, "D=\(d) rel=\(rel)")+ }++ @Test("WHT is an involution", arguments: [128, 256, 512])+ func involution(d: Int) {+ var rng = SeedTree(0x1A2).key("wht-involution-d\(d)")+ let x = (0..<d).map { _ in rng.uniform(-1.0, 1.0) }+ let twice = WhtRef.apply(WhtRef.apply(x))+ let rel = RelError.compute(actual: twice, reference: x)+ #expect(rel < Tolerance.identity, "D=\(d) round-trip rel=\(rel)")+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppPromptPresetTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppPromptPresetTests.swiftnew file mode 100644index 00000000..d9abd241--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppPromptPresetTests.swift@@ -0,0 +1,84 @@+import TurboFieldfareAppCore+import Testing++@Suite("App prompt presets")+struct AppPromptPresetTests {+ @Test("Catalog has unique nonempty identifiers and titles")+ func catalogIdentity() {+ let presets = AppPromptPreset.all++ #expect(Set(presets.map(\.id)).count == presets.count)+ #expect(Set(presets.map(\.title)).count == presets.count)+ #expect(presets.allSatisfy { !$0.prefix.isEmpty })+ #expect(presets.count == 6)+ #expect(AppPromptPreset.primary.count == 3)+ #expect(AppPromptPreset.secondary.count == 3)+ }++ @Test("Primary presets are exact raw-completion prefixes")+ func exactPrimaryPrefixes() {+ #expect(AppPromptPreset.primary[0].prefix ==+ "Paris is the capital and largest city of France. Situated on the River Seine, the city is known for")+ #expect(AppPromptPreset.primary[1].prefix == """+ An iterative Python function can return the first n Fibonacci numbers without recursion. It returns an empty list when n is zero, uses O(n) time, and includes a small correctness check:++ ```python+ def fibonacci(n: int) -> list[int]:+ """)+ #expect(AppPromptPreset.primary[2].prefix ==+ "The fieldfare (Turdus pilaris) is a grey-headed, chestnut-backed thrush that reaches Britain and Ireland from northern Europe each autumn. Its noisy winter flocks roam the countryside in search of berries, and")+ #expect(AppPromptPreset.primary[2].id == "fieldfare")+ #expect(AppPromptPreset.primary[2].title == "Meet the fieldfare")+ #expect(!AppPromptPreset.all.contains { $0.id == "metal-gemv" })+ }++ @Test("Presets contain no chat wrappers or imperative requests")+ func rawCompletionContract() {+ let forbiddenOpenings = ["Write ", "Explain ", "Give me ", "Rewrite "]+ let forbiddenMarkers = ["<start_of_turn>", "<end_of_turn>", "user\n", "assistant\n"]++ for preset in AppPromptPreset.all {+ #expect(!forbiddenOpenings.contains { preset.prefix.hasPrefix($0) })+ #expect(!forbiddenMarkers.contains { preset.prefix.contains($0) })+ }+ }++ @Test("Primary presets include the Fieldfare easter egg")+ func fieldfarePreset() {+ let preset = AppPromptPreset.primary.first { $0.id == "fieldfare" }++ #expect(preset?.title == "Meet the fieldfare")+ #expect(preset?.prefix ==+ "The fieldfare (Turdus pilaris) is a grey-headed, chestnut-backed thrush that reaches Britain and Ireland from northern Europe each autumn. Its noisy winter flocks roam the countryside in search of berries, and")+ #expect(!AppPromptPreset.all.contains { $0.id == "software" })+ #expect(!AppPromptPreset.all.contains { $0.id == "lighthouse" })+ }++ @Test("Secondary presets include cosine similarity")+ func cosineSimilarityPreset() {+ let preset = AppPromptPreset.secondary.first { $0.id == "cosine-similarity" }++ #expect(preset?.title == "Dot product and cosine similarity")+ #expect(preset?.prefix == """+ The unit vectors u = [1, 0] and v = [0, 1] are orthogonal. Their dot product is 0, both lengths are 1, and their cosine similarity is exactly 0. A compact check is:++ ```python+ assert dot([1, 0], [0, 1]) == 0+ assert cosine_similarity([1, 0], [0, 1]) ==+ """)+ #expect(!AppPromptPreset.all.contains { $0.id == "solar-system" })+ }++ @Test("Secondary presets include recommendation systems and matrix multiplication")+ func substantialExplanationPresets() {+ let recommendations = AppPromptPreset.secondary.first { $0.id == "recommendation-systems" }+ let matrix = AppPromptPreset.secondary.first { $0.id == "matrix-multiplication" }++ #expect(recommendations?.title == "How recommendations learn")+ #expect(recommendations?.prefix.contains("Matrix factorization learns a low-dimensional vector") == true)+ #expect(recommendations?.prefix.hasSuffix("## The sparse interaction matrix") == true)+ #expect(matrix?.title == "Matrix multiplication")+ #expect(matrix?.prefix.contains("C[2,2] = 3 x 6 + 4 x 8 = 50") == true)+ #expect(matrix?.prefix.hasSuffix("## Why the inner dimensions match") == true)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swiftnew file mode 100644index 00000000..21dae813--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift@@ -0,0 +1,96 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++@Suite struct AppRuntimeOptionsTests {+ @Test func defaultsMatchProduction() throws {+ let options = AppRuntimeOptions()+ #expect(options.expertCacheSlots == 16)+ #expect(options.expertCachePolicy == .lfu)+ #expect(options.prefillEnabled)+ #expect(options.prefillChunkTokens == 128)+ #expect(!options.turboQuantKVEnabled)+ #expect(options.rdadvisePolicy == .off)+ #expect(options.modelVerification == .fullSha256)++ let runtime = try options.resolvedRuntimeConfiguration(forceLogitsHead: false)+ #expect(runtime == .production)+ #expect(options.resultSummary ==+ "Cache 16 LFU, prefill 128, FP16 KV, RDADVISE off, full SHA-256")+ }++ @Test func everyPublicChoiceMapsToRuntime() throws {+ for slots in AppRuntimeOptions.allowedSlotCounts {+ let runtime = try AppRuntimeOptions(expertCacheSlots: slots)+ .resolvedRuntimeConfiguration(forceLogitsHead: false)+ #expect(runtime.expertCacheSlots == slots)+ }+ for chunk in AppRuntimeOptions.allowedPrefillChunkTokens {+ let runtime = try AppRuntimeOptions(prefillChunkTokens: chunk)+ .resolvedRuntimeConfiguration(forceLogitsHead: false)+ #expect(runtime.prefillConfig.chunkTokens == chunk)+ }+ for policy in AppRDAdvicePolicy.allCases {+ let runtime = try AppRuntimeOptions(rdadvisePolicy: policy)+ .resolvedRuntimeConfiguration(forceLogitsHead: false)+ #expect(runtime.rdadvisePolicy == policy.runtimeValue)+ }+ }++ @Test func experimentalAndTrustChoicesAreExplicit() throws {+ let options = AppRuntimeOptions(+ expertCacheSlots: 32,+ expertCachePolicy: .lru,+ prefillEnabled: false,+ prefillChunkTokens: 64,+ turboQuantKVEnabled: true,+ rdadvisePolicy: .adaptive,+ modelVerification: .trustedInstall)+ let runtime = try options.resolvedRuntimeConfiguration(forceLogitsHead: true)+ #expect(runtime.modelExpertCachePolicy == .lru)+ #expect(runtime.prefillConfig == .off)+ #expect(runtime.turboQuantKVEnabled)+ #expect(runtime.rdadvisePolicy == .adaptive)+ #expect(runtime.headPath == .logits)+ #expect(options.modelVerification.runtimeValue == .sizeCheckTrustedReceipt)+ }++ @Test func validationRejectsValuesOutsideClosedSets() {+ #expect(throws: AppInferenceError.self) {+ try AppRuntimeOptions(expertCacheSlots: 12).validate()+ }+ #expect(throws: AppInferenceError.self) {+ try AppRuntimeOptions(prefillChunkTokens: 96).validate()+ }+ }++ @Test func loadedRuntimeKeyTracksEveryRuntimeChoice() {+ let directory = URL(fileURLWithPath: "/tmp/model.gturbo")+ let base = AppRuntimeOptions()+ let baseline = AppLoadedRuntimeKey(+ modelDirectory: directory, maxContextTokens: 4096, options: base)++ var variants: [AppRuntimeOptions] = []+ var value = base+ value.expertCacheSlots = 24; variants.append(value)+ value = base; value.expertCachePolicy = .lru; variants.append(value)+ value = base; value.prefillEnabled = false; variants.append(value)+ value = base; value.prefillChunkTokens = 64; variants.append(value)+ value = base; value.turboQuantKVEnabled = true; variants.append(value)+ value = base; value.rdadvisePolicy = .bounded; variants.append(value)+ value = base; value.modelVerification = .trustedInstall; variants.append(value)++ for variant in variants {+ #expect(AppLoadedRuntimeKey(+ modelDirectory: directory,+ maxContextTokens: 4096,+ options: variant) != baseline)+ }+ #expect(AppLoadedRuntimeKey(+ modelDirectory: directory,+ maxContextTokens: 4096,+ options: base,+ forceLogitsHead: true) != baseline)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift b/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swiftnew file mode 100644index 00000000..84711163--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Diagnostics/AppDiagnosticsTests.swift@@ -0,0 +1,65 @@+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppDiagnosticsTests {+ @Test func requestStartTTFTAddsPrefillAndPostPrefillWait() {+ let diagnostics = AppDiagnostics(+ generatedTokens: 1,+ stopReason: .eos,+ prefillSeconds: 1.25,+ timeToFirstTokenSeconds: 0.5,+ decodeSeconds: 0.75,+ tokensPerSecond: 1.0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())++ #expect(diagnostics.requestStartTimeToFirstTokenSeconds == 1.75)+ }++ @Test func requestStartTTFTIsNilWhenEitherSideIsMissing() {+ let missingPrefill = AppDiagnostics(+ generatedTokens: 1,+ stopReason: .eos,+ prefillSeconds: nil,+ timeToFirstTokenSeconds: 0.5,+ decodeSeconds: 0.75,+ tokensPerSecond: 1.0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())+ let missingFirstToken = AppDiagnostics(+ generatedTokens: 0,+ stopReason: .cancelled,+ prefillSeconds: 1.25,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0,+ tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())++ #expect(missingPrefill.requestStartTimeToFirstTokenSeconds == nil)+ #expect(missingFirstToken.requestStartTimeToFirstTokenSeconds == nil)+ }++ @Test func runnerDiagnosticsRetainPublicResultAndAdvancedMetrics() {+ let diagnostics = AppRunnerDiagnostics(+ cb1MillisecondsPerToken: 1,+ ioMillisecondsPerToken: 2,+ cb2MillisecondsPerToken: 3,+ headMillisecondsPerToken: 4,+ rdadviseMillisecondsPerToken: 5,+ rdadviseCallsPerToken: 6,+ rdadviseMegabytesPerToken: 7,+ rdadviseSkippedPerToken: 8,+ rdadviseFailures: 9)++ #expect(diagnostics.cb1MillisecondsPerToken == 1)+ #expect(diagnostics.ioMillisecondsPerToken == 2)+ #expect(diagnostics.cb2MillisecondsPerToken == 3)+ #expect(diagnostics.headMillisecondsPerToken == 4)+ #expect(diagnostics.rdadviseMillisecondsPerToken == 5)+ #expect(diagnostics.rdadviseCallsPerToken == 6)+ #expect(diagnostics.rdadviseMegabytesPerToken == 7)+ #expect(diagnostics.rdadviseSkippedPerToken == 8)+ #expect(diagnostics.rdadviseFailures == 9)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Diagnostics/AppMemorySamplerTests.swift b/Tests/TurboFieldfareApp/Core/Diagnostics/AppMemorySamplerTests.swiftnew file mode 100644index 00000000..252573d4--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Diagnostics/AppMemorySamplerTests.swift@@ -0,0 +1,29 @@+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppMemorySamplerTests {+ @Test func samplingDoesNotThrowAndTracksPeak() {+ let sampler = AppMemorySampler()+ sampler.resetPeak()+ _ = sampler.sample()+ _ = sampler.sample()+ if let peak = sampler.peakBytes {+ #expect(peak > 0)+ }+ }++ @Test func samplingReportsProcessFootprint() {+ let footprint: UInt64 = 2 * 1_024 * 1_024 * 1_024+ let sampler = AppMemorySampler(processFootprint: { footprint })++ #expect(sampler.sample() == footprint)+ #expect(sampler.peakBytes == footprint)+ }++ @Test func failedSampleDoesNotSetPeak() {+ let sampler = AppMemorySampler(processFootprint: { nil })++ #expect(sampler.sample() == nil)+ #expect(sampler.peakBytes == nil)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Diagnostics/AppModelLiveMetricsTests.swift b/Tests/TurboFieldfareApp/Core/Diagnostics/AppModelLiveMetricsTests.swiftnew file mode 100644index 00000000..92c50b09--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Diagnostics/AppModelLiveMetricsTests.swift@@ -0,0 +1,81 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppModelLiveMetricsTests {+ @MainActor+ @Test func prefillProgressUpdatesPhaseAndCounts() {+ let model = AppModel()+ model.apply(.prefillProgress(done: 12, total: 50))+ #expect(model.phase == .prefill)+ #expect(model.livePrefillDone == 12)+ #expect(model.livePrefillTotal == 50)+ }++ @MainActor+ @Test func tokenEventSwitchesToDecodeAndComputesRate() {+ let model = AppModel()+ model.apply(.token(AppTokenEvent(+ index: 4, textDelta: " x", elapsedDecodeSeconds: 2.0)))+ #expect(model.phase == .decode)+ #expect(model.liveTokenCount == 5)+ #expect(model.liveElapsedDecodeSeconds == 2.0)+ #expect(model.liveTokensPerSecond == 2.5)+ #expect(model.liveMemoryBytes != nil)+ }++ @MainActor+ @Test func liveRateIsZeroBeforeAnyToken() {+ let model = AppModel()+ #expect(model.liveTokensPerSecond == 0)+ }++ @MainActor+ @Test func terminalEventsReturnPhaseToIdleKeepingLastValues() {+ let model = AppModel()+ model.apply(.token(AppTokenEvent(+ index: 2, textDelta: "a", elapsedDecodeSeconds: 1.0)))+ model.apply(.finished(AppDiagnostics(+ generatedTokens: 3, stopReason: .eos,+ timeToFirstTokenSeconds: 0.1, decodeSeconds: 1.0, tokensPerSecond: 3,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())))+ #expect(model.phase == .idle)+ #expect(model.liveTokenCount == 3)+ }++ @MainActor+ @Test func runResetsLiveMetricsAndEntersPrefill() async {+ let client = MockInferenceClient(response: "one two", tokenDelayNanos: 1_000_000_000)+ let model = AppModel(client: client)+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.loadState = .ready(modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1)+ model.apply(.token(AppTokenEvent(+ index: 9, textDelta: "z", elapsedDecodeSeconds: 5)))+ model.promptText = "go"+ model.run()+ #expect(model.phase == .prefill)+ #expect(model.liveTokenCount == 0)+ #expect(model.liveElapsedDecodeSeconds == 0)+ #expect(model.livePrefillDone == 0)+ model.cancel()+ for _ in 0..<200 where model.isRunning {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ }++ @MainActor+ @Test func cancelKeepsPartialLiveMetrics() {+ let model = AppModel()+ model.apply(.token(AppTokenEvent(+ index: 1, textDelta: "p", elapsedDecodeSeconds: 0.5)))+ model.apply(.cancelled(AppDiagnostics(+ generatedTokens: 2, stopReason: .cancelled,+ timeToFirstTokenSeconds: nil, decodeSeconds: 0.5, tokensPerSecond: 4,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())))+ #expect(model.phase == .idle)+ #expect(model.liveTokenCount == 2)+ #expect(model.error == .cancelled)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swiftnew file mode 100644index 00000000..8e7ed539--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift@@ -0,0 +1,94 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppGenerationRequestTests {+ private let existingDirectory = FileManager.default.temporaryDirectory++ @Test func defaultRequestUsesDocumentedSamplingPolicy() {+ let request = AppGenerationRequest(modelDirectory: existingDirectory, prompt: "hello")+ #expect(request.maxNewTokens == 1_024)+ #expect(request.temperature == 0.1)+ #expect(request.topK == 64)+ #expect(request.topP == 0.95)+ #expect(request.repetitionPenalty == 1)+ #expect(!request.isPureGreedy)+ }++ @Test func temperatureZeroRemainsPureGreedyWithTruncationDefaults() {+ let request = AppGenerationRequest(modelDirectory: existingDirectory,+ prompt: "hello",+ temperature: 0)+ #expect(request.topK == 64)+ #expect(request.topP == 0.95)+ #expect(request.isPureGreedy)+ }++ @Test func emptyPromptRejected() {+ let request = AppGenerationRequest(modelDirectory: existingDirectory, prompt: " ")+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }++ @Test func invalidMaxTokensRejected() {+ let request = AppGenerationRequest(modelDirectory: existingDirectory,+ prompt: "hello", maxNewTokens: 0)+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }++ @Test func invalidSlotCountRejected() {+ var options = AppRuntimeOptions()+ options.expertCacheSlots = 7+ let request = AppGenerationRequest(modelDirectory: existingDirectory,+ prompt: "hello", runtimeOptions: options)+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }++ @Test func repetitionPenaltyBelowOneRejected() {+ let request = AppGenerationRequest(modelDirectory: existingDirectory,+ prompt: "hello", repetitionPenalty: 0.9)+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }++ @Test func invalidTopKRejected() {+ for topK in [0, 257] {+ let request = AppGenerationRequest(modelDirectory: existingDirectory,+ prompt: "hello", topK: topK)+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }+ }++ @Test func invalidTopPRejected() {+ let request = AppGenerationRequest(modelDirectory: existingDirectory,+ prompt: "hello", topP: 1.1)+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }++ @Test func stochasticTopPRequiresTopK() {+ let request = AppGenerationRequest(modelDirectory: existingDirectory,+ prompt: "hello", topK: nil, topP: 0.95)+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }++ @Test func missingModelDirectoryRejected() {+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: "/nonexistent/model.gturbo"),+ prompt: "hello")+ #expect(throws: AppInferenceError.self) {+ try request.validate()+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swiftnew file mode 100644index 00000000..006f1159--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift@@ -0,0 +1,141 @@+import Foundation+import Testing+import TurboFieldfareDecodeProtocol++@Suite struct DecodeProtocolTests {+ @Test func loadRequestRoundTripPreservesEveryPublicRuntimeOption() throws {+ let options = DecodeRuntimeOptions(+ expertCacheSlots: 32,+ expertCachePolicy: "lru",+ prefillEnabled: false,+ prefillChunkTokens: 64,+ turboQuantKVEnabled: true,+ rdadvisePolicy: "adaptive",+ modelVerification: "trusted-install")+ let request = DecodeLoadRequest(+ modelPath: "/tmp/model.gturbo",+ maxContextTokens: 8192,+ runtimeOptions: options,+ forceLogitsHead: true)++ let pipe = Pipe()+ try pipe.fileHandleForWriting.write(+ contentsOf: DecodeFrameCodec.encode(request))+ try pipe.fileHandleForWriting.close()+ let decoded = try DecodeFrameCodec.read(+ DecodeLoadRequest.self,+ from: pipe.fileHandleForReading)++ #expect(decoded.modelPath == request.modelPath)+ #expect(decoded.maxContextTokens == 8192)+ #expect(decoded.runtimeOptions == options)+ #expect(decoded.forceLogitsHead)+ }++ @Test func terminalEventRoundTripPreservesDiagnosticsAndMemory() throws {+ let runner = DecodeRunnerDiagnostics(+ cb1MillisecondsPerToken: 0.6,+ ioMillisecondsPerToken: 12,+ cb2MillisecondsPerToken: 0.4,+ headMillisecondsPerToken: 1.7,+ rdadviseMillisecondsPerToken: 0,+ rdadviseCallsPerToken: 0,+ rdadviseMegabytesPerToken: 0,+ rdadviseSkippedPerToken: 0,+ rdadviseFailures: 0)+ let event = DecodeServiceEvent(+ kind: .finished,+ generationID: UUID(),+ tokenCount: 256,+ promptTokenCount: 1_017,+ prefillSeconds: 10.2,+ timeToFirstTokenSeconds: 0.04,+ decodeSeconds: 7.7,+ tokensPerSecond: 33.2,+ currentMemoryBytes: 2_000_000_000,+ peakMemoryBytes: 2_100_000_000,+ runner: runner)+ let pipe = Pipe()+ try pipe.fileHandleForWriting.write(+ contentsOf: DecodeFrameCodec.encode(event))+ try pipe.fileHandleForWriting.close()+ let decoded = try DecodeFrameCodec.read(+ DecodeServiceEvent.self,+ from: pipe.fileHandleForReading)++ #expect(decoded.tokenCount == 256)+ #expect(decoded.promptTokenCount == 1_017)+ #expect(decoded.currentMemoryBytes == 2_000_000_000)+ #expect(decoded.peakMemoryBytes == 2_100_000_000)+ #expect(decoded.runner == runner)+ }++ @Test func prefillEventRoundTripPreservesProgress() throws {+ let event = DecodeServiceEvent(+ kind: .prefill,+ generationID: UUID(),+ sequence: 7,+ prefillDone: 128,+ prefillTotal: 514)+ let pipe = Pipe()+ try pipe.fileHandleForWriting.write(+ contentsOf: DecodeFrameCodec.encode(event))+ try pipe.fileHandleForWriting.close()++ let decoded = try DecodeFrameCodec.read(+ DecodeServiceEvent.self,+ from: pipe.fileHandleForReading)++ #expect(decoded.kind == .prefill)+ #expect(decoded.sequence == 7)+ #expect(decoded.prefillDone == 128)+ #expect(decoded.prefillTotal == 514)+ }++ @Test func decoderAcceptsAFrameSplitAcrossSingleByteWrites() throws {+ let event = DecodeServiceEvent(+ kind: .snapshot,+ generationID: UUID(),+ sequence: 1,+ textDelta: "caf\u{00E9}",+ tokenCount: 1)+ let frame = try DecodeFrameCodec.encode(event)+ let pipe = Pipe()+ for byte in frame {+ try pipe.fileHandleForWriting.write(contentsOf: Data([byte]))+ }+ try pipe.fileHandleForWriting.close()++ let decoded = try DecodeFrameCodec.read(+ DecodeServiceEvent.self,+ from: pipe.fileHandleForReading)++ #expect(decoded.sequence == 1)+ #expect(decoded.textDelta == "caf\u{00E9}")+ }++ @Test func oversizedPayloadIsRejectedBeforeEncoding() {+ let request = DecodeGenerationRequest(+ prompt: String(repeating: "x", count: DecodeFrameCodec.maximumPayloadBytes + 1),+ maxNewTokens: 1,+ maxContextTokens: 4_096,+ temperature: 0)++ #expect(throws: DecodeFrameError.self) {+ _ = try DecodeFrameCodec.encode(request)+ }+ }++ @Test func oversizedFrameIsRejectedBeforePayloadRead() throws {+ let pipe = Pipe()+ var count = UInt32(DecodeFrameCodec.maximumPayloadBytes + 1).littleEndian+ try pipe.fileHandleForWriting.write(contentsOf: withUnsafeBytes(of: &count) { Data($0) })+ try pipe.fileHandleForWriting.close()++ #expect(throws: DecodeFrameError.self) {+ _ = try DecodeFrameCodec.read(+ DecodeServiceEvent.self,+ from: pipe.fileHandleForReading)+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/FakeInferenceClientTests.swift b/Tests/TurboFieldfareApp/Core/Inference/FakeInferenceClientTests.swiftnew file mode 100644index 00000000..c132d90b--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/FakeInferenceClientTests.swift@@ -0,0 +1,93 @@+import Foundation+import Testing++@testable import TurboFieldfareAppCore++@Suite struct FakeInferenceClientTests {++ @MainActor+ @Test func installedModelSupportsLoadAndGenerationWithTestClient() async throws {+ let directory = try makeCompleteModelInstall("fake-runtime")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(+ modelDirectory: directory,+ client: FakeInferenceClient(eventDelay: .zero),+ installer: MockModelInstallerClient())++ #expect(model.isModelInstalled)+ #expect(model.loadState == .notLoaded)+ model.loadModel()+ try await waitForFakeClient { model.loadState.isReady }+ model.promptText = "Hello from the test"+ model.run()+ try await waitForFakeClient { model.diagnostics != nil && !model.isRunning }++ #expect(model.isModelInstalled)+ #expect(model.outputText.contains("Simulated response"))+ #expect(model.outputText.contains("Hello from the test"))+ #expect(model.diagnostics?.generatedTokens ?? 0 > 0)+ }++ @Test func fakeInferenceCancellationEmitsCancelledEvent() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(5))+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: "/missing/fake-model"),+ prompt: "Cancel this simulated response")+ try await client.ensureLoaded(+ modelDirectory: request.modelDirectory,+ maxContextTokens: request.maxContextTokens,+ options: request.runtimeOptions,+ forceLogitsHead: !request.isPureGreedy,+ onState: { _ in })+ var sawCancellation = false++ do {+ for try await event in client.generate(request) {+ if case .token = event {+ client.cancel()+ } else if case .cancelled = event {+ sawCancellation = true+ }+ }+ } catch AppInferenceError.cancelled {+ }++ #expect(sawCancellation)+ }++ @Test func fakeInferenceRejectsConcurrentGeneration() async throws {+ let client = FakeInferenceClient(eventDelay: .milliseconds(20))+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: "/missing/fake-model"),+ prompt: "First")+ try await client.ensureLoaded(+ modelDirectory: request.modelDirectory,+ maxContextTokens: request.maxContextTokens,+ options: request.runtimeOptions,+ forceLogitsHead: !request.isPureGreedy,+ onState: { _ in })+ let first = client.generate(request)+ let second = client.generate(request)+ var failure: AppInferenceError?+ do {+ for try await event in second {+ if case .failed(let error, _) = event { failure = error }+ }+ } catch let error as AppInferenceError {+ failure = failure ?? error+ }+ #expect(failure == .generationInFlight)+ client.cancel()+ _ = first+ }++ @MainActor+ private func waitForFakeClient(_ predicate: @escaping @MainActor () -> Bool) async throws {+ for _ in 0..<200 {+ if predicate() { return }+ try await Task.sleep(for: .milliseconds(5))+ }+ Issue.record("timed out waiting for fake client state")+ }++}diff --git a/Tests/TurboFieldfareApp/Core/Inference/GenerationTranscriptMailboxTests.swift b/Tests/TurboFieldfareApp/Core/Inference/GenerationTranscriptMailboxTests.swiftnew file mode 100644index 00000000..29db93f8--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/GenerationTranscriptMailboxTests.swift@@ -0,0 +1,37 @@+import Testing+@testable import TurboFieldfareAppCore++@Suite struct GenerationTranscriptMailboxTests {+ @Test func drainIsLosslessAndExactlyOnce() {+ let mailbox = GenerationTranscriptMailbox()+ mailbox.append("alpha")+ mailbox.append(" beta")++ let first = mailbox.drain()+ #expect(first.pendingText == "alpha beta")+ #expect(first.completeText == "alpha beta")++ let second = mailbox.drain()+ #expect(second.pendingText.isEmpty)+ #expect(second.completeText == "alpha beta")+ }++ @Test func UnicodeSuffixesRemainLossless() {+ let mailbox = GenerationTranscriptMailbox()+ mailbox.append("Fieldfare ")+ mailbox.append("\u{1F426}\u{200D}\u{2B1B}")+ mailbox.append(" caf\u{00E9}")++ #expect(mailbox.drain().completeText == "Fieldfare \u{1F426}\u{200D}\u{2B1B} caf\u{00E9}")+ }++ @Test func resetClearsPendingAndCanonicalText() {+ let mailbox = GenerationTranscriptMailbox()+ mailbox.append("old")+ mailbox.reset()++ let snapshot = mailbox.drain()+ #expect(snapshot.pendingText.isEmpty)+ #expect(snapshot.completeText.isEmpty)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift b/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swiftnew file mode 100644index 00000000..8c422aff--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift@@ -0,0 +1,213 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareAppCore++/// Model-free state coverage for the real client: load failure surfaces+/// before any network or Metal work, idle cancel is a no-op, and a bad+/// request fails the stream with a typed error.+@Suite struct RealInferenceClientStateTests {+ @Test func generationRegistryScopesTerminationToOwningID() async {+ let registry = GenerationTaskRegistry()+ let first = UUID()+ let second = UUID()+ #expect(registry.reserve(first))+ registry.clear(first)+ #expect(registry.reserve(second))+ let secondTask = Task<Void, Never> {+ do { try await Task.sleep(for: .seconds(10)) } catch {}+ }+ registry.attach(secondTask, to: second)++ #expect(registry.take(first) == nil)+ #expect(!secondTask.isCancelled)+ registry.take(second)?.cancel()+ #expect(secondTask.isCancelled)+ }++ @Test func generationRegistryRejectsConcurrentReservationAndClearsByOwner() {+ let registry = GenerationTaskRegistry()+ let first = UUID()+ let second = UUID()+ #expect(registry.reserve(first))+ #expect(!registry.reserve(second))+ registry.clear(second)+ #expect(!registry.reserve(second))+ registry.clear(first)+ #expect(registry.reserve(second))+ registry.clear(second)+ }++ @Test func generationRegistryCancelsTaskAttachedAfterReservationEnded() async {+ let registry = GenerationTaskRegistry()+ let id = UUID()+ #expect(registry.reserve(id))+ registry.clear(id)+ let task = Task<Void, Never> {+ do { try await Task.sleep(for: .seconds(10)) } catch {}+ }+ registry.attach(task, to: id)+ #expect(task.isCancelled)+ let next = UUID()+ #expect(registry.reserve(next))+ registry.clear(next)+ }++ @Test func generationRunnerPolicyKeepsFusionHeadForPureGreedyChunkedPrefill() {+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"),+ prompt: "hello",+ temperature: 0,+ repetitionPenalty: 1)++ #expect(!RealInferenceSession.forceLogitsHead(for: request))+ }++ @Test func generationRunnerPolicyForcesLogitsForSamplingChunkedPrefill() {+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"),+ prompt: "hello",+ temperature: 0.7,+ repetitionPenalty: 1)++ #expect(RealInferenceSession.forceLogitsHead(for: request))+ }++ @Test func generationConfigCarriesDocumentedSamplingPolicy() {+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"),+ prompt: "hello")++ let config = RealInferenceSession.generationConfig(for: request)+ #expect(config.temperature == 0.1)+ #expect(config.topK == 64)+ #expect(config.topP == 0.95)+ #expect(config.repetitionPenalty == 1)+ }++ @Test func tokenizerDirectoryCacheReloadsOnlyWhenModelDirectoryChanges() {+ var cache = TokenizerDirectoryCache()+ let first = URL(fileURLWithPath: "/tmp/first.gturbo")+ let second = URL(fileURLWithPath: "/tmp/second.gturbo")++ #expect(cache.shouldReload(for: first))+ cache.markLoaded(for: first)+ #expect(!cache.shouldReload(for: first))+ #expect(cache.shouldReload(for: second))+ cache.clear()+ #expect(cache.shouldReload(for: first))+ }++ @Test func generateWithoutLoadedModelFailsWithoutPartialDiagnostics() async throws {+ let client = RealInferenceClient()+ let modelDirectory = FileManager.default.temporaryDirectory+ .appendingPathComponent("gturbo-prefill-off-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: modelDirectory,+ withIntermediateDirectories: false)+ defer { try? FileManager.default.removeItem(at: modelDirectory) }+ let request = AppGenerationRequest(+ modelDirectory: modelDirectory,+ prompt: "hello",+ runtimeOptions: AppRuntimeOptions(prefillEnabled: false,+ turboQuantKVEnabled: true))++ var failure: AppInferenceError?+ var partial: AppDiagnostics?+ do {+ for try await event in client.generate(request) {+ if case .failed(let error, let diagnostics) = event {+ failure = error+ partial = diagnostics+ }+ }+ } catch let error as AppInferenceError {+ failure = failure ?? error+ } catch {+ Issue.record("unexpected error type: \(error)")+ }++ #expect(failure != nil)+ #expect(partial == nil)+ }++ @Test func ensureLoadedFailsFastForMissingDirectory() async {+ let client = RealInferenceClient()+ var states: [AppModelLoadState] = []+ let recorder = StateRecorder()++ await #expect(throws: AppInferenceError.self) {+ try await client.ensureLoaded(+ modelDirectory: URL(fileURLWithPath: "/nonexistent/model.gturbo"),+ maxContextTokens: 1024,+ options: AppRuntimeOptions(),+ forceLogitsHead: false,+ onState: { recorder.append($0) })+ }+ states = recorder.snapshot()+ #expect(states.first == .loading(.validatingDirectory))+ #expect(states.last?.isFailed == true)+ #expect(!states.contains(.loading(.tokenizer)))+ }++ @Test func generateWithMissingDirectoryFailsStream() async {+ let client = RealInferenceClient()+ let request = AppGenerationRequest(+ modelDirectory: URL(fileURLWithPath: "/nonexistent/model.gturbo"),+ prompt: "hello")++ var failure: AppInferenceError?+ do {+ for try await event in client.generate(request) {+ if case .failed(let error, _) = event { failure = error }+ }+ } catch let error as AppInferenceError {+ failure = failure ?? error+ } catch {+ Issue.record("unexpected error type: \(error)")+ }+ #expect(failure == .modelNotFound("/nonexistent/model.gturbo"))+ }++ @Test func prefillFailureDiagnosticsMarksUnsupportedModeAndReason() {+ let config = PrefillRuntimeConfig.production(chunkTokens: 32)++ let diagnostics = RealInferenceSession.prefillFailureDiagnostics(+ config: config,+ kvStorageMode: .fp16,+ reason: "chunked prefill synthetic unsupported diagnostic")++ #expect(diagnostics.requestedMode == .chunked)+ #expect(diagnostics.executedMode == .unsupported)+ #expect(diagnostics.chunkCompleteness == .unsupported)+ #expect(diagnostics.kvStorageMode == .fp16)+ #expect(diagnostics.unsupportedReason?.contains("synthetic unsupported") == true)+ }++ @Test func cancelWhenIdleIsNoOp() {+ let client = RealInferenceClient()+ client.cancel()+ client.cancel()+ }++ @Test func unloadWhenIdleIsSafe() async {+ let client = RealInferenceClient()+ await client.unload()+ }+}++private final class StateRecorder: @unchecked Sendable {+ private let lock = NSLock()+ private var states: [AppModelLoadState] = []++ func append(_ state: AppModelLoadState) {+ lock.lock()+ states.append(state)+ lock.unlock()+ }++ func snapshot() -> [AppModelLoadState] {+ lock.lock()+ defer { lock.unlock() }+ return states+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallFixture.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallFixture.swiftnew file mode 100644index 00000000..92a77e3a--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallFixture.swift@@ -0,0 +1,72 @@+import Darwin+import Foundation+import TurboFieldfare++func makeCompleteModelInstall(_ tag: String) throws -> URL {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("turbofieldfare-complete-\(tag)-\(UUID().uuidString).gturbo")+ let experts = directory.appendingPathComponent("packed_experts", isDirectory: true)+ try FileManager.default.createDirectory(at: experts, withIntermediateDirectories: true)+ try Data("{}".utf8).write(to: experts.appendingPathComponent("layout.json"))++ let arch = ArchConfig.gemma4_26B_A4B+ var files: [String: Any] = [+ "model_weights.bin": ["size": 0, "sha256": String(repeating: "0", count: 64)],+ "packed_experts/layout.json": ["size": 2, "sha256": String(repeating: "0", count: 64)],+ ]+ for layer in 0..<arch.numLayers {+ files[String(format: "packed_experts/layer_%02d.bin", layer)] = [+ "size": 0,+ "sha256": String(repeating: "0", count: 64),+ ]+ }+ let manifest: [String: Any] = [+ "magic": "GTURBO",+ "versionMajor": 1,+ "versionMinor": 0,+ "flags": ["streamingPresent": true],+ "modelID": "test/gemma-4-26b-a4b",+ "arch": [+ "hiddenSize": arch.hiddenSize,+ "ffnIntermediate": arch.intermediateSize,+ "moeIntermediateSize": arch.moeIntermediateSize,+ "numHeads": arch.numHeads,+ "numKVHeads": arch.numKVHeads,+ "numFullKVHeads": arch.numFullKVHeads,+ "headDim": arch.headDim,+ "fullHeadDim": arch.fullHeadDim,+ "vocabSize": arch.vocabSize,+ "slidingWindow": arch.slidingWindow,+ "finalLogitSoftcap": arch.finalLogitSoftcap,+ "ropeTheta": arch.ropeTheta,+ "fullRopeTheta": arch.fullRopeTheta,+ "partialRotaryFactor": arch.partialRotaryFactor,+ "numLayers": arch.numLayers,+ "numExperts": arch.numExperts,+ "topKExperts": arch.topKExperts,+ "tieWordEmbeddings": arch.tieWordEmbeddings,+ "attentionKEqV": arch.attentionKEqV,+ "hiddenActivation": arch.hiddenActivation,+ "fullAttentionLayerMask": arch.fullAttentionLayerMask.map(Int.init),+ ],+ "files": files,+ "expertsPerLayer": arch.numExperts,+ "numLayers": arch.numLayers,+ "expertStride": UInt64(getpagesize()),+ ]+ let manifestData = try JSONSerialization.data(withJSONObject: manifest, options: [.sortedKeys])+ let manifestURL = directory.appendingPathComponent("manifest.json")+ try manifestData.write(to: manifestURL)+ let manifestHash = Sha256Verifier.hashData(manifestData)+ let receipt: [String: Any] = [+ "schemaVersion": 1,+ "manifestSha256": manifestHash,+ "modelDirectoryPath": directory.standardizedFileURL.path,+ "verificationTimestamp": "2026-07-11T00:00:00Z",+ "toolVersion": "TurboFieldfareAppCoreTests",+ "files": [:],+ ]+ let receiptData = try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys])+ try receiptData.write(to: directory.appendingPathComponent("verified-install.json"))+ return directory+}diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swiftnew file mode 100644index 00000000..e59f19d9--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift@@ -0,0 +1,189 @@+import Foundation+import Testing+import TurboFieldfareRepackCore++@testable import TurboFieldfareAppCore++@Suite struct AppModelInstallTests {++ @MainActor+ @Test func missingModelCanInstall() {+ let installer = MockModelInstallerClient()+ let directory = temporaryInstallPath("missing")+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: installer)++ #expect(!model.isModelInstalled)+ #expect(model.requiresModelInstallation)+ #expect(model.canInstallModel)+ }++ @MainActor+ @Test func installedModelShowsLoadNotInstall() throws {+ let directory = try makeCompleteModelInstall("installed")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient())++ #expect(model.isModelInstalled)+ #expect(!model.requiresModelInstallation)+ #expect(!model.canInstallModel)+ #expect(model.canLoadModel)+ }++ @MainActor+ @Test func defaultInstallDescriptorMatchesPinnedAudit() {+ let descriptor = AppModelInstallDescriptor.default+ #expect(descriptor.displayName == "gemma-4-26B-A4B-TurboQuant-MLX-4bit")+ #expect(descriptor.repoID == "majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit")+ #expect(descriptor.revision == "cc499c86a958ea7f05cffaa91c7e7243240dabbe")+ #expect(descriptor.approximateDownloadBytes == 14_952_958_284)+ #expect(descriptor.installedBytes == 14_527_372_034)+ #expect(descriptor.requiredFreeBytes == 15_668_222_722)+ }++ @MainActor+ @Test func insufficientSpaceDisablesInstallAndExposesShortfall() {+ let requirement = AppModelInstallRequirement(+ requiredBytes: 100,+ availableBytes: 40)+ let installer = MockModelInstallerClient(requirement: requirement)+ let model = AppModel(+ modelDirectory: temporaryInstallPath("space"),+ client: MockLifecycleInferenceClient(),+ installer: installer)++ #expect(model.installReadiness == .insufficientSpace(requirement))+ #expect(model.installRequirement?.shortfallBytes == 60)+ #expect(!model.canInstallModel)+ }++ @MainActor+ @Test func installProgressUpdatesStatusAndByteCounts() async throws {+ let directory = temporaryInstallPath("progress")+ let installer = MockModelInstallerClient(+ events: [+ .checking,+ .copyingPayload(doneBytes: 4, totalBytes: 10),+ ], holdOpen: true)+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: installer)+ model.installModel()++ try await waitUntil { model.installState == .copyingPayload(doneBytes: 4, totalBytes: 10) }+ #expect(model.installDownloadedBytes == 4)+ #expect(model.installTotalBytes == 10)+ #expect(model.installProgressFraction == 0.4)+ #expect(model.presentation.label == "Downloading model")+ model.cancelInstall()+ try await waitUntil { model.installState == .cancelled }+ }++ @MainActor+ @Test func installCompletionStopsUnloaded() async throws {+ let requestedDirectory = temporaryInstallPath("requested")+ let completedDirectory = try makeCompleteModelInstall("complete")+ defer { try? FileManager.default.removeItem(at: completedDirectory) }+ let client = MockLifecycleInferenceClient()+ let installer = MockModelInstallerClient(events: [.installed(completedDirectory)])+ let model = AppModel(+ modelDirectory: requestedDirectory,+ client: client,+ installer: installer)++ model.installModel()+ try await waitUntil {+ model.installState == .installed(modelDirectory: completedDirectory.standardizedFileURL)+ }+ #expect(+ model.installState == .installed(modelDirectory: completedDirectory.standardizedFileURL))+ #expect(model.modelPathText == completedDirectory.standardizedFileURL.path)+ #expect(model.loadState == .notLoaded)+ #expect(model.canLoadModel)+ #expect(client.ensureLoadedCallCount() == 0)+ }++ @MainActor+ @Test func installFailureDoesNotAttemptLoad() async throws {+ struct SyntheticError: Error {}+ let client = MockLifecycleInferenceClient()+ let installer = MockModelInstallerClient(failure: SyntheticError())+ let model = AppModel(+ modelDirectory: temporaryInstallPath("failure"),+ client: client,+ installer: installer)+ model.installModel()++ try await waitUntil {+ if case .failed = model.installState { return true }+ return false+ }+ #expect(model.loadState == .notLoaded)+ #expect(client.ensureLoadedCallCount() == 0)+ }++ @MainActor+ @Test func diskFailureKeepsExactRequirementAndShortfall() async throws {+ let error = RepackError.diskSpaceInsufficient(+ path: "/volume",+ required: 120,+ available: 45)+ let installer = MockModelInstallerClient(failure: error)+ let model = AppModel(+ modelDirectory: temporaryInstallPath("disk-failure"),+ client: MockLifecycleInferenceClient(),+ installer: installer)+ model.installModel()++ try await waitUntil {+ if case .failed = model.installState { return true }+ return false+ }++ let expected = AppModelInstallRequirement(+ requiredBytes: 120,+ availableBytes: 45)+ #expect(model.installReadiness == .insufficientSpace(expected))+ #expect(model.installRequirement?.shortfallBytes == 75)+ }++ @MainActor+ @Test func cancelInstallWaitsForAcknowledgementAndAllowsRetry() async throws {+ let installer = MockModelInstallerClient(events: [.downloadingMetadata], holdOpen: true)+ let model = AppModel(+ modelDirectory: temporaryInstallPath("cancel"),+ client: MockLifecycleInferenceClient(),+ installer: installer)+ model.installModel()+ try await waitUntil { model.installState == .downloadingMetadata }++ model.cancelInstall()+ #expect(installer.cancelCalled)+ #expect(model.installState == .cancelling || model.installState == .cancelled)+ try await waitUntil { model.installState == .cancelled }++ #expect(model.loadState == .notLoaded)+ #expect(model.canInstallModel)+ }++ private func temporaryInstallPath(_ tag: String) -> URL {+ FileManager.default.temporaryDirectory+ .appendingPathComponent("turbofieldfare-app-install-\(tag)-\(UUID().uuidString).gturbo")+ }++ @MainActor+ private func waitUntil(_ predicate: @escaping @MainActor () -> Bool) async throws {+ for _ in 0..<200 {+ if predicate() { return }+ try await Task.sleep(for: .milliseconds(5))+ }+ Issue.record("timed out waiting for condition")+ }++}diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swiftnew file mode 100644index 00000000..877a6ac7--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift@@ -0,0 +1,42 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppModelInstallationProbeTests {+ @Test func missingDirectoryIsMissing() {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("turbofieldfare-missing-\(UUID().uuidString).gturbo")+ #expect(AppModelInstallationProbe.status(at: url) == .missing)+ }++ @Test func manifestWithoutFinalMetadataIsPartial() throws {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("turbofieldfare-partial-\(UUID().uuidString).gturbo")+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: url) }+ try Data("{}".utf8).write(to: url.appendingPathComponent("manifest.json"))+ guard case .partial = AppModelInstallationProbe.status(at: url) else {+ Issue.record("expected partial status")+ return+ }+ }++ @Test func validBoundedMetadataIsComplete() throws {+ let url = try makeCompleteModelInstall("probe")+ defer { try? FileManager.default.removeItem(at: url) }+ #expect(AppModelInstallationProbe.status(at: url) == .complete)+ }++ @Test func receiptBoundToDifferentPathIsPartial() throws {+ let url = try makeCompleteModelInstall("wrong-path")+ defer { try? FileManager.default.removeItem(at: url) }+ let receiptURL = url.appendingPathComponent("verified-install.json")+ var receipt = try JSONSerialization.jsonObject(with: Data(contentsOf: receiptURL)) as! [String: Any]+ receipt["modelDirectoryPath"] = "/different/model.gturbo"+ try JSONSerialization.data(withJSONObject: receipt, options: [.sortedKeys]).write(to: receiptURL)+ guard case .partial = AppModelInstallationProbe.status(at: url) else {+ Issue.record("expected partial status")+ return+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelLocationTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelLocationTests.swiftnew file mode 100644index 00000000..a74103d6--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelLocationTests.swift@@ -0,0 +1,47 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppModelLocationTests {+ @Test func explicitURLWins() {+ let result = AppModelLocation.resolve(+ explicitURL: URL(fileURLWithPath: "/models/explicit.gturbo"),+ executableURL: nil,+ currentDirectoryURL: URL(fileURLWithPath: "/repo"),+ applicationSupportURL: URL(fileURLWithPath: "/support"),+ fileExists: { _ in false })+ #expect(result.path == "/models/explicit.gturbo")+ }++ @Test func executableAncestorFindsPackageRootOutsideCWD() {+ let files: Set<String> = ["/repo/Package.swift", "/repo/Sources/TurboFieldfareApp/Mac"]+ let result = AppModelLocation.resolve(+ explicitURL: nil,+ executableURL: URL(fileURLWithPath: "/repo/.build/debug/TurboFieldfareMac"),+ currentDirectoryURL: URL(fileURLWithPath: "/elsewhere"),+ applicationSupportURL: URL(fileURLWithPath: "/support"),+ fileExists: files.contains)+ #expect(result.path == "/repo/scratch/gemma4.gturbo")+ }++ @Test func currentDirectoryCanBePackageRoot() {+ let files: Set<String> = ["/repo/Package.swift", "/repo/Sources/TurboFieldfareApp/Mac"]+ let result = AppModelLocation.resolve(+ explicitURL: nil,+ executableURL: nil,+ currentDirectoryURL: URL(fileURLWithPath: "/repo"),+ applicationSupportURL: URL(fileURLWithPath: "/support"),+ fileExists: files.contains)+ #expect(result.path == "/repo/scratch/gemma4.gturbo")+ }++ @Test func standaloneAppFallsBackToApplicationSupport() {+ let result = AppModelLocation.resolve(+ explicitURL: nil,+ executableURL: URL(fileURLWithPath: "/Applications/TurboFieldfareMac"),+ currentDirectoryURL: URL(fileURLWithPath: "/"),+ applicationSupportURL: URL(fileURLWithPath: "/support"),+ fileExists: { _ in false })+ #expect(result.path == "/support/TurboFieldfare/gemma4.gturbo")+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Installation/RepackModelInstallerClientTests.swift b/Tests/TurboFieldfareApp/Core/Installation/RepackModelInstallerClientTests.swiftnew file mode 100644index 00000000..aa87b95e--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Installation/RepackModelInstallerClientTests.swift@@ -0,0 +1,72 @@+import Foundation+@testable import TurboFieldfareRepackCore+import Synchronization+import Testing+@testable import TurboFieldfareAppCore++@Suite struct RepackModelInstallerClientTests {+ @Test func mapsCoreProgressAndCompletion() async throws {+ let output = FileManager.default.temporaryDirectory+ .appendingPathComponent("scripted.gturbo")+ let client = RepackModelInstallerClient { outputDirectory, progress in+ progress(.downloadingMetadata)+ progress(.planning(downloadBytes: 10, outputBytes: 20))+ progress(.checkingDisk(DiskSpaceRequirement(path: "/",+ requiredBytes: 30,+ availableBytes: 40)))+ progress(.reservingOutput(bytes: 20))+ progress(.copyingPayload(downloadedBytes: 4, totalBytes: 10))+ progress(.hashingOutput("model_weights.bin"))+ progress(.finalizing)+ return outputDirectory+ }++ var events: [AppModelInstallEvent] = []+ for try await event in client.installDefaultModel(outputDirectory: output) {+ events.append(event)+ }++ #expect(events == [+ .checking,+ .downloadingMetadata,+ .planning,+ .checking,+ .reservingOutput,+ .copyingPayload(doneBytes: 4, totalBytes: 10),+ .hashingOutput("model_weights.bin"),+ .finalizing,+ .installed(output.standardizedFileURL),+ ])+ }++ @Test func cancelPropagatesCancellationToConsumer() async throws {+ let started = Flag()+ let client = RepackModelInstallerClient { outputDirectory, progress in+ progress(.downloadingMetadata)+ started.set()+ try await Task.sleep(for: .seconds(60))+ return outputDirectory+ }+ let output = FileManager.default.temporaryDirectory+ .appendingPathComponent("cancelled.gturbo")+ let consume = Task {+ for try await _ in client.installDefaultModel(outputDirectory: output) {}+ }++ for _ in 0..<200 where !started.value {+ await Task.yield()+ }+ #expect(started.value)+ client.cancel()++ await #expect(throws: CancellationError.self) {+ try await consume.value+ }+ }+}++private final class Flag: Sendable {+ private let storage = Mutex(false)+ var value: Bool { storage.withLock { $0 } }+ func set() { storage.withLock { $0 = true } }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swiftnew file mode 100644index 00000000..6f2ff6c2--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift@@ -0,0 +1,203 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppModelLoadStateTests {+ @MainActor+ @Test func runRequiresReadyState() {+ let model = AppModel()+ model.promptText = "go"++ model.loadState = .notLoaded+ #expect(!model.canRun)+ model.loadState = .loading(.verifyingWeights)+ #expect(!model.canRun)+ model.loadState = .failed(.modelLoadFailed("boom"))+ #expect(!model.canRun)+ model.loadState = .ready(modelDirectory: URL(fileURLWithPath: "/tmp/m.gturbo"), loadSeconds: 1.2)+ #expect(model.canRun)+ }++ @MainActor+ @Test func canLoadModelOnlyFromNotLoadedOrFailed() throws {+ let directory = try makeCompleteModelInstall("can-load")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory)+ model.loadState = .notLoaded+ #expect(model.canLoadModel)+ model.loadState = .failed(.modelLoadFailed("boom"))+ #expect(model.canLoadModel)+ model.loadState = .loading(.tokenizer)+ #expect(!model.canLoadModel)+ model.loadState = .ready(modelDirectory: URL(fileURLWithPath: "/tmp/m.gturbo"), loadSeconds: 1.2)+ #expect(!model.canLoadModel)+ }++ @MainActor+ @Test func loadingStateBlocksRun() {+ let model = AppModel()+ model.promptText = "go"+ model.loadState = .loading(.preparingRunner)+ #expect(!model.canRun)+ #expect(model.loadState.isLoading)+ }++ @MainActor+ @Test func explicitLoadReloadAndUnloadActionsAreMutuallyExclusive() throws {+ let directory = try makeCompleteModelInstall("action-matrix")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory,+ client: MockLifecycleInferenceClient())+ #expect(model.canLoadModel)+ #expect(!model.canReloadModel)+ #expect(!model.canUnloadModel)++ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))+ #expect(!model.canLoadModel)+ #expect(model.canUnloadModel)++ model.runtimeOptions.turboQuantKVEnabled.toggle()+ #expect(model.canReloadModel)+ #expect(model.canUnloadModel)+ #expect(!model.canRun)+ }++ @MainActor+ @Test func unloadWaitsForLifecycleAndPreservesTranscript() async throws {+ let directory = try makeCompleteModelInstall("unload")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockLifecycleInferenceClient()+ client.suspendUnloads = true+ let model = AppModel(modelDirectory: directory, client: client)+ model.outputText = "keep me"+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))++ model.unloadModel()+ await client.waitForUnloadStart()+ #expect(model.loadState == .unloading)+ client.releaseUnloads()+ for _ in 0..<200 where model.loadState != .notLoaded {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ #expect(model.loadState == .notLoaded)+ #expect(model.outputText == "keep me")+ }++ @MainActor+ @Test func cancelLoadWaitsForUnloadAndRejectsLateReady() async throws {+ let directory = try makeCompleteModelInstall("cancel-load")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockLifecycleInferenceClient()+ client.suspendLoads = true+ client.suspendUnloads = true+ let model = AppModel(modelDirectory: directory, client: client)++ model.loadModel()+ await client.waitForLoadStart()+ for _ in 0..<200 where !model.canCancelLoad {+ try? await Task.sleep(for: .milliseconds(5))+ }+ model.cancelLoad()+ await client.waitForUnloadStart()+ #expect(model.loadState == .cancelling)++ client.emitLoadState(.ready(modelDirectory: directory, loadSeconds: 0), callIndex: 0)+ await Task.yield()+ #expect(model.loadState == .cancelling)++ client.releaseUnloads()+ for _ in 0..<200 where model.loadState != .notLoaded {+ try? await Task.sleep(for: .milliseconds(5))+ }+ #expect(model.loadState == .notLoaded)+ }++ @MainActor+ @Test func failedLoadIsRetryableAndOldAttemptCannotCompleteRetry() async throws {+ let directory = try makeCompleteModelInstall("retry-load")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockLifecycleInferenceClient()+ client.suspendLoads = true+ let model = AppModel(modelDirectory: directory, client: client)++ model.loadModel()+ await client.waitForLoadStart()+ client.failNextLoad(.modelLoadFailed("synthetic"))+ for _ in 0..<200 where !model.loadState.isFailed {+ try? await Task.sleep(for: .milliseconds(5))+ }+ #expect(model.loadState == .failed(.modelLoadFailed("synthetic")))+ #expect(model.canLoadModel)++ client.suspendLoads = true+ model.loadModel()+ await client.waitForLoadStart(2)+ client.emitLoadState(.ready(modelDirectory: directory, loadSeconds: 0), callIndex: 0)+ await Task.yield()+ #expect(model.loadState.isLoading)++ client.releaseLoads()+ for _ in 0..<200 where !model.loadState.isReady {+ try? await Task.sleep(for: .milliseconds(5))+ }+ #expect(model.loadState.isReady)+ #expect(client.ensureLoadedCallCount() == 2)+ }++ @MainActor+ @Test func loadModelWithoutLifecycleClientFails() throws {+ let directory = try makeCompleteModelInstall("no-lifecycle")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory, client: MockInferenceClient())+ model.loadModel()+ #expect(model.loadState.isFailed)+ }++ @MainActor+ @Test func applyLoadStateUpdatesPresentation() throws {+ let directory = try makeCompleteModelInstall("presentation")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory)+ model.applyLoadState(.loading(.verifyingWeights))+ #expect(model.presentation.label == AppModelLoadPhase.verifyingWeights.label)+ model.applyLoadState(.failed(.modelLoadFailed("boom")))+ #expect(model.presentation.detail == "Model load failed: boom")+ }++ @MainActor+ @Test func loadModelWaitsForPendingUnloadAfterModelPathChange() async throws {+ let client = MockLifecycleInferenceClient()+ client.suspendUnloads = true+ let oldURL = try makeCompleteModelInstall("old-load")+ let newURL = try makeCompleteModelInstall("new-load")+ defer {+ try? FileManager.default.removeItem(at: oldURL)+ try? FileManager.default.removeItem(at: newURL)+ }+ let model = AppModel(modelDirectory: oldURL, client: client)+ model.loadState = .ready(modelDirectory: oldURL, loadSeconds: 1)++ model.setModelURL(newURL)+ await client.waitForUnloadStart()+ model.loadModel()++ #expect(client.ensureLoadedCallCount() == 0)+ client.releaseUnloads()+ await client.waitForEnsureLoadedCallCount(1)+ #expect(client.ensureLoadedCallCount() == 1)+ }++ @MainActor+ @Test func staleReadyStateForOldModelPathIsIgnored() {+ let model = AppModel(client: MockInferenceClient())+ let oldURL = URL(fileURLWithPath: "/tmp/old.gturbo")+ let newURL = URL(fileURLWithPath: "/tmp/new.gturbo")+ model.modelPathText = oldURL.path++ model.setModelURL(newURL)+ model.applyLoadState(.ready(modelDirectory: oldURL, loadSeconds: 0))++ #expect(model.loadState == .notLoaded)+ #expect(model.loadedRuntimeKey == nil)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swiftnew file mode 100644index 00000000..2829809b--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift@@ -0,0 +1,55 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppModelServiceReportingTests {+ @MainActor+ @Test func serviceMemoryAndCanonicalTranscriptOverrideUIProcessState() {+ let client = ReportingInferenceClient(memoryBytes: 2_100_000_000)+ let model = AppModel(client: client)+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))+ client.generationTranscriptMailbox.append("lossless output")++ #expect(model.currentProcessMemoryBytes == 2_100_000_000)+ #expect(model.outputPlainText == "lossless output")++ model.clearOutput()+ #expect(client.generationTranscriptMailbox.completeText.isEmpty)+ }++ @MainActor+ @Test func startingAnotherRunClearsPreviousServiceTranscriptSynchronously() {+ let client = ReportingInferenceClient(memoryBytes: 2_100_000_000)+ let model = AppModel(client: client)+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))+ client.generationTranscriptMailbox.append("previous completion")+ model.promptText = "new prompt"++ model.run()++ #expect(client.generationTranscriptMailbox.completeText.isEmpty)+ #expect(model.outputPromptText == "new prompt")+ #expect(model.outputPlainText == "new prompt")+ }+}++private final class ReportingInferenceClient: AppInferenceClient,+ AppInferenceMemoryReporting, AppInferenceTranscriptReporting, @unchecked Sendable {+ let currentInferenceMemoryBytes: UInt64?+ let generationTranscriptMailbox = GenerationTranscriptMailbox()++ init(memoryBytes: UInt64) {+ currentInferenceMemoryBytes = memoryBytes+ }++ func generate(_ request: AppGenerationRequest)+ -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream { continuation in continuation.finish() }+ }++ func cancel() {}+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swiftnew file mode 100644index 00000000..7dc468ba--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift@@ -0,0 +1,285 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppModelTests {+ @MainActor+ @Test func defaultsUseSampledRequest() throws {+ let model = AppModel()+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.promptText = "go"++ let request = try model.makeRequest()+ #expect(request.temperature == 0.1)+ #expect(request.topK == 64)+ #expect(request.topP == 0.95)+ #expect(request.maxNewTokens == 1_024)+ #expect(request.repetitionPenalty == 1)+ #expect(!request.isPureGreedy)+ #expect(request.runtimeOptions.expertCacheSlots == 16)+ #expect(request.runtimeOptions.expertCachePolicy == .lfu)+ #expect(request.runtimeOptions.rdadvisePolicy == .off)+ #expect(!request.runtimeOptions.turboQuantKVEnabled)+ #expect(request.runtimeOptions.prefillEnabled)+ #expect(request.runtimeOptions.prefillChunkTokens == 128)+ #expect(request.runtimeOptions.modelVerification == .fullSha256)+ }++ @MainActor+ @Test func runDisabledWhenPromptEmpty() {+ let model = AppModel()+ model.loadState = .ready(modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1)+ model.promptText = " "+ #expect(!model.canRun)+ }++ @MainActor+ @Test func runDisabledUntilModelReady() {+ let model = AppModel()+ model.promptText = "go"+ #expect(!model.canRun)+ }++ @MainActor+ @Test func disabledRepetitionPenaltyNeutralizesRequest() throws {+ let model = AppModel()+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.promptText = "go"+ model.repetitionPenalty = 1.4++ model.repetitionPenaltyEnabled = true+ #expect(try model.makeRequest().repetitionPenalty == 1.4)+ model.repetitionPenaltyEnabled = false+ #expect(try model.makeRequest().repetitionPenalty == 1.0)+ }++ @MainActor+ @Test func disablingTopKNeutralizesBothTruncationControls() throws {+ let model = AppModel()+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.promptText = "go"+ model.topKEnabled = false+ model.topPEnabled = true++ let request = try model.makeRequest()+ #expect(request.topK == nil)+ #expect(request.topP == nil)+ }++ @MainActor+ @Test func prefillToggleSurvivesRequestCreation() throws {+ let model = AppModel()+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.promptText = "go"++ model.runtimeOptions.prefillEnabled = false+ #expect(try !model.makeRequest().runtimeOptions.prefillEnabled)++ model.runtimeOptions.prefillEnabled = true+ #expect(try model.makeRequest().runtimeOptions.prefillEnabled)+ }++ @MainActor+ @Test func adaptiveRDAdvicePolicySurvivesRequestCreation() throws {+ let model = AppModel()+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.promptText = "go"+ model.runtimeOptions.rdadvisePolicy = .adaptive++ let request = try model.makeRequest()+ #expect(request.runtimeOptions.rdadvisePolicy == .adaptive)+ }++ @MainActor+ @Test func loadAffectingRuntimeChangeMarksReadySessionStale() {+ let model = AppModel(client: MockLifecycleInferenceClient())+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))++ #expect(!model.hasStaleLoadedRuntime)+ model.runtimeOptions.turboQuantKVEnabled = true+ #expect(model.hasStaleLoadedRuntime)+ }++ @MainActor+ @Test func prefillChangeMarksReadySessionStale() {+ let model = AppModel(client: MockLifecycleInferenceClient())+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))++ model.runtimeOptions.prefillEnabled = false++ #expect(model.hasStaleLoadedRuntime)+ }++ @MainActor+ @Test func mockRunUpdatesOutputAndDiagnostics() async throws {+ let client = MockInferenceClient(response: "alpha beta", tokenDelayNanos: 1)+ let model = AppModel(client: client)+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.loadState = .ready(modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1)+ model.promptText = "go"+ model.maxNewTokens = 4+ model.run()++ for _ in 0..<200 where model.isRunning {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }++ #expect(!model.isRunning)+ #expect(model.outputText.contains("alpha beta"))+ #expect(model.diagnostics != nil)+ #expect(model.error == nil)+ }++ @MainActor+ @Test func runSnapshotsPromptIntoOutputTranscript() async throws {+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)+ let model = readyModel(client: client)+ model.promptText = "original prompt"+ model.maxNewTokens = 1+ model.run()++ #expect(model.outputPromptText == "original prompt")+ #expect(model.hasOutputTranscript)+ #expect(model.outputPlainText == "original prompt")++ model.promptText = "edited prompt"+ await waitForIdle(model)++ #expect(model.outputPromptText == "original prompt")+ #expect(model.outputPlainText == "original promptanswer")+ #expect(model.outputPlainText.contains("original prompt"))+ #expect(!model.outputPlainText.contains("edited prompt"))+ }++ @MainActor+ @Test func staleReadySessionDisablesGenerationUntilReload() throws {+ let client = MockLifecycleInferenceClient()+ let directory = try makeCompleteModelInstall("stale-runtime")+ defer { try? FileManager.default.removeItem(at: directory) }+ let model = AppModel(modelDirectory: directory, client: client)+ model.promptText = "go"+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))++ #expect(model.canRun)+ model.runtimeOptions.turboQuantKVEnabled = true+ #expect(model.hasStaleLoadedRuntime)+ #expect(!model.canRun)+ #expect(model.canReloadModel)+ #expect(client.ensureLoadedCallCount() == 0)+ }++ @MainActor+ @Test func cancelAfterPartialOutputCanBeCleared() async throws {+ let client = MockInferenceClient(response: "one two three four five", tokenDelayNanos: 20_000_000)+ client.prefillSteps = 0+ let model = readyModel(client: client)+ model.promptText = "stop after token"+ model.maxNewTokens = 10+ model.run()++ for _ in 0..<200 where model.liveTokenCount == 0 {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }++ #expect(model.liveTokenCount > 0)+ model.cancel()+ #expect(model.isCancellationPending)+ await waitForIdle(model)++ #expect(!model.isRunning)+ #expect(!model.isCancellationPending)+ #expect(model.error == .cancelled)+ #expect(model.hasOutputTranscript)++ model.clearOutput()+ #expect(!model.hasOutputTranscript)+ #expect(model.outputPromptText.isEmpty)+ #expect(model.outputText.isEmpty)+ #expect(model.error == nil)+ }++ @MainActor+ @Test func cancelDuringPrefillKeepsPromptSnapshotUntilClear() async throws {+ let client = MockInferenceClient(response: "unused", tokenDelayNanos: 1_000_000)+ client.prefillSteps = 20+ let model = readyModel(client: client)+ model.promptText = "prefill prompt"+ model.run()++ for _ in 0..<200 where model.livePrefillDone == 0 {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }++ #expect(model.outputPromptText == "prefill prompt")+ model.cancel()+ await waitForIdle(model)++ #expect(!model.isRunning)+ #expect(model.outputPromptText == "prefill prompt")+ #expect(model.outputText.isEmpty)+ #expect(model.hasOutputTranscript)++ model.clearOutput()+ #expect(!model.hasOutputTranscript)+ }++ @MainActor+ @Test func failedEventThenThrownErrorKeepsFirstTerminalState() async throws {+ let client = MockInferenceClient(tokenDelayNanos: 1, failureMessage: "synthetic failure")+ let model = readyModel(client: client)+ model.promptText = "fail"++ model.run()+ await waitForIdle(model)++ #expect(model.error?.userMessage == "synthetic failure")+ #expect(model.diagnostics?.stopReason == .failed)+ }++ @MainActor+ @Test func changingModelPathInvalidatesLoadedStateAndDiagnostics() {+ let model = AppModel(client: MockInferenceClient())+ let oldURL = FileManager.default.temporaryDirectory.appendingPathComponent("old.gturbo")+ let newURL = FileManager.default.temporaryDirectory.appendingPathComponent("new.gturbo")+ model.modelPathText = oldURL.path+ model.loadState = .ready(modelDirectory: oldURL, loadSeconds: 1)+ model.diagnostics = AppDiagnostics(+ generatedTokens: 1,+ stopReason: .eos,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 1,+ tokensPerSecond: 1,+ peakMemoryBytes: nil,+ runtimeOptions: AppRuntimeOptions())+ model.error = .unknown("old error")++ model.setModelURL(newURL)++ #expect(model.modelPathText == newURL.standardizedFileURL.path)+ #expect(model.loadState == .notLoaded)+ #expect(model.loadedRuntimeKey == nil)+ #expect(model.diagnostics == nil)+ #expect(model.error == nil)+ #expect(model.presentation.label == "Model required")+ #expect(!model.canRun)+ }++ @MainActor+ private func readyModel(client: MockInferenceClient) -> AppModel {+ let model = AppModel(client: client)+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.loadState = .ready(modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1)+ return model+ }++ @MainActor+ private func waitForIdle(_ model: AppModel) async {+ for _ in 0..<200 where model.isRunning {+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ }+}diff --git a/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swiftnew file mode 100644index 00000000..fc75a078--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift@@ -0,0 +1,116 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppPresentationStateTests {+ @Test func staleReadyPrecedesLastRun() {+ var snapshot = Self.installedSnapshot(loadState: .ready(+ modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"), loadSeconds: 1))+ snapshot.hasStaleRuntime = true+ snapshot.lastStopReason = .maxTokens+ let state = AppPresentationState.resolve(snapshot)+ #expect(state.label == "Reload required")+ }++ @Test func loadFailureIsVisibleAndRetryable() {+ let state = AppPresentationState.resolve(Self.installedSnapshot(+ loadState: .failed(.modelLoadFailed("synthetic"))))+ #expect(state.label == "Model load failed")+ #expect(state.detail == "Model load failed: synthetic")+ #expect(state.severity == .error)+ }++ @Test func readinessFailureIsStoppedNotActive() {+ var snapshot = Self.installedSnapshot(loadState: .notLoaded)+ snapshot.requiresInstallation = true+ snapshot.installReadiness = .failed("disk probe failed")+ let state = AppPresentationState.resolve(snapshot)+ #expect(state.label == "Storage check failed")+ #expect(state.detail == "disk probe failed")+ #expect(!state.showsActivity)+ }++ @Test func activeLifecycleStatesHaveExpectedPresentation() {+ var snapshot = Self.installedSnapshot(loadState: .loading(.tokenizer))+ var state = AppPresentationState.resolve(snapshot)+ #expect(state.showsActivity)++ snapshot.loadState = .unloading+ state = AppPresentationState.resolve(snapshot)+ #expect(state.label == "Unloading model")+ }++ @Test func installedAndReadyStatesHaveExpectedLabels() {+ var snapshot = Self.installedSnapshot(loadState: .notLoaded)+ var state = AppPresentationState.resolve(snapshot)+ #expect(state.label == "Installed · Not loaded")++ snapshot.loadState = .ready(modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"),+ loadSeconds: 1)+ state = AppPresentationState.resolve(snapshot)+ #expect(state.label == "Ready")+ }++ @Test func lifecyclePriorityTable() {+ let ready = AppModelLoadState.ready(+ modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"), loadSeconds: 1)+ var cases: [(AppPresentationSnapshot, String, Bool)] = []++ var snapshot = Self.installedSnapshot(loadState: .notLoaded)+ snapshot.requiresInstallation = true+ snapshot.installState = .checking+ cases.append((snapshot, "Checking installation", true))+ snapshot.installState = .cancelling+ cases.append((snapshot, "Cancelling installation", true))+ snapshot.installState = .cancelled+ cases.append((snapshot, "Installation cancelled", false))+ snapshot.installState = .failed("network")+ cases.append((snapshot, "Installation failed", false))++ snapshot = Self.installedSnapshot(loadState: .cancelling)+ cases.append((snapshot, "Cancelling load", true))+ snapshot.loadState = .unloading+ cases.append((snapshot, "Unloading model", true))++ snapshot = Self.installedSnapshot(loadState: ready)+ snapshot.isRunning = true+ snapshot.generationPhase = .prefill+ cases.append((snapshot, "Prefill", false))+ snapshot.generationPhase = .decode+ cases.append((snapshot, "Generating", false))+ snapshot.isGenerationCancellationPending = true+ cases.append((snapshot, "Stopping", true))++ for (input, label, activity) in cases {+ let state = AppPresentationState.resolve(input)+ #expect(state.label == label)+ #expect(state.showsActivity == activity)+ }+ }++ @Test func prefillProgressUsesCompactFractionLabel() {+ let ready = AppModelLoadState.ready(+ modelDirectory: URL(fileURLWithPath: "/tmp/model.gturbo"),+ loadSeconds: 1)+ var snapshot = Self.installedSnapshot(loadState: ready)+ snapshot.isRunning = true+ snapshot.generationPhase = .prefill+ snapshot.livePrefillDone = 128+ snapshot.livePrefillTotal = 514++ let state = AppPresentationState.resolve(snapshot)++ #expect(state.label == "Prefill (128/514)")+ }++ private static func installedSnapshot(loadState: AppModelLoadState) -> AppPresentationSnapshot {+ AppPresentationSnapshot(requiresInstallation: false,+ installState: .idle,+ installReadiness: .checking,+ loadState: loadState,+ hasStaleRuntime: false,+ isRunning: false,+ isGenerationCancellationPending: false,+ generationPhase: .idle)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swiftnew file mode 100644index 00000000..c6df5fe0--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/FakeInferenceClient.swift@@ -0,0 +1,163 @@+import Foundation+import Synchronization++@testable import TurboFieldfareAppCore++final class FakeInferenceClient: AppModelLifecycleClient, Sendable {+ private struct State: Sendable {+ var loadedKey: AppLoadedRuntimeKey?+ }++ private final class StateBox: Sendable {+ let value = Mutex(State())+ }++ private let state = StateBox()+ private let generationTasks = GenerationTaskRegistry()+ private let eventDelay: Duration++ init(eventDelay: Duration = .milliseconds(80)) {+ self.eventDelay = eventDelay+ }++ func ensureLoaded(modelDirectory: URL,+ maxContextTokens: Int,+ options: AppRuntimeOptions,+ forceLogitsHead: Bool,+ onState: @escaping @Sendable (AppModelLoadState) -> Void) async throws {+ let start = Date()+ onState(.loading(.validatingDirectory))+ try await Task.sleep(for: eventDelay)+ onState(.loading(.preparingRunner))+ try await Task.sleep(for: eventDelay)+ try Task.checkCancellation()+ state.value.withLock {+ $0.loadedKey = AppLoadedRuntimeKey(modelDirectory: modelDirectory,+ maxContextTokens: maxContextTokens,+ options: options,+ forceLogitsHead: forceLogitsHead)+ }+ onState(.ready(+ modelDirectory: modelDirectory.standardizedFileURL,+ loadSeconds: Date().timeIntervalSince(start)))+ }++ func unload() async {+ cancel()+ state.value.withLock { $0.loadedKey = nil }+ }++ func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream { continuation in+ do {+ try request.validate(requireModelDirectory: false)+ let expected = AppLoadedRuntimeKey(+ modelDirectory: request.modelDirectory,+ maxContextTokens: request.maxContextTokens,+ options: request.runtimeOptions,+ forceLogitsHead: !request.isPureGreedy)+ guard let loaded = state.value.withLock({ $0.loadedKey }) else {+ throw AppInferenceError.modelNotLoaded+ }+ guard loaded == expected else { throw AppInferenceError.reloadRequired }+ } catch {+ let appError = error as? AppInferenceError ?? .unknown("\(error)")+ continuation.yield(.failed(appError, partial: nil))+ continuation.finish(throwing: appError)+ return+ }++ let id = UUID()+ guard generationTasks.reserve(id) else {+ continuation.yield(.failed(.generationInFlight, partial: nil))+ continuation.finish(throwing: AppInferenceError.generationInFlight)+ return+ }+ let task = Task { [self] in+ await streamResponse(request: request,+ continuation: continuation,+ generationID: id)+ }+ generationTasks.attach(task, to: id)++ continuation.onTermination = { [generationTasks] _ in+ generationTasks.take(id)?.cancel()+ }+ }+ }++ func cancel() {+ generationTasks.takeCurrent()?.cancel()+ }++ private func streamResponse(+ request: AppGenerationRequest,+ continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation,+ generationID: UUID+ ) async {+ let start = Date()+ var firstTokenDate: Date?+ var prefillEnd = start+ var generated = 0++ do {+ for step in 1...3 {+ try await Task.sleep(for: eventDelay)+ try Task.checkCancellation()+ continuation.yield(.prefillProgress(done: step, total: 3))+ }+ prefillEnd = Date()++ let response = "Simulated response. Your prompt was: \(request.prompt)"+ let words = response.split(whereSeparator: \.isWhitespace)+ let pieces = words.enumerated().map { index, word in+ index == 0 ? String(word) : " " + word+ }.prefix(request.maxNewTokens)++ for (index, piece) in pieces.enumerated() {+ try await Task.sleep(for: eventDelay)+ try Task.checkCancellation()+ if firstTokenDate == nil { firstTokenDate = Date() }+ generated += 1+ continuation.yield(.token(AppTokenEvent(+ index: index,+ textDelta: piece,+ elapsedDecodeSeconds: Date().timeIntervalSince(prefillEnd))))+ }++ let end = Date()+ let decodeSeconds = max(end.timeIntervalSince(prefillEnd), 0)+ continuation.yield(.finished(AppDiagnostics(+ generatedTokens: generated,+ stopReason: generated >= request.maxNewTokens ? .maxTokens : .eos,+ promptTokenCount: max(1, request.prompt.split(whereSeparator: \.isWhitespace).count),+ prefillSeconds: prefillEnd.timeIntervalSince(start),+ timeToFirstTokenSeconds: firstTokenDate.map { $0.timeIntervalSince(prefillEnd) },+ decodeSeconds: decodeSeconds,+ tokensPerSecond: decodeSeconds > 0 ? Double(generated) / decodeSeconds : 0,+ peakMemoryBytes: nil,+ runtimeOptions: request.runtimeOptions)))+ continuation.finish()+ } catch is CancellationError {+ let end = Date()+ let decodeSeconds = max(end.timeIntervalSince(prefillEnd), 0)+ continuation.yield(.cancelled(AppDiagnostics(+ generatedTokens: generated,+ stopReason: .cancelled,+ promptTokenCount: max(1, request.prompt.split(whereSeparator: \.isWhitespace).count),+ prefillSeconds: prefillEnd.timeIntervalSince(start),+ timeToFirstTokenSeconds: firstTokenDate.map { $0.timeIntervalSince(prefillEnd) },+ decodeSeconds: decodeSeconds,+ tokensPerSecond: decodeSeconds > 0 ? Double(generated) / decodeSeconds : 0,+ peakMemoryBytes: nil,+ runtimeOptions: request.runtimeOptions)))+ continuation.finish(throwing: AppInferenceError.cancelled)+ } catch {+ let appError = error as? AppInferenceError ?? .unknown("\(error)")+ continuation.yield(.failed(appError, partial: nil))+ continuation.finish(throwing: appError)+ }++ generationTasks.clear(generationID)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swiftnew file mode 100644index 00000000..ebef2700--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift@@ -0,0 +1,187 @@+import Foundation+@testable import TurboFieldfareAppCore++/// Test double: streams canned word tokens behind the `AppInferenceClient`+/// protocol so AppModel control flow stays testable without a model load.+final class MockInferenceClient: AppInferenceClient, @unchecked Sendable {+ var response: String+ var tokenDelayNanos: UInt64+ var failureMessage: String?+ var prefillSteps: Int = 3++ private let lock = NSLock()+ private var activeTask: Task<Void, Never>?+ private var activeGenerationID: UUID?+ private let memorySampler: AppMemorySampler++ init(response: String = "This is a lightweight mock response streaming through the TurboFieldfare Mac shell.",+ tokenDelayNanos: UInt64 = 35_000_000,+ memorySampler: AppMemorySampler = AppMemorySampler(),+ failureMessage: String? = nil) {+ self.response = response+ self.tokenDelayNanos = tokenDelayNanos+ self.memorySampler = memorySampler+ self.failureMessage = failureMessage+ }++ func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream { continuation in+ do {+ try request.validate()+ } catch {+ let appError = error as? AppInferenceError ?? .unknown("\(error)")+ continuation.yield(.failed(appError, partial: nil))+ continuation.finish(throwing: appError)+ return+ }++ lock.lock()+ if activeTask != nil {+ lock.unlock()+ continuation.yield(.failed(.generationInFlight, partial: nil))+ continuation.finish(throwing: AppInferenceError.generationInFlight)+ return+ }+ memorySampler.resetPeak()+ _ = memorySampler.sample()+ let generationID = UUID()+ let task = Task { [self] in+ await run(request: request, generationID: generationID, continuation: continuation)+ }+ activeTask = task+ activeGenerationID = generationID+ lock.unlock()++ continuation.onTermination = { [weak self] _ in+ self?.cancel()+ }+ }+ }++ func cancel() {+ lock.lock()+ let task = activeTask+ activeTask = nil+ activeGenerationID = nil+ lock.unlock()+ task?.cancel()+ }++ private func clearActiveTask(generationID: UUID) {+ lock.lock()+ if activeGenerationID == generationID {+ activeTask = nil+ activeGenerationID = nil+ }+ lock.unlock()+ }++ private func run(request: AppGenerationRequest,+ generationID: UUID,+ continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation) async {+ defer { clearActiveTask(generationID: generationID) }++ if let failureMessage {+ let error = AppInferenceError.unknown(failureMessage)+ let diagnostics = makeDiagnostics(request: request, generated: 0, start: Date(),+ firstToken: nil, stopReason: .failed)+ continuation.yield(.failed(error, partial: diagnostics))+ continuation.finish(throwing: error)+ return+ }++ let start = Date()+ var firstTokenDate: Date?+ var prefillEndDate: Date?+ let pieces = Array(responsePieces(for: request)).prefix(request.maxNewTokens)+ var generated = 0++ for step in 0..<max(prefillSteps, 0) {+ if Task.isCancelled {+ let diagnostics = makeDiagnostics(request: request, generated: 0,+ start: start, firstToken: nil,+ prefillEnd: Date(),+ stopReason: .cancelled)+ continuation.yield(.cancelled(diagnostics))+ continuation.finish(throwing: AppInferenceError.cancelled)+ return+ }+ try? await Task.sleep(nanoseconds: tokenDelayNanos)+ continuation.yield(.prefillProgress(done: step + 1, total: prefillSteps))+ }+ prefillEndDate = Date()++ for (index, piece) in pieces.enumerated() {+ let decodeStart = prefillEndDate ?? start+ if Task.isCancelled {+ let diagnostics = makeDiagnostics(request: request, generated: generated,+ start: start, firstToken: firstTokenDate,+ prefillEnd: prefillEndDate,+ stopReason: .cancelled)+ continuation.yield(.cancelled(diagnostics))+ continuation.finish(throwing: AppInferenceError.cancelled)+ return+ }+ try? await Task.sleep(nanoseconds: tokenDelayNanos)+ if Task.isCancelled {+ let diagnostics = makeDiagnostics(request: request, generated: generated,+ start: start, firstToken: firstTokenDate,+ prefillEnd: prefillEndDate,+ stopReason: .cancelled)+ continuation.yield(.cancelled(diagnostics))+ continuation.finish(throwing: AppInferenceError.cancelled)+ return+ }+ if firstTokenDate == nil { firstTokenDate = Date() }+ generated += 1+ _ = memorySampler.sample()+ continuation.yield(.token(AppTokenEvent(+ index: index,+ textDelta: piece,+ elapsedDecodeSeconds: max(Date().timeIntervalSince(decodeStart), 0))))+ }++ let diagnostics = makeDiagnostics(request: request, generated: generated,+ start: start, firstToken: firstTokenDate,+ prefillEnd: prefillEndDate,+ stopReason: generated >= request.maxNewTokens ? .maxTokens : .eos)+ continuation.yield(.finished(diagnostics))+ continuation.finish()+ }++ private func responsePieces(for request: AppGenerationRequest) -> [String] {+ let trimmed = request.prompt.trimmingCharacters(in: .whitespacesAndNewlines)+ let text = trimmed.isEmpty ? response : "\(response) Prompt received: \(trimmed)"+ let words = text.split(separator: " ", omittingEmptySubsequences: false)+ guard !words.isEmpty else { return [""] }+ return words.enumerated().map { index, word in+ index == 0 ? String(word) : " " + word+ }+ }++ private func makeDiagnostics(request: AppGenerationRequest,+ generated: Int,+ start: Date,+ firstToken: Date?,+ prefillEnd: Date? = nil,+ stopReason: AppStopReason) -> AppDiagnostics {+ _ = memorySampler.sample()+ let decodeStart = prefillEnd ?? start+ let decodeElapsed = max(Date().timeIntervalSince(decodeStart), 0)+ return AppDiagnostics(+ generatedTokens: generated,+ stopReason: stopReason,+ promptTokenCount: mockPromptTokenCount(request.prompt),+ prefillSeconds: prefillEnd.map { max($0.timeIntervalSince(start), 0) },+ timeToFirstTokenSeconds: firstToken.map { max($0.timeIntervalSince(decodeStart), 0) },+ decodeSeconds: decodeElapsed,+ tokensPerSecond: decodeElapsed > 0 ? Double(generated) / decodeElapsed : 0,+ peakMemoryBytes: memorySampler.peakBytes,+ runtimeOptions: request.runtimeOptions,+ runner: nil)+ }++ private func mockPromptTokenCount(_ prompt: String) -> Int {+ max(1, prompt.split(whereSeparator: \.isWhitespace).count)+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/MockInferenceClientTests.swift b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClientTests.swiftnew file mode 100644index 00000000..17afe6e1--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClientTests.swift@@ -0,0 +1,90 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct MockInferenceClientTests {+ @Test func streamsTokensAndFinishesWithDiagnostics() async throws {+ let client = MockInferenceClient(response: "one two three", tokenDelayNanos: 1_000_000)+ let request = AppGenerationRequest(modelDirectory: FileManager.default.temporaryDirectory, prompt: "go", maxNewTokens: 8)+ var text = ""+ var diagnostics: AppDiagnostics?+ var prefillEvents: [(Int, Int)] = []+ var sawTokenBeforePrefillEnded = false+ var firstTokenElapsed: Double?++ for try await event in client.generate(request) {+ switch event {+ case .prefillProgress(let done, let total):+ prefillEvents.append((done, total))+ case .token(let token):+ if prefillEvents.count < client.prefillSteps { sawTokenBeforePrefillEnded = true }+ if firstTokenElapsed == nil { firstTokenElapsed = token.elapsedDecodeSeconds }+ text += token.textDelta+ case .finished(let d):+ diagnostics = d+ default:+ break+ }+ }++ #expect(text.contains("one two three"))+ #expect(prefillEvents.count == client.prefillSteps)+ #expect(prefillEvents.last?.0 == client.prefillSteps)+ #expect(!sawTokenBeforePrefillEnded)+ let d = try #require(diagnostics)+ #expect(d.generatedTokens > 0)+ #expect(d.promptTokenCount == 1)+ let ttft = try #require(d.timeToFirstTokenSeconds)+ let prefillSeconds = try #require(d.prefillSeconds)+ let firstElapsed = try #require(firstTokenElapsed)+ #expect(prefillSeconds >= 0)+ #expect(ttft >= 0)+ #expect(firstElapsed >= ttft)+ #expect(firstElapsed <= d.decodeSeconds)+ #expect(d.tokensPerSecond >= 0)+ }++ @Test func cancellationEmitsCancelledDiagnostics() async throws {+ let client = MockInferenceClient(response: "one two three four five", tokenDelayNanos: 5_000_000)+ let request = AppGenerationRequest(modelDirectory: FileManager.default.temporaryDirectory, prompt: "go", maxNewTokens: 10)+ var sawToken = false+ var sawCancel = false+ var cancelledDiagnostics: AppDiagnostics?++ do {+ for try await event in client.generate(request) {+ switch event {+ case .token:+ sawToken = true+ client.cancel()+ case .cancelled(let diagnostics):+ sawCancel = diagnostics.stopReason == .cancelled+ cancelledDiagnostics = diagnostics+ default:+ break+ }+ }+ } catch AppInferenceError.cancelled {+ }++ #expect(sawToken)+ #expect(sawCancel)+ #expect(cancelledDiagnostics?.promptTokenCount == 1)+ #expect(cancelledDiagnostics?.prefillSeconds != nil)+ }++ @Test func concurrentGenerationRejected() async throws {+ let client = MockInferenceClient(response: "one two three", tokenDelayNanos: 20_000_000)+ let request = AppGenerationRequest(modelDirectory: FileManager.default.temporaryDirectory, prompt: "go", maxNewTokens: 3)+ let first = client.generate(request)+ let second = client.generate(request)++ var firstIterator = first.makeAsyncIterator()+ _ = try await firstIterator.next()++ await #expect(throws: AppInferenceError.self) {+ for try await _ in second {}+ }+ client.cancel()+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swiftnew file mode 100644index 00000000..2abeb36b--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/MockLifecycleInferenceClient.swift@@ -0,0 +1,186 @@+import Foundation+@testable import TurboFieldfareAppCore++final class MockLifecycleInferenceClient: AppModelLifecycleClient, @unchecked Sendable {+ var suspendUnloads = false+ var suspendLoads = false++ private let lock = NSLock()+ private var unloadContinuations: [CheckedContinuation<Void, Never>] = []+ private var unloadStartedCount = 0+ private var loadStartedCount = 0+ private var loadStateHandlers: [@Sendable (AppModelLoadState) -> Void] = []+ private var nextLoadFailure: AppInferenceError?+ private(set) var ensureLoadedCalls: [(URL, Int, AppRuntimeOptions, Bool)] = []++ func ensureLoaded(modelDirectory: URL,+ maxContextTokens: Int,+ options: AppRuntimeOptions,+ forceLogitsHead: Bool,+ onState: @escaping @Sendable (AppModelLoadState) -> Void) async throws {+ recordEnsureLoaded(modelDirectory: modelDirectory,+ maxContextTokens: maxContextTokens,+ options: options,+ forceLogitsHead: forceLogitsHead)+ recordLoadStart(onState)++ onState(.loading(.validatingDirectory))+ while shouldSuspendLoad {+ try await Task.sleep(for: .milliseconds(5))+ }+ if let failure = takeLoadFailure() {+ onState(.failed(failure))+ throw failure+ }+ try Task.checkCancellation()+ onState(.ready(modelDirectory: modelDirectory.standardizedFileURL,+ loadSeconds: 0))+ }++ func unload() async {+ if beginUnload() {+ await withCheckedContinuation { continuation in+ appendUnloadContinuation(continuation)+ }+ }++ }++ func generate(_ request: AppGenerationRequest) -> AsyncThrowingStream<AppInferenceEvent, Error> {+ AsyncThrowingStream { continuation in+ let task = Task {+ continuation.yield(.finished(AppDiagnostics(+ generatedTokens: 0,+ stopReason: .eos,+ promptTokenCount: 1,+ prefillSeconds: nil,+ timeToFirstTokenSeconds: nil,+ decodeSeconds: 0,+ tokensPerSecond: 0,+ peakMemoryBytes: nil,+ runtimeOptions: request.runtimeOptions)))+ continuation.finish()+ }++ continuation.onTermination = { _ in task.cancel() }+ }+ }++ func cancel() {}++ func releaseUnloads() {+ let continuations: [CheckedContinuation<Void, Never>]+ lock.lock()+ continuations = unloadContinuations+ unloadContinuations.removeAll()+ suspendUnloads = false+ lock.unlock()+ continuations.forEach { $0.resume() }+ }++ func releaseLoads() {+ lock.lock()+ suspendLoads = false+ lock.unlock()+ }++ func failNextLoad(_ error: AppInferenceError) {+ lock.lock()+ nextLoadFailure = error+ suspendLoads = false+ lock.unlock()+ }++ func emitLoadState(_ state: AppModelLoadState, callIndex: Int) {+ let handler: (@Sendable (AppModelLoadState) -> Void)?+ lock.lock()+ handler = loadStateHandlers.indices.contains(callIndex)+ ? loadStateHandlers[callIndex]+ : nil+ lock.unlock()+ handler?(state)+ }++ func ensureLoadedCallCount() -> Int {+ lock.lock()+ defer { lock.unlock() }+ return ensureLoadedCalls.count+ }++ func waitForUnloadStart() async {+ for _ in 0..<200 {+ if unloadHasStarted { return }+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ }++ func waitForLoadStart(_ expected: Int = 1) async {+ for _ in 0..<200 {+ if loadStartCount >= expected { return }+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ }++ func waitForEnsureLoadedCallCount(_ expected: Int) async {+ for _ in 0..<200 {+ if ensureLoadedCallCount() >= expected { return }+ try? await Task.sleep(nanoseconds: 5_000_000)+ }+ }++ private var unloadHasStarted: Bool {+ lock.lock()+ defer { lock.unlock() }+ return unloadStartedCount > 0+ }++ private var loadStartCount: Int {+ lock.lock()+ defer { lock.unlock() }+ return loadStartedCount+ }++ private var shouldSuspendLoad: Bool {+ lock.lock()+ defer { lock.unlock() }+ return suspendLoads+ }++ private func recordEnsureLoaded(modelDirectory: URL,+ maxContextTokens: Int,+ options: AppRuntimeOptions,+ forceLogitsHead: Bool) {+ lock.lock()+ ensureLoadedCalls.append((modelDirectory.standardizedFileURL, maxContextTokens,+ options, forceLogitsHead))+ lock.unlock()+ }++ private func recordLoadStart(_ handler: @escaping @Sendable (AppModelLoadState) -> Void) {+ lock.lock()+ loadStartedCount += 1+ loadStateHandlers.append(handler)+ lock.unlock()+ }++ private func takeLoadFailure() -> AppInferenceError? {+ lock.lock()+ defer { lock.unlock() }+ defer { nextLoadFailure = nil }+ return nextLoadFailure+ }++ private func beginUnload() -> Bool {+ lock.lock()+ defer { lock.unlock() }+ unloadStartedCount += 1+ return suspendUnloads+ }++ private func appendUnloadContinuation(_ continuation: CheckedContinuation<Void, Never>) {+ lock.lock()+ unloadContinuations.append(continuation)+ lock.unlock()+ }++}diff --git a/Tests/TurboFieldfareApp/Core/Support/MockModelInstallerClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockModelInstallerClient.swiftnew file mode 100644index 00000000..e5ebc5aa--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Support/MockModelInstallerClient.swift@@ -0,0 +1,84 @@+import Foundation+import Synchronization+@testable import TurboFieldfareAppCore++final class MockModelInstallerClient: AppModelInstallerClient, Sendable {+ let events: [AppModelInstallEvent]+ let failure: Error?+ let holdOpen: Bool+ let requirement: AppModelInstallRequirement+ let descriptor: AppModelInstallDescriptor+ private struct State {+ var task: Task<Void, Never>?+ var cancelCalled = false+ }+ private final class TaskState: Sendable {+ let value = Mutex(State())+ }+ private let taskState = TaskState()++ var cancelCalled: Bool { taskState.value.withLock { $0.cancelCalled } }++ init(events: [AppModelInstallEvent] = [],+ failure: Error? = nil,+ requirement: AppModelInstallRequirement = AppModelInstallRequirement(+ requiredBytes: 1,+ availableBytes: UInt64.max),+ descriptor: AppModelInstallDescriptor = .default,+ holdOpen: Bool = false) {+ self.events = events+ self.failure = failure+ self.requirement = requirement+ self.descriptor = descriptor+ self.holdOpen = holdOpen+ }++ func checkInstallRequirement(outputDirectory: URL) throws -> AppModelInstallRequirement {+ requirement+ }++ func installDefaultModel(outputDirectory: URL) -> AsyncThrowingStream<AppModelInstallEvent, Error> {+ AsyncThrowingStream { continuation in+ let events = self.events+ let failure = self.failure+ let holdOpen = self.holdOpen+ let task = Task {+ do {+ for event in events {+ try Task.checkCancellation()+ continuation.yield(event)+ await Task.yield()+ }+ if holdOpen {+ try await Task.sleep(for: .seconds(60))+ }+ if let failure {+ continuation.finish(throwing: failure)+ } else {+ continuation.finish()+ }+ } catch is CancellationError {+ continuation.finish(throwing: CancellationError())+ } catch {+ continuation.finish(throwing: error)+ }+ }+ taskState.value.withLock { $0.task = task }+ continuation.onTermination = { [taskState] _ in+ let task = taskState.value.withLock { state -> Task<Void, Never>? in+ defer { state.task = nil }+ return state.task+ }+ task?.cancel()+ }+ }+ }++ func cancel() {+ let task = taskState.value.withLock { state -> Task<Void, Never>? in+ state.cancelCalled = true+ return state.task+ }+ task?.cancel()+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Cleanup.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Cleanup.swiftnew file mode 100644index 00000000..37e26f7f--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Cleanup.swift@@ -0,0 +1,48 @@+import Foundation+import Synchronization+import Testing++@testable import TurboFieldfareRepackCore++extension RemotePayloadCopyTests {+ @Test func stalePartialSweepRemovesDeadPidAndPreservesUnrelatedSiblings() async throws {+ let root = tmpDirForRemote("partial-root")+ let output = (root as NSString).appendingPathComponent("out.gturbo")+ let stale = (root as NSString).appendingPathComponent("out.gturbo.partial.999999")+ let unrelatedA = (root as NSString).appendingPathComponent("out.gturbo.partial")+ let unrelatedB = (root as NSString).appendingPathComponent("outX.gturbo.partial.1")+ defer { cleanUpRemote([root]) }+ try Posix.mkdirP(stale)+ try Data("x".utf8).write(+ to: URL(fileURLWithPath: (stale as NSString).appendingPathComponent("payload")))+ try Posix.mkdirP(unrelatedA)+ try Posix.mkdirP(unrelatedB)+ let audit = RepackAudit()++ try RemoteStreamingRepacker.sweepStalePartials(outputDir: output, audit: audit)++ #expect(!FileManager.default.fileExists(atPath: stale))+ #expect(FileManager.default.fileExists(atPath: unrelatedA))+ #expect(FileManager.default.fileExists(atPath: unrelatedB))+ #expect(audit.stalePartialsRemoved == [stale])+ }++ @Test func stalePartialSweepRefusesLivePid() throws {+ let root = tmpDirForRemote("partial-live-root")+ let output = (root as NSString).appendingPathComponent("out.gturbo")+ let live = (root as NSString).appendingPathComponent("out.gturbo.partial.\(getpid())")+ defer { cleanUpRemote([root]) }+ try Posix.mkdirP(live)++ #expect {+ try RemoteStreamingRepacker.sweepStalePartials(outputDir: output)+ } throws: { error in+ guard case RepackError.configurationInvalid(let detail) = error else {+ return false+ }+ return detail.contains("another repack")+ }+ #expect(FileManager.default.fileExists(atPath: live))+ }++}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Installation.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Installation.swiftnew file mode 100644index 00000000..390b47f4--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Installation.swift@@ -0,0 +1,180 @@+import Foundation+import Synchronization+import Testing++@testable import TurboFieldfareRepackCore++extension RemotePayloadCopyTests {+ @Test func remoteInstallProgressIsMonotonicAndComplete() async throws {+ let snapshotDir = tmpDirForRemote("snap-progress")+ let remoteOutput = tmpPathForRemote("remote-progress")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x10_2938_4756)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ let recorder = InstallProgressRecorder()++ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: remoteOutput, session: fakeHFSession())+ )+ .run { recorder.append($0) }++ let payload = recorder.values.compactMap { event -> (UInt64, UInt64)? in+ guard case .copyingPayload(let downloaded, let total) = event else { return nil }+ return (downloaded, total)+ }+ #expect(payload.count > 2)+ #expect(payload.first?.0 == 0)+ #expect(payload.last?.0 == payload.last?.1)+ #expect(+ zip(payload, payload.dropFirst()).allSatisfy { pair in+ pair.0.0 <= pair.1.0+ })+ #expect(payload.allSatisfy { $0.0 <= $0.1 })+ #expect(+ recorder.values.contains {+ if case .planning = $0 { return true }+ return false+ })+ #expect(+ recorder.values.contains {+ if case .hashingOutput = $0 { return true }+ return false+ })+ #expect(recorder.values.contains(.finalizing))+ }++ @Test func cancellationCleansPartialAndAllowsImmediateRetry() async throws {+ let snapshotDir = tmpDirForRemote("snap-cancel")+ let remoteOutput = tmpPathForRemote("remote-cancel")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x56_4738_2910)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ let options = remoteOptions(+ outputDir: remoteOutput,+ session: fakeHFSession(),+ retainPartialOnFailure: false)++ let cancelledInstall = Task {+ try await RemoteStreamingRepacker(options: options).run { event in+ if case .copyingPayload(let downloaded, _) = event, downloaded > 0 {+ withUnsafeCurrentTask { $0?.cancel() }+ }+ }+ }+ await #expect(throws: CancellationError.self) {+ _ = try await cancelledInstall.value+ }++ #expect(!FileManager.default.fileExists(atPath: remoteOutput))+ #expect(+ !FileManager.default.fileExists(+ atPath: remoteOutput + ".partial.\(getpid())"))++ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(+ outputDir: remoteOutput,+ session: fakeHFSession(),+ retainPartialOnFailure: false)+ ).run()+ #expect(+ FileManager.default.fileExists(+ atPath: (remoteOutput as NSString).appendingPathComponent("manifest.json")))+ }++ @Test func remoteTokenizerOptionalSpecialTokensMissingStillInstalls() async throws {+ let snapshotDir = tmpDirForRemote("snap-tokenizer-optional")+ let remoteOutput = tmpDirForRemote("remote-tokenizer-optional")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x6655_4433_2211)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ let session = fakeHFSession()++ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: remoteOutput, session: session)+ ).run()++ try assertRemoteTokenizerFilesRecorded(+ outputDir: remoteOutput,+ expectsOptionalSpecialTokens: false)++ let verification = try VerifiedInstallTool.run(+ options: VerifyInstallOptions(inputGTurbo: remoteOutput))+ #expect(FileManager.default.fileExists(atPath: verification.receiptPath))+ #expect(verification.fileCount > 1)+ #expect(verification.bytesVerified > 0)+ #expect(verification.unexpectedEntries.isEmpty)+ }++ @Test func remoteTokenizerMissingRequiredFileFailsInstall() async throws {+ let snapshotDir = tmpDirForRemote("snap-tokenizer-required")+ let remoteOutput = tmpPathForRemote("remote-tokenizer-required")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x7766_5544_3322)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: false,+ includeOptionalTokenizer: true)+ let session = fakeHFSession()++ await #expect(throws: RepackError.self) {+ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: remoteOutput, session: session)+ ).run()+ }+ #expect(!FileManager.default.fileExists(atPath: remoteOutput))+ }++ @Test func remoteInstallRejectsPerTensorGroupSizeOverride() async throws {+ let snapshotDir = tmpDirForRemote("snap-group-size")+ let remoteOutput = tmpPathForRemote("remote-group-size")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x65_726F_7570)++ resetFakeHF()+ var files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ let configData = try #require(files["config.json"])+ var config = try #require(+ JSONSerialization.jsonObject(with: configData) as? [String: Any])+ var quantization = try #require(config["quantization"] as? [String: Any])+ let key = "language_model.model.layers.0.router.proj"+ var override = try #require(quantization[key] as? [String: Any])+ override["group_size"] = 32+ quantization[key] = override+ config["quantization"] = quantization+ files["config.json"] = try JSONSerialization.data(withJSONObject: config)+ FakeHFURLProtocol.files = files++ await #expect(throws: RepackError.self) {+ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: remoteOutput, session: fakeHFSession())+ ).run()+ }+ #expect(!FileManager.default.fileExists(atPath: remoteOutput))+ }++}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Retries.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Retries.swiftnew file mode 100644index 00000000..951678f3--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Retries.swift@@ -0,0 +1,128 @@+import Foundation+import Synchronization+import Testing++@testable import TurboFieldfareRepackCore++extension RemotePayloadCopyTests {+ @Test func remoteRangeRetriesURLErrorAndCompletes() async throws {+ let snapshotDir = tmpDirForRemote("snap-retry-url")+ let remoteOutput = tmpPathForRemote("remote-retry-url")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x8877_6655_4433)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ FakeHFURLProtocol.failures["GET:model-00001-of-00001.safetensors"] = [+ .url(.networkConnectionLost),+ .url(.timedOut),+ ]+ let audit = RepackAudit()+ let recorder = InstallProgressRecorder()++ let result = try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: remoteOutput, session: fakeHFSession()),+ audit: audit+ ).run { recorder.append($0) }++ #expect(audit.remoteRangeRetries == 2)+ #expect((FakeHFURLProtocol.requestCounts["GET:model-00001-of-00001.safetensors"] ?? 0) >= 3)+ let payload = recorder.values.compactMap { event -> UInt64? in+ guard case .copyingPayload(let downloaded, _) = event else { return nil }+ return downloaded+ }+ #expect(payload.last == result.remoteBytesToDownload)+ #expect(zip(payload, payload.dropFirst()).allSatisfy { $0.0 <= $0.1 })+ try assertNoInternalRemoteDirs(outputDir: remoteOutput)+ }++ @Test func remotePersistentServerErrorStopsAfterConfiguredAttempts() async throws {+ let snapshotDir = tmpDirForRemote("snap-retry-500")+ let remoteOutput = tmpPathForRemote("remote-retry-500")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x9988_7766_5544)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ FakeHFURLProtocol.failures["HEAD:model.safetensors.index.json"] = [+ .http(500),+ .http(500),+ .http(500),+ ]+ let audit = RepackAudit()++ await #expect(throws: RepackError.self) {+ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(+ outputDir: remoteOutput,+ session: fakeHFSession(),+ rangeRetryAttempts: 3),+ audit: audit+ ).run()+ }++ #expect(FakeHFURLProtocol.requestCounts["HEAD:model.safetensors.index.json"] == 3)+ #expect(audit.remoteRangeRetries == 2)+ #expect(!FileManager.default.fileExists(atPath: remoteOutput))+ }++ @Test func remote404DoesNotRetry() async throws {+ let snapshotDir = tmpDirForRemote("snap-retry-404")+ let remoteOutput = tmpPathForRemote("remote-retry-404")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0xAA99_8877_6655)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ FakeHFURLProtocol.files.removeValue(forKey: "config.json")+ let audit = RepackAudit()++ await #expect(throws: RepackError.self) {+ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: remoteOutput, session: fakeHFSession()),+ audit: audit+ ).run()+ }++ #expect(FakeHFURLProtocol.requestCounts["HEAD:config.json"] == 1)+ #expect(audit.remoteRangeRetries == 0)+ #expect(!FileManager.default.fileExists(atPath: remoteOutput))+ }++ @Test func remoteTruncatedRangeRetriesAndCleansTemp() async throws {+ let snapshotDir = tmpDirForRemote("snap-retry-truncated")+ let remoteOutput = tmpPathForRemote("remote-retry-truncated")+ defer { cleanUpRemote([snapshotDir, remoteOutput]) }+ let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0xBBAA_9988_7766)++ resetFakeHF()+ FakeHFURLProtocol.files = try remoteFiles(+ snapshotDir: snapshotDir,+ snap: snap,+ includeRequiredTokenizer: true,+ includeOptionalTokenizer: false)+ FakeHFURLProtocol.failures["GET:model-00001-of-00001.safetensors"] = [.truncatedBody]+ let audit = RepackAudit()++ _ = try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: remoteOutput, session: fakeHFSession()),+ audit: audit+ ).run()++ #expect(audit.remoteRangeRetries == 1)+ try assertNoInternalRemoteDirs(outputDir: remoteOutput)+ }++}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swiftnew file mode 100644index 00000000..79463e2a--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift@@ -0,0 +1,274 @@+import Foundation+import Synchronization+import Testing+@testable import TurboFieldfareRepackCore++final class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {+ nonisolated(unsafe) static var files: [String: Data] = [:]+ nonisolated(unsafe) static var commit = "cc499c86a958ea7f05cffaa91c7e7243240dabbe"+ nonisolated(unsafe) static var failures: [String: [FakeFailure]] = [:]+ nonisolated(unsafe) static var requestCounts: [String: Int] = [:]++ override class func canInit(with request: URLRequest) -> Bool {+ request.url?.host == "hf.test"+ }++ override class func canonicalRequest(for request: URLRequest) -> URLRequest {+ request+ }++ override func startLoading() {+ guard let url = request.url,+ let filename = Self.filename(from: url) else {+ let response = HTTPURLResponse(url: request.url!,+ statusCode: 404,+ httpVersion: nil,+ headerFields: nil)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocolDidFinishLoading(self)+ return+ }+ let method = request.httpMethod ?? "GET"+ let key = "\(method):\(filename)"+ Self.requestCounts[key, default: 0] += 1+ let failure = Self.nextFailure(for: key)+ switch failure {+ case .url(let code):+ client?.urlProtocol(self, didFailWithError: URLError(code))+ return+ case .http(let status):+ let response = HTTPURLResponse(url: url,+ statusCode: status,+ httpVersion: nil,+ headerFields: nil)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocolDidFinishLoading(self)+ return+ case .truncatedBody, nil:+ break+ }++ guard let data = Self.files[filename] else {+ let response = HTTPURLResponse(url: request.url!,+ statusCode: 404,+ httpVersion: nil,+ headerFields: nil)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocolDidFinishLoading(self)+ return+ }++ if method == "HEAD" {+ let headers = baseHeaders(data: data,+ contentLength: data.count)+ let response = HTTPURLResponse(url: url,+ statusCode: 200,+ httpVersion: nil,+ headerFields: headers)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocolDidFinishLoading(self)+ return+ }++ let range = request.value(forHTTPHeaderField: "Range")+ guard let (start, end) = parseRange(range, fileSize: data.count) else {+ let response = HTTPURLResponse(url: url,+ statusCode: 416,+ httpVersion: nil,+ headerFields: nil)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocolDidFinishLoading(self)+ return+ }+ let expectedLength = end - start + 1+ let body: Data+ if failure == .truncatedBody {+ body = start < end ? Data(data[start..<end]) : Data()+ } else {+ body = Data(data[start...end])+ }+ var headers = baseHeaders(data: data,+ contentLength: expectedLength)+ headers["Content-Range"] = "bytes \(start)-\(end)/\(data.count)"+ let response = HTTPURLResponse(url: url,+ statusCode: 206,+ httpVersion: nil,+ headerFields: headers)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocol(self, didLoad: Data(body))+ client?.urlProtocolDidFinishLoading(self)+ }++ override func stopLoading() {}++ func baseHeaders(data: Data,+ contentLength: Int) -> [String: String] {+ [+ "X-Repo-Commit": Self.commit,+ "X-Linked-Size": "\(data.count)",+ "Accept-Ranges": "bytes",+ "Content-Length": "\(contentLength)",+ "Content-Encoding": "identity",+ ]+ }++ static func filename(from url: URL) -> String? {+ let parts = url.path.split(separator: "/").map(String.init)+ guard let resolveIndex = parts.firstIndex(of: "resolve"),+ parts.count > resolveIndex + 2 else {+ return nil+ }+ return parts[(resolveIndex + 2)...].joined(separator: "/")+ }++ static func nextFailure(for key: String) -> FakeFailure? {+ guard var queue = failures[key], !queue.isEmpty else { return nil }+ let failure = queue.removeFirst()+ failures[key] = queue+ return failure+ }++ func parseRange(_ value: String?, fileSize: Int) -> (Int, Int)? {+ guard let value, value.hasPrefix("bytes=") else { return nil }+ let body = value.dropFirst("bytes=".count)+ let parts = body.split(separator: "-", maxSplits: 1)+ guard parts.count == 2,+ let start = Int(parts[0]),+ let end = Int(parts[1]),+ start >= 0,+ end >= start,+ end < fileSize else {+ return nil+ }+ return (start, end)+ }+}++enum FakeFailure: Equatable {+ case url(URLError.Code)+ case http(Int)+ case truncatedBody+}++let remoteTokenizerJSON = Data(#"{"model":{"type":"BPE"}}"#.utf8)+let remoteTokenizerConfigJSON = Data(#"{"tokenizer_class":"PreTrainedTokenizerFast"}"#.utf8)+let remoteSpecialTokensMapJSON = Data(#"{"eos_token":"<eos>"}"#.utf8)++@Suite(.serialized)+struct RemotePayloadCopyTests {++}++func remoteFiles(snapshotDir: String,+ snap: SyntheticSnapshot.Snapshot,+ includeRequiredTokenizer: Bool,+ includeOptionalTokenizer: Bool) throws -> [String: Data] {+ var files = [+ "config.json": try Data(contentsOf: URL(fileURLWithPath:+ (snapshotDir as NSString).appendingPathComponent("config.json"))),+ "model.safetensors.index.json": try Data(contentsOf: URL(fileURLWithPath:+ (snapshotDir as NSString).appendingPathComponent("model.safetensors.index.json"))),+ "model-00001-of-00001.safetensors": try Data(contentsOf: URL(fileURLWithPath: snap.shardPath)),+ ]+ if includeRequiredTokenizer {+ files["tokenizer.json"] = remoteTokenizerJSON+ files["tokenizer_config.json"] = remoteTokenizerConfigJSON+ }+ if includeOptionalTokenizer {+ files["special_tokens_map.json"] = remoteSpecialTokensMapJSON+ }+ return files+}++func resetFakeHF() {+ FakeHFURLProtocol.files = [:]+ FakeHFURLProtocol.failures = [:]+ FakeHFURLProtocol.requestCounts = [:]+}++func fakeHFSession() -> URLSession {+ let config = URLSessionConfiguration.ephemeral+ config.protocolClasses = [FakeHFURLProtocol.self]+ return URLSession(configuration: config)+}++func remoteOptions(outputDir: String,+ session: URLSession,+ rangeRetryAttempts: Int = 4,+ retainPartialOnFailure: Bool = true) -> RemoteStreamingRepackOptions {+ RemoteStreamingRepackOptions(+ outputDir: outputDir,+ overwrite: true,+ repoID: "owner/model",+ revision: "main",+ requireKnownSource: false,+ rangeChunkBytes: 4096,+ minFreeReserveBytes: 0,+ retainPartialOnFailure: retainPartialOnFailure,+ session: session,+ baseURL: URL(string: "https://hf.test")!,+ rangeRetryAttempts: rangeRetryAttempts,+ retryBaseDelayNs: 0)+}++final class InstallProgressRecorder: Sendable {+ let storage = Mutex<[ModelInstallProgress]>([])+ var values: [ModelInstallProgress] { storage.withLock { $0 } }+ func append(_ value: ModelInstallProgress) { storage.withLock { $0.append(value) } }+}++func assertRemoteTokenizerFilesRecorded(outputDir: String,+ expectsOptionalSpecialTokens: Bool) throws {+ let tokenizerDir = (outputDir as NSString).appendingPathComponent("tokenizer")+ #expect(try Data(contentsOf: URL(fileURLWithPath:+ (tokenizerDir as NSString).appendingPathComponent("tokenizer.json"))) == remoteTokenizerJSON)+ #expect(try Data(contentsOf: URL(fileURLWithPath:+ (tokenizerDir as NSString).appendingPathComponent("tokenizer_config.json"))) == remoteTokenizerConfigJSON)+ let specialTokensPath = (tokenizerDir as NSString).appendingPathComponent("special_tokens_map.json")+ #expect(FileManager.default.fileExists(atPath: specialTokensPath) == expectsOptionalSpecialTokens)++ let manifestData = try Data(contentsOf: URL(fileURLWithPath:+ (outputDir as NSString).appendingPathComponent("manifest.json")))+ let manifest = try JSONSerialization.jsonObject(with: manifestData) as! [String: Any]+ let manifestFiles = manifest["files"] as! [String: Any]+ #expect(manifestFiles["tokenizer/config.json"] != nil)+ #expect(manifestFiles["tokenizer/tokenizer.json"] != nil)+ #expect(manifestFiles["tokenizer/tokenizer_config.json"] != nil)+ #expect((manifestFiles["tokenizer/special_tokens_map.json"] != nil) == expectsOptionalSpecialTokens)++ let receiptData = try Data(contentsOf: URL(fileURLWithPath:+ (outputDir as NSString).appendingPathComponent(VerifiedInstallReceiptWriter.fileName)))+ let receipt = try JSONSerialization.jsonObject(with: receiptData) as! [String: Any]+ let receiptFiles = receipt["files"] as! [String: Any]+ #expect(receiptFiles["tokenizer/config.json"] != nil)+ #expect(receiptFiles["tokenizer/tokenizer.json"] != nil)+ #expect(receiptFiles["tokenizer/tokenizer_config.json"] != nil)+ #expect((receiptFiles["tokenizer/special_tokens_map.json"] != nil) == expectsOptionalSpecialTokens)+}++func assertNoInternalRemoteDirs(outputDir: String) throws {+ let entries = try FileManager.default.contentsOfDirectory(atPath: outputDir)+ #expect(!entries.contains(".range-tmp"))+ #expect(!entries.contains(".remote-metadata"))+}++func tmpDirForRemote(_ tag: String) -> String {+ let path = (NSTemporaryDirectory() as NSString)+ .appendingPathComponent("turbofieldfare-remote-\(tag)-\(UUID().uuidString)")+ try? FileManager.default.removeItem(atPath: path)+ try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true)+ return path+}++func tmpPathForRemote(_ tag: String) -> String {+ let path = (NSTemporaryDirectory() as NSString)+ .appendingPathComponent("turbofieldfare-remote-\(tag)-\(UUID().uuidString)")+ try? FileManager.default.removeItem(atPath: path)+ return path+}++func cleanUpRemote(_ paths: [String]) {+ for path in paths {+ try? FileManager.default.removeItem(atPath: path)+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/Support/SyntheticSnapshot.swift b/Tests/TurboFieldfareRepack/Core/Support/SyntheticSnapshot.swiftnew file mode 100644index 00000000..3810d0a4--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Support/SyntheticSnapshot.swift@@ -0,0 +1,304 @@+import Foundation++/// Synthesises a tiny MLX-affine-quantized safetensors snapshot inside a+/// temporary directory. The remote repack tests need only deterministic bytes+/// plus matching `config.json` and `model.safetensors.index.json` metadata.+enum SyntheticSnapshot {++ struct Snapshot {+ let shardPath: String+ }++ struct Arch {+ let hidden: Int = 128+ let moeIntermediate: Int = 64+ let intermediate: Int = 192+ let numHeads: Int = 2+ let numKVHeads: Int = 2+ let numGlobalKVHeads: Int = 2+ let headDim: Int = 32+ let globalHeadDim: Int = 64+ let vocab: Int = 512+ let numLayers: Int = 2+ let numExperts: Int = 2+ let topK: Int = 2+ let slidingWindow: Int = 128+ let groupSize: Int = 64+ // layer 0 = sliding, layer 1 = full+ let layerTypes: [String] = ["sliding_attention", "full_attention"]+ }++ /// Build the snapshot. `seed` controls the pseudo-random payload bytes so+ /// tests can pre-compute byte-fidelity expectations.+ static func build(at dir: String, seed: UInt64 = 0xA17B_EEF1_5FAC_E202) throws -> Snapshot {+ try? FileManager.default.removeItem(atPath: dir)+ try FileManager.default.createDirectory(atPath: dir,+ withIntermediateDirectories: true)++ let arch = Arch()+ var rng = SplitMix64(seed: seed)++ // Build the inventory: (name, dtype, shape, payload)+ var tensors: [(String, String, [Int], [UInt8])] = []+ tensors.reserveCapacity(64)++ // -- LM resident: embedding (4-bit, group=64)+ appendQuantizedWeight(name: "language_model.model.embed_tokens",+ outerShape: [arch.vocab],+ innerLogical: arch.hidden, bits: 4,+ groupSize: arch.groupSize, into: &tensors, rng: &rng)++ for li in 0..<arch.numLayers {+ let prefix = "language_model.model.layers.\(li)"+ // q/k/v/o projections — 4-bit attention+ // SWA layer: heads*head_dim out; full: globalHeadDim heads (here equal kv configs).+ let isFull = arch.layerTypes[li] == "full_attention"+ let qOut = arch.numHeads * (isFull ? arch.globalHeadDim : arch.headDim)+ let kOut = (isFull ? arch.numGlobalKVHeads : arch.numKVHeads) * (isFull ? arch.globalHeadDim : arch.headDim)+ let vOut = kOut+ let oIn = qOut+ appendQuantizedWeight(name: prefix + ".self_attn.q_proj",+ outerShape: [qOut], innerLogical: arch.hidden,+ bits: 4, groupSize: arch.groupSize, into: &tensors, rng: &rng)+ appendQuantizedWeight(name: prefix + ".self_attn.k_proj",+ outerShape: [kOut], innerLogical: arch.hidden,+ bits: 4, groupSize: arch.groupSize, into: &tensors, rng: &rng)+ if !isFull {+ appendQuantizedWeight(name: prefix + ".self_attn.v_proj",+ outerShape: [vOut], innerLogical: arch.hidden,+ bits: 4, groupSize: arch.groupSize, into: &tensors, rng: &rng)+ }+ appendQuantizedWeight(name: prefix + ".self_attn.o_proj",+ outerShape: [arch.hidden], innerLogical: oIn,+ bits: 4, groupSize: arch.groupSize, into: &tensors, rng: &rng)++ // Per-head norms (BF16, no scale/bias)+ appendUnquantizedBF16(name: prefix + ".self_attn.q_norm.weight",+ shape: [isFull ? arch.globalHeadDim : arch.headDim],+ into: &tensors, rng: &rng)+ appendUnquantizedBF16(name: prefix + ".self_attn.k_norm.weight",+ shape: [isFull ? arch.globalHeadDim : arch.headDim],+ into: &tensors, rng: &rng)++ // Router proj — 8-bit affine+ appendQuantizedWeight(name: prefix + ".router.proj",+ outerShape: [arch.numExperts], innerLogical: arch.hidden,+ bits: 8, groupSize: arch.groupSize, into: &tensors, rng: &rng)+ appendUnquantizedBF16(name: prefix + ".router.scale",+ shape: [arch.hidden], into: &tensors, rng: &rng)+ appendUnquantizedBF16(name: prefix + ".router.per_expert_scale",+ shape: [arch.numExperts], into: &tensors, rng: &rng)+ appendUnquantizedBF16(name: prefix + ".layer_scalar",+ shape: [1], into: &tensors, rng: &rng)++ // Shared-expert mlp — 8-bit affine+ appendQuantizedWeight(name: prefix + ".mlp.gate_proj",+ outerShape: [arch.intermediate], innerLogical: arch.hidden,+ bits: 8, groupSize: arch.groupSize, into: &tensors, rng: &rng)+ appendQuantizedWeight(name: prefix + ".mlp.up_proj",+ outerShape: [arch.intermediate], innerLogical: arch.hidden,+ bits: 8, groupSize: arch.groupSize, into: &tensors, rng: &rng)+ appendQuantizedWeight(name: prefix + ".mlp.down_proj",+ outerShape: [arch.hidden], innerLogical: arch.intermediate,+ bits: 8, groupSize: arch.groupSize, into: &tensors, rng: &rng)++ // Routed experts — 4-bit affine, leading dim = numExperts+ appendQuantizedWeight(name: prefix + ".experts.switch_glu.gate_proj",+ outerShape: [arch.numExperts, arch.moeIntermediate],+ innerLogical: arch.hidden, bits: 4,+ groupSize: arch.groupSize, into: &tensors, rng: &rng)+ appendQuantizedWeight(name: prefix + ".experts.switch_glu.up_proj",+ outerShape: [arch.numExperts, arch.moeIntermediate],+ innerLogical: arch.hidden, bits: 4,+ groupSize: arch.groupSize, into: &tensors, rng: &rng)+ appendQuantizedWeight(name: prefix + ".experts.switch_glu.down_proj",+ outerShape: [arch.numExperts, arch.hidden],+ innerLogical: arch.moeIntermediate, bits: 4,+ groupSize: arch.groupSize, into: &tensors, rng: &rng)++ // Per-layer norms+ for norm in ["input_layernorm","post_attention_layernorm",+ "pre_feedforward_layernorm","pre_feedforward_layernorm_2",+ "post_feedforward_layernorm","post_feedforward_layernorm_1",+ "post_feedforward_layernorm_2"] {+ appendUnquantizedBF16(name: prefix + "." + norm + ".weight",+ shape: [arch.hidden], into: &tensors, rng: &rng)+ }+ }+ // Final norm+ appendUnquantizedBF16(name: "language_model.model.norm.weight",+ shape: [arch.hidden], into: &tensors, rng: &rng)++ // Multimodal tensors included to prove the text-only repacker drops them.+ appendUnquantizedBF16(name: "vision_tower.encoder.layers.0.input_layernorm.weight",+ shape: [arch.hidden], into: &tensors, rng: &rng)+ appendQuantizedWeight(name: "vision_tower.encoder.layers.0.self_attn.q_proj.linear",+ outerShape: [arch.hidden], innerLogical: arch.hidden, bits: 4,+ groupSize: arch.groupSize, into: &tensors, rng: &rng)+ appendQuantizedWeight(name: "embed_vision.embedding_projection",+ outerShape: [arch.hidden], innerLogical: arch.hidden, bits: 4,+ groupSize: arch.groupSize, into: &tensors, rng: &rng)++ // -- Encode safetensors.+ let shardName = "model-00001-of-00001.safetensors"+ let shardPath = (dir as NSString).appendingPathComponent(shardName)+ try writeShard(path: shardPath, tensors: tensors)++ // -- Write config.json with bit-width overrides for mlp + router.+ var overrides: [String: [String: Any]] = [:]+ for li in 0..<arch.numLayers {+ let prefix = "language_model.model.layers.\(li)"+ for k in ["mlp.gate_proj", "mlp.up_proj", "mlp.down_proj", "router.proj"] {+ overrides[prefix + "." + k] = ["bits": 8, "group_size": arch.groupSize]+ }+ }+ var quant: [String: Any] = [+ "bits": 4, "group_size": arch.groupSize, "mode": "affine"+ ]+ for (k, v) in overrides { quant[k] = v }++ let textConfig: [String: Any] = [+ "hidden_size": arch.hidden,+ "intermediate_size": arch.intermediate,+ "moe_intermediate_size": arch.moeIntermediate,+ "num_attention_heads": arch.numHeads,+ "num_key_value_heads": arch.numKVHeads,+ "num_global_key_value_heads": arch.numGlobalKVHeads,+ "head_dim": arch.headDim,+ "global_head_dim": arch.globalHeadDim,+ "vocab_size": arch.vocab,+ "num_hidden_layers": arch.numLayers,+ "num_experts": arch.numExperts,+ "top_k_experts": arch.topK,+ "sliding_window": arch.slidingWindow,+ "final_logit_softcapping": 30.0,+ "rope_parameters": [+ "sliding_attention": ["rope_theta": 10000.0, "rope_type": "default"],+ "full_attention": ["rope_theta": 1000000.0, "rope_type": "proportional",+ "partial_rotary_factor": 0.25]+ ],+ "layer_types": arch.layerTypes,+ "tie_word_embeddings": true,+ "attention_k_eq_v": true,+ "hidden_activation": "gelu_pytorch_tanh"+ ]+ let config: [String: Any] = [+ "architectures": ["Gemma4ForConditionalGeneration"],+ "model_type": "gemma4",+ "quantization": quant,+ "text_config": textConfig+ ]+ let configData = try JSONSerialization.data(withJSONObject: config, options: [.sortedKeys])+ try configData.write(to: URL(fileURLWithPath: (dir as NSString).appendingPathComponent("config.json")))++ // -- Write model.safetensors.index.json.+ var weightMap: [String: String] = [:]+ for (name, _, _, _) in tensors { weightMap[name] = shardName }+ let indexObj: [String: Any] = [+ "metadata": ["format": "mlx"],+ "weight_map": weightMap+ ]+ let indexData = try JSONSerialization.data(withJSONObject: indexObj, options: [.sortedKeys])+ let indexPath = (dir as NSString).appendingPathComponent("model.safetensors.index.json")+ try indexData.write(to: URL(fileURLWithPath: indexPath))+ return Snapshot(shardPath: shardPath)+ }++ // MARK: - Tensor builders++ private static func appendQuantizedWeight(name: String,+ outerShape: [Int],+ innerLogical: Int,+ bits: Int,+ groupSize: Int,+ into tensors: inout [(String, String, [Int], [UInt8])],+ rng: inout SplitMix64) {+ precondition(innerLogical % groupSize == 0)+ let factor = 32 / bits+ precondition(innerLogical % factor == 0)+ let innerSource = innerLogical / factor+ let shape = outerShape + [innerSource]+ let elements = shape.reduce(1, *)+ var bytes = [UInt8](repeating: 0, count: elements * 4)+ for i in 0..<bytes.count { bytes[i] = UInt8(rng.next() & 0xFF) }+ tensors.append((name + ".weight", "U32", shape, bytes))++ let groups = innerLogical / groupSize+ let companionShape = outerShape + [groups]+ let companionElems = companionShape.reduce(1, *)+ var sb = [UInt8](repeating: 0, count: companionElems * 2)+ for i in 0..<sb.count { sb[i] = UInt8(rng.next() & 0xFF) }+ tensors.append((name + ".scales", "BF16", companionShape, sb))+ var bb = [UInt8](repeating: 0, count: companionElems * 2)+ for i in 0..<bb.count { bb[i] = UInt8(rng.next() & 0xFF) }+ tensors.append((name + ".biases", "BF16", companionShape, bb))+ }++ private static func appendUnquantizedBF16(name: String, shape: [Int],+ into tensors: inout [(String, String, [Int], [UInt8])],+ rng: inout SplitMix64) {+ let elements = shape.reduce(1, *)+ var bytes = [UInt8](repeating: 0, count: elements * 2)+ for i in 0..<bytes.count { bytes[i] = UInt8(rng.next() & 0xFF) }+ tensors.append((name, "BF16", shape, bytes))+ }++ // MARK: - Safetensors writer++ private static func writeShard(path: String,+ tensors: [(String, String, [Int], [UInt8])]) throws {+ var off: UInt64 = 0+ var headerEntries: [(String, [String: Any])] = []+ for (name, dtype, shape, bytes) in tensors {+ let begin = off+ let end = begin + UInt64(bytes.count)+ headerEntries.append((name, [+ "dtype": dtype,+ "shape": shape,+ "data_offsets": [begin, end]+ ]))+ off = end+ }+ var headerDict: [String: Any] = [:]+ for (n, e) in headerEntries { headerDict[n] = e }+ headerDict["__metadata__"] = ["format": "mlx"]+ // Ensure deterministic key ordering for the header — JSONSerialization+ // sortedKeys handles that for us.+ let headerData = try JSONSerialization.data(withJSONObject: headerDict,+ options: [.sortedKeys])+ // Pad header so payload starts on an 8-byte boundary (matches MLX+ // convention and trips fewer downstream surprises).+ var padded = headerData+ while padded.count % 8 != 0 { padded.append(0x20) } // space pad++ let fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0o644)+ precondition(fd >= 0, "open failed for \(path)")+ defer { close(fd) }+ var headerLenLE = UInt64(padded.count).littleEndian+ withUnsafeBytes(of: &headerLenLE) { raw in+ _ = write(fd, raw.baseAddress, 8)+ }+ padded.withUnsafeBytes { raw in+ _ = write(fd, raw.baseAddress, padded.count)+ }+ for (_, _, _, bytes) in tensors {+ bytes.withUnsafeBufferPointer { ptr in+ _ = write(fd, ptr.baseAddress, ptr.count)+ }+ }+ }+}++/// Tiny deterministic PRNG. We do not need crypto quality — just stable+/// byte streams across test runs.+struct SplitMix64 {+ private var state: UInt64+ init(seed: UInt64) { self.state = seed }+ mutating func next() -> UInt64 {+ state &+= 0x9E3779B97F4A7C15+ var z = state+ z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9+ z = (z ^ (z >> 27)) &* 0x94D049BB133111EB+ return z ^ (z >> 31)+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/System/DiskSpaceCheckerTests.swift b/Tests/TurboFieldfareRepack/Core/System/DiskSpaceCheckerTests.swiftnew file mode 100644index 00000000..229bac36--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/System/DiskSpaceCheckerTests.swift@@ -0,0 +1,55 @@+import Foundation+import Testing+@testable import TurboFieldfareRepackCore++@Suite struct DiskSpaceCheckerTests {+ @Test func assessmentDoesNotCreateMissingTargetAndUsesExistingAncestor() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("turbofieldfare-space-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let target = root.appendingPathComponent("nested/model.gturbo", isDirectory: true)++ let result = try DiskSpaceChecker.assess(path: target.path, bytes: 100, reserveBytes: 20)++ #expect(result.path == root.path)+ #expect(result.requiredBytes == 120)+ #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("nested").path))+ }++ @Test func authoritativeCheckUsesSameRequirement() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("turbofieldfare-space-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let target = root.appendingPathComponent("model.gturbo", isDirectory: true)++ let assessed = try DiskSpaceChecker.assess(path: target.path, bytes: 100, reserveBytes: 20)+ let required = try DiskSpaceChecker.requireAvailable(path: target.path,+ bytes: 100,+ reserveBytes: 20)+ #expect(assessed.requiredBytes == required.requiredBytes)+ }++ @Test func insufficientCheckReportsExactShortfall() throws {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("turbofieldfare-space-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let target = root.appendingPathComponent("model.gturbo", isDirectory: true)+ let available = try DiskSpaceChecker.assess(path: target.path,+ bytes: 0,+ reserveBytes: 0).availableBytes++ #expect {+ _ = try DiskSpaceChecker.requireAvailable(path: target.path,+ bytes: available,+ reserveBytes: 1)+ } throws: { error in+ guard case RepackError.diskSpaceInsufficient(_, let required, let actual) = error else {+ return false+ }+ return required == available + 1 && actual == available+ }+ }+}diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.mdnew file mode 100644index 00000000..c51a1d56--- /dev/null+++ b/docs/BENCHMARKS.md@@ -0,0 +1,107 @@+# Benchmarks++This page records TurboFieldfare measurements on an 8 GB M2 MacBook Air and a+24 GB M5 Pro. Each number belongs to the workload shown. Prompt length,+generated length, cache state, and hardware all change throughput, so ranges+across workloads are not run-to-run variation.++All rows use greedy decoding and the same source checkpoint. TurboFieldfare+uses the model installed by the+[command-line instructions](../README.md#command-line-interface). Decode rate+excludes model installation, model loading, and prompt prefill.++## Results at a glance++| Host and runtime | Decode rate | Reported memory |+| --- | ---: | ---: |+| 8 GB M2, TurboFieldfare | 5.10-6.30 tok/s | ~1.9-2.1 GB footprint |+| 24 GB M5 Pro, TurboFieldfare | 31.96-36.08 tok/s | ~2.0-2.2 GB footprint |+| 24 GB M5 Pro, mlx-lm | 76.33-82.07 tok/s | 8.3-9.8 GB RSS; 14.7-15.3 GB GPU allocation |++## M2 measured decode++These rows ran on a `Mac14,15` M2 MacBook Air with 8 GB of memory. No+experiment, profiler, or trace mode was active.++| Prompt / generated tokens | Prefill | TTFT | Decode | Peak RSS / footprint |+| --- | ---: | ---: | ---: | ---: |+| 6 / 32 | 7,025 ms | 7,979 ms | 6.30 tok/s | 1,304 / 1,791 MiB |+| 121 / 64 | 7,934 ms | 8,862 ms | 5.10 tok/s | 1,528 / 1,776 MiB |+| 527 / 64 | 21,736 ms | 22,649 ms | 5.90 tok/s | 1,535 / 1,886 MiB |+| 1,017 / 128 | 36,729 ms | 37,656 ms | 5.38 tok/s | 1,455 / 1,971 MiB |++Each workload ran once in a fresh process. The file cache was warm but+uncontrolled, and every row produced the same token IDs as its validation+control. These four points show the production path running under the 8 GB+rule; they do not form a confidence interval or describe sustained long+generation.++### Where the short M2 row spent its time++A separate diagnostic pass on the six-token prompt divided a 162.8 ms decode+step into four broad parts:++| Work | ms/token |+| --- | ---: |+| Expert reads | 83.1 |+| Waiting in the command-buffer pipeline | 55.6 |+| Tied output head | 14.2 |+| Other runtime work | 9.9 |++The diagnostic instrumentation disabled the normal command-buffer pipeline+and reduced throughput to 4.23 tok/s. The breakdown explains where that run+spent time; it does not describe independent speedups or a performance bound.++## M5 measured decode++These rows ran on 2026-07-16 on a 24 GB M5 Pro (`Mac17,8`) with macOS 26.5.1,+Xcode 26.6, and Swift 6.3.3. No profiler or trace mode was active.++One warmup preceded three measured rows per workload. The table reports+medians; the file cache was warm but uncontrolled.++| Prompt / generated tokens | Prefill / TTFT | Decode | Peak RSS / footprint |+| --- | ---: | ---: | ---: |+| 121 / 64 | 4,980 / 5,606 ms | 31.96 tok/s | 1,764 / 1,893 MiB |+| 527 / 64 | 7,297 / 7,922 ms | 36.08 tok/s | 1,792 / 1,991 MiB |+| 1,017 / 128 | 10,134 / 10,767 ms | 33.96 tok/s | 1,810 / 2,088 MiB |++## Same-host MLX comparison++The same M5 Pro ran MLX 0.32.0 and mlx-lm 0.31.3 against the same checkpoint,+prompt-token IDs, and generated-token counts. MLX measured 82.07, 80.25, and+76.33 tok/s for the 121-, 527-, and 1,017-token prompts.++Treat this as throughput context, not a complete engine comparison:++- The engines ran in separate blocks rather than a balanced, interleaved order.+- Their first-token clocks started at different points, so TTFT is not comparable.+- Generated IDs matched for the shortest prompt but diverged for the two longer prompts.+- TurboFieldfare recorded a 1.89-2.09 GiB physical footprint. MLX reported+ 14.66-15.31 GB of peak GPU allocation and 8.27-9.79 GB of peak process RSS.+ Those counters measure different things and should not be compared as a+ direct memory ratio.++The MLX process required the larger host and is not an 8 GB TurboFieldfare+deployment path.++## Reproduce and contribute a result++The [community benchmark guide](COMMUNITY_BENCHMARKS.md) uses the established+1,017-token prefill fixture followed by 256 greedy decode tokens. It provides+the release CLI command, machine-preparation checklist, three-run policy, and+issue template. The public CLI's timing footer reports the production decode+rate without requiring a separate research benchmark harness.++The community workload extends the historical 1,017 / 128 row above to 256+generated tokens. Compare community submissions with other runs of the same+protocol rather than treating them as direct reproductions of that row.++A current checkout may not reproduce a historical number after the runtime,+compiler, or operating system changes. Report the commit and all three rows+rather than presenting one run as a general hardware result.++Read [System design](SYSTEM_DESIGN.md) for the runtime and resource split,+[Experiments](OPTIMIZATION_JOURNEY.md) for the main wins and failures, and the+[measurement lessons](experiments/summaries/09-validation-and-measurement-lessons.md)+for the rules used to evaluate performance changes.diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.mdnew file mode 100644index 00000000..125c643c--- /dev/null+++ b/docs/COMMUNITY_BENCHMARKS.md@@ -0,0 +1,163 @@+# Contribute a benchmark result++Results from other Apple Silicon Macs help show where TurboFieldfare runs well+and where it needs more work. This guide uses the+[canonical 1K prompt](benchmark-prompts/prefill-1024.txt) from the project's+prefill and decode benchmarks. It contains 1,017 model tokens including BOS.+Each run generates 256 greedy tokens so reports from different machines remain+comparable.++This is an explicit reproducibility workload, not the interactive product+default. The app and CLI normally allow up to 1,024 new tokens and sample with+temperature `0.1`, Top-K `64`, and Top-P `0.95`; the commands below override+those values with a fixed 256-token greedy decode.++The public package uses `TurboFieldfareCLI` for this measurement. Its timing+footer runs the production defaults and reports decode-only tokens per second.+It excludes model installation, model loading, and prompt prefill.++## Before you run++Install the model with the [README instructions](../README.md#command-line-interface),+then prepare the Mac:++1. Connect a laptop to power and turn off Low Power Mode. Use the normal+ Automatic energy mode unless you clearly report another mode.+2. Build the release executable before measuring:++ ```bash+ swift build -c release --product TurboFieldfareCLI+ ```++3. Quit every app you can, leaving only Terminal. In particular, close the+ TurboFieldfare Mac app, Xcode, browsers, video calls, games, screen recorders,+ local model runners, downloads, backups, and file indexing that you started.+4. Let background CPU activity and the Mac's temperature settle.+5. Check for another model process:++ ```bash+ pgrep -fl 'TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'+ ```++ Continue only when this prints nothing. Quit a listed app normally; do not+ start two model runs at once.++Do not change the prompt, token count, temperature, or public runtime defaults+for the standard result.++## Record the machine++From the repository root, collect a privacy-safe system summary:++```bash+mkdir -p benchmark-results+{+ git status --short+ git rev-parse HEAD+ sw_vers+ swift --version+ system_profiler SPHardwareDataType |+ awk -F': ' '/Model Name|Model Identifier|Chip|Total Number of Cores|Memory/ { print $1 ": " $2 }'+ shasum -a 256 scratch/gemma4.gturbo/manifest.json+ shasum -a 256 docs/benchmark-prompts/prefill-1024.txt+} 2>&1 | tee benchmark-results/system.txt+```++An empty first line from `git status --short` means the checkout is clean. If it+prints changes, either use a clean checkout or describe those changes in the+report. The filtered hardware command omits the serial number and hardware UUID,+but review `benchmark-results/system.txt` before sharing it.++## Run the fixed workload++First run one warmup. It also confirms that the model loads and the prompt+completes:++```bash+.build/release/TurboFieldfareCLI \+ --model scratch/gemma4.gturbo \+ --prompt "$(cat docs/benchmark-prompts/prefill-1024.txt)" \+ --max-new 256 \+ --max-context 4096 \+ --temperature 0 \+ > benchmark-results/warmup.txt 2>&1++tail -n 2 benchmark-results/warmup.txt+```++Then run three measured rows, sequentially:++```bash+for run in 1 2 3; do+ output="benchmark-results/run-${run}.txt"+ .build/release/TurboFieldfareCLI \+ --model scratch/gemma4.gturbo \+ --prompt "$(cat docs/benchmark-prompts/prefill-1024.txt)" \+ --max-new 256 \+ --max-context 4096 \+ --temperature 0 \+ > "$output" 2>&1 || break+ tail -n 2 "$output"+done+```++Each successful file ends with a timing footer. Confirm that it contains this+workload shape:++```text+prefill=1017tok new=256tok+```++Collect the three timing lines for easy copy and paste:++```bash+grep -h '^\[stop=' benchmark-results/run-*.txt |+ tee benchmark-results/summary.txt+```++This protocol uses one warmup followed by three fresh CLI processes. The file+cache is warm but uncontrolled. Do not purge caches or average these rows with+runs made under different conditions.++## Report the result++Open an issue in this repository with the title+`Benchmark: <chip>, <memory>, <macOS version>`. Paste this template:++````markdown+## TurboFieldfare benchmark++- Energy mode: Automatic / High Power / other+- Connected to power: yes / no+- Other apps: quit / list anything left open+- Thermal state before run: settled / uncertain+- Protocol changes: none / describe every change++### System++```text+Paste benchmark-results/system.txt here.+```++### Results++```text+Paste benchmark-results/summary.txt here.+```++### Notes++Add unexpected output, errors, throttling, or other observations.+````++Attach the three `run-*.txt` files when possible. They contain the generated+completion and timing footer, which helps us spot incomplete or non-equivalent+runs.++If you want to test a different app setting or code change, submit the standard+result first. Then change one thing, repeat the same warmup and three-run policy,+and label the follow-up as experimental. Never combine rows from different+settings into one standard result.++See [Benchmarks](BENCHMARKS.md) for the current reference measurements and how+to interpret comparisons.diff --git a/docs/IMPLEMENTATION_REFERENCES.md b/docs/IMPLEMENTATION_REFERENCES.mdnew file mode 100644index 00000000..91c99bcf--- /dev/null+++ b/docs/IMPLEMENTATION_REFERENCES.md@@ -0,0 +1,92 @@+# Implementation references++TurboFieldfare builds on work by other developers and researchers. These are+the sources that materially shaped its Gemma 4 implementation, Metal kernels,+out-of-core runtime, and experiments under the 8 GB memory constraint.++Upstream code references whose exact behavior mattered are pinned to commits+checked on 2026-07-16. Project home pages remain branch-level when they are+included for broader design context rather than a line-level claim.++## Model and weights++- The official [Gemma 4 model card](https://ai.google.dev/gemma/docs/core/model_card_4)+ defines the model family, the 26B A4B mixture-of-experts shape, hybrid+ attention, and intended capabilities.+- Hugging Face Transformers provides executable decoder cross-checks for+ [Gemma 4 math](https://github.com/huggingface/transformers/blob/a8609bed2ad1593e7d756006525a10053d4d5bc6/src/transformers/models/gemma4/modular_gemma4.py),+ [configuration](https://github.com/huggingface/transformers/blob/a8609bed2ad1593e7d756006525a10053d4d5bc6/src/transformers/models/gemma4/configuration_gemma4.py),+ and [RoPE utilities](https://github.com/huggingface/transformers/blob/a8609bed2ad1593e7d756006525a10053d4d5bc6/src/transformers/modeling_rope_utils.py).+ TurboFieldfare used them to verify normalization, K/V derivation, routing,+ MoE combination, layer scaling, and final logits.+- [MLX-LM Gemma 4](https://github.com/ml-explore/mlx-lm/blob/15b522f593b7ca5fbc0cac6f7572d40859d2d8fe/mlx_lm/models/gemma4_text.py)+ and [MLX-VLM Gemma 4](https://github.com/Blaizzy/mlx-vlm/blob/84f43753380355c0455a2bafb291d4b7cbcf81d1/mlx_vlm/models/gemma4/language.py)+ supplied independent implementation checks. MLX-LM also served as the+ bounded logit and quality reference.+- The [Majentik Gemma 4 MLX 4-bit checkpoint](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit),+ pinned at [`cc499c86`](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit/tree/cc499c86a958ea7f05cffaa91c7e7243240dabbe),+ is the source of the weights, configuration, and tokenizer. The repacker+ preserves its group-64 MLX affine values rather than requantizing them.+- [Hugging Face swift-transformers](https://github.com/huggingface/swift-transformers)+ is the direct tokenizer dependency. TurboFieldfare adds bounded streaming+ detokenization around it.++## Metal and kernels++- Pinned [MLX Metal kernels](https://github.com/ml-explore/mlx/tree/4367c73b60541ddd5a266ce4644fd93d20223b6e/mlx/backend/metal/kernels)+ were the main reference for quantized QMV/QMM, RMSNorm, RoPE, and attention+ geometry. The tagged [v0.32.0 vector SDPA](https://github.com/ml-explore/mlx/blob/v0.32.0/mlx/backend/metal/kernels/sdpa_vector.h)+ inspired the D512 one-pass attention variant.+- Pinned [llama.cpp/ggml Metal](https://github.com/ggml-org/llama.cpp/tree/79bba02a6741de194912d370015866414faa83ad/ggml/src/ggml-metal)+ informed row-SIMD quantized matvec, register-resident decode,+ capability-gated kernels, memory mappings, and resource hazards.+- [LeetCUDA](https://github.com/xlite-dev/LeetCUDA) supplied transferable+ patterns for SIMD-per-row GEMV, packed loads, reductions, online softmax, and+ split-KV attention.++<a id="apple-metal"></a>+### Apple platform contracts++- Apple's [Metal Performance Primitives guide](https://developer.apple.com/download/files/Metal-Performance-Primitives-Programming-Guide.pdf)+ and [Metal tensor session](https://developer.apple.com/videos/play/wwdc2026/330/)+ define the platform contract for `MTLTensor`, cooperative inputs,+ `mpp::tensor_ops::matmul2d`, execution scopes, data types, and alignment.+ They guided the staged affine MPP prefill path.++### Apple shader operations++- Apple's [inline Metal 4 operations](https://developer.apple.com/documentation/metal/running-inline-ml-operations-in-a-shader-with-metal-4)+ documents shader-local tensors and inline cooperative operations considered+ in the Metal 4 experiments.++## Out-of-core inference++- [`danveloper/flash-moe`](https://github.com/danveloper/flash-moe),+ [`Anemll/flash-moe`](https://github.com/Anemll/flash-moe), and+ [SwiftLM](https://github.com/SharpAI/SwiftLM) informed Apple-Silicon+ SSD-backed MoE, positional reads, reusable expert buffers, I/O workers, and+ GPU synchronization.+- Apple's [LLM in a Flash](https://arxiv.org/abs/2312.11514) framed the+ out-of-core problem around transferred bytes, useful read size, and flash+ scheduling.+- Apple's Darwin [`pread(2)`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/pread.2.html),+ [`mmap(2)`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/mmap.2.html),+ and [`fcntl(2)`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html)+ document concurrent offset reads, page alignment, and file-advice APIs such+ as `F_RDADVISE`.++## KV-cache and attention research++- [FlashAttention](https://arxiv.org/abs/2205.14135),+ [online normalizer calculation](https://arxiv.org/abs/1805.02867), and+ [Flash-Decoding](https://crfm.stanford.edu/2023/10/12/flashdecoding.html)+ supplied the tiled-attention and associative online-softmax principles behind+ TurboFieldfare's split-KV kernels.+- Pinned [vLLM attention operators](https://github.com/vllm-project/vllm/tree/530852f9591a822ff4065908778a58fa015f0e69/vllm/v1/attention/ops)+ and [vLLM Metal kernels v2](https://github.com/vllm-project/vllm-metal/tree/11f1b453b74c60d113d67f9a5e7fda41500fd5b5/vllm_metal/metal/kernels_v2)+ were implementation references for transformed and quantized KV caches,+ fused dequantization, and online-softmax reduction.+- [TurboQuant](https://arxiv.org/abs/2504.19874) informed the transformed and+ quantized K4/V4 cache experiments.+- [Open-TQ-Metal](https://arxiv.org/abs/2604.16957) informed the per-group+ asymmetric INT4 KV and `affine4g32` experiment.diff --git a/docs/OPTIMIZATION_JOURNEY.md b/docs/OPTIMIZATION_JOURNEY.mdnew file mode 100644index 00000000..a12d02a0--- /dev/null+++ b/docs/OPTIMIZATION_JOURNEY.md@@ -0,0 +1,248 @@+# Optimizing a 14.4 GB model for an 8 GB machine++TurboFieldfare runs Gemma 4 26B-A4B with about 14.4 GB of packed text-only+weight payload on an 8 GB Apple Silicon machine. The completed installation is+about 14.5 GB after its manifest, expert layout, and tokenizer files. The model+cannot remain resident in memory, so the runtime keeps roughly 1.58 GB of+common weights resident and streams the roughly 11.6 GB routed-expert payload+from NVMe. This constraint shaped the useful optimizations: reduce demand I/O,+expose enough GPU parallelism, and never buy speed by loading the model into+RAM.++This article covers the experiments that materially changed the runtime. The+[experiment inventory](experiments/EXPERIMENT_INVENTORY.md) retains the complete record,+including narrow wins and negative results. Measurements below come from their+named controls and should not be combined into one historical speed curve.++## What worked and what did not++The successful experiments attacked costs visible in the complete token path.+Parallel bounded `pread` made expert misses explicit and schedulable;+persistent multi-threadgroup MoE exposed enough GPU work; a 16-slot LFU cache+and coarse compute/I/O overlap reused resident experts; layout-aware INT4+vectorization shortened hot kernels; split-KV attention and staged affine MPP+changed the shape of expensive work; and one-pass Gumbel sampling removed+repeated vocabulary scans. Each change survived production-shaped and+end-to-end gates.++The unsuccessful experiments often improved a proxy while making the runtime+worse. Demand-paged `mmap` won only with warm pages. Cooperative MoE reduced+the number of row streams but starved the GPU. Progressive expert overlap+added synchronization and regressed decode. Simple Darwin read hints were+neutral; RDADVISE reversed at longer contexts; and `F_SPECULATIVE_READ`, read+reordering, grouped `preadv`, and MTLIO won narrow probes but not broader+runtime gates. Packed K4/V4 saved 82 MiB against the final FP16 ring but failed+the quality gate. A monolithic fusion removed dispatches yet lost throughput.++The sections below pair these wins with the nearby failures that clarified+them. Changes that claim identical math must preserve exact output; changes+that reorder floating-point operations must pass deterministic,+reference-relative quality tests. A promising microbenchmark starts an+experiment, but only end-to-end speed and quality decide whether it ships.++## Explicit reads transformed expert streaming++The first streaming design memory-mapped the expert pool and relied on demand+faults. It looked attractive because the source code contained no explicit+copy, but it gave the virtual-memory system control over read timing and+concurrency. Warm mapped pages won a narrow benchmark; the cold working set on+the target machine did not stay warm.++A cold expert read took 9.88 ms through demand paging and 2.79 ms through+`pread`. In the full streaming simulation, `mmap` delivered about 0.50 tok/s,+while parallel `pread` reached 3.97 tok/s. The production runtime maps the+common model file for Metal access, but services routed-expert misses from+per-layer files through explicit reads into bounded slots. Parallel reads later+moved staged decode from about 1.13 to 2.08 tok/s. See [`mmap` versus+`pread`](experiments/summaries/01-model-install-and-expert-io.md#io-01).++The installer follows the same design. Remote repacking downloaded+14,952,958,284 source bytes in 229 range requests, with a largest transfer of+64 MiB and only 524,288 bytes of payload and scratch heap. Installation is not+an offline exception to the memory architecture.++## MoE needed parallel work, reuse, and coarse overlap++After explicit I/O, routed MoE dominated GPU time. A SIMD-cooperative kernel+assigned several lanes to one expert, reducing hundreds of independent row+streams to eight expert streams. The second command-buffer phase—the routed+computation after expert I/O, called `cb2` in the profiler—grew from about 230+to 527 ms.++Persistent multi-threadgroup workers made the opposite choice. Threadgroups+claimed independent rows until the dispatch completed, cutting `cb2` from+about 239 to 60 ms, a 75% reduction. Paired decode improved from 2.188 to 3.313+tok/s, or 51%. This was the largest end-to-end gain from redesigning a core+forward-pass Metal kernel. It came from exposing more schedulable work, not+from making each worker's arithmetic more elaborate. [Persistent+MoE](experiments/summaries/02-decode-moe-int4-and-router.md#dec-03) became the+production structure.++A bounded 16-slot cache per layer then reduced repeated expert I/O from about+166 to 88 ms and raised decode from 3.313 to 4.261 tok/s. Replacing LRU with+LFU later reduced canonical I/O from 72.6 to 64.8 ms/token and raised decode+from 5.476 to 5.631 tok/s; long-run I/O fell from 110.5 to 97.9 ms/token. A+64-token window reduced simulated misses slightly but produced neutral or+mixed real-decode results, so monotonic LFU remained the default. [The cache+policy record](experiments/summaries/03-expert-cache-prediction-and-layout.md#cache-01)+keeps the full comparison.++Cacheability did not imply predictability. Expert choices repeated enough+within the same layer across tokens for LFU to help, but adjacent layers within+one token shared almost no experts. Across 448 decode tokens, the mean+adjacent-layer Jaccard was 0.039, the median was zero, and copying layer L's+experts predicted only 7% of layer L+1. That decisive [offline+no-go](experiments/summaries/03-expert-cache-prediction-and-layout.md#cache-05)+stopped speculative cross-layer prefetch before runtime wiring. Reuse paid+through caching, but the tested routing signal could not identify the required+weights early enough to prefetch them.++The shared dense MLP provided a safe overlap boundary: it uses resident+weights, so the GPU can execute it while the CPU fills routed-expert misses.+That change moved a later control from 4.404 to 4.736 tok/s.++Finer-grained overlap failed. Progressive execution launched each expert group+as soon as its reads completed, but the repaired implementation regressed the+1K/256 gate from 4.799 to 4.648 tok/s and diverged. The coarser hit-first split+was faster and easier to synchronize. Overlap helped only when ownership and+dependencies remained explicit.++## Vectorization helped when it respected the storage layout++The model stores affine INT4 weights in groups of 64, decoded as+`q * scale + bias` with BF16 metadata. The successful routed-MoE kernel handled+four groups together, used `half4` activation loads, and exposed independent+arithmetic. Routed GPU time fell from 36.5 to 31.3 ms. The gain came mainly+from shorter dependency chains and instruction-level parallelism, not from+the widest possible integer load.++Applying 32-bit packed loads to resident GEMV initially passed an offset-zero+fixture and then produced garbage in real decode. Resident sub-tensors were+only guaranteed 2-byte alignment because BF16 metadata preceded the weights.+Two `ushort` loads were safe and still reduced LM-head GPU time from about+21.5 to 16 ms. Vector width is therefore a property of the live byte offset,+not just the element format. [The corrected+path](experiments/summaries/02-decode-moe-int4-and-router.md#dec-07) made+production-shaped offsets part of later kernel tests.++## Attention and prefill rewarded structural changes++Split-KV attention divided the cached sequence across threadgroups and merged+online-softmax partials in a second pass. It improved isolated sliding-window+attention by about 3.3x and full 4K attention by about 4.1x. Short-context+decode stayed nearly flat, whereas long-context GPU time in that phase fell+about 28% as attention's share of the step grew.++A later MLX-style geometry reduced isolated full-attention time by roughly+71–74%, yet complete decode improved only 1.30–1.59%. The measurements did not+conflict. Only five of thirty layers use full attention, and attention occupied+a small fraction of these token steps. The microbenchmark proved that the+geometry worked; the full pass measured how often that faster work mattered.++Chunked prefill replaced scalar prompt replay. Increasing the bounded chunk+from 32 to 128 reduced a 1,017-token prefill from 92.89 to 52.35 seconds.+Staged affine MPP then dequantized a small FP16 tile, ran the hardware matrix+primitive, and discarded the tile. It improved the 512-token prefill gate by+about 11% without changing the source format or violating the memory budget.+[Direct shader-local UInt4](experiments/summaries/06-prefill.md#pf-13) was+20.40% slower than this staged path at M128.++Prefill showed the same effect. Batched routed MoE cut its isolated kernel time+by about 31%, while balanced prefill improved about 2%. Reusing activation+tiles in the remaining quantized matrix kernels improved individual families+by 3–10%, but their combined whole-prefill opportunity was only about 0.4%+after earlier promotions. The tile-reuse optimization worked locally; its+target was no longer large enough to justify promotion.++## Sampling removed an algorithmic factor++Sampling exposed an algorithmic mistake rather than a kernel bottleneck. The+old non-greedy path repeatedly extracted candidates across the entire+vocabulary. One Gumbel value per entry followed by a single maximum reduction+restored sampled decode to roughly greedy speed. Because the baseline was very+naive, its speedup ratio would exaggerate the value of the optimization. The+useful result was removing an unnecessary algorithmic factor, not accelerating+the old loop.++## Promising results that did not survive validation++`F_RDADVISE` produced credible short-run wins. One paired median reduced I/O+from 87.4 to 72.2 ms/token and raised throughput from 5.176 to 5.449 tok/s.+Longer and differently cached runs reversed the result: at a 1,536-token+context, advice produced 4.028 tok/s against 5.687 with advice disabled.+Coalescing adjacent advice ranges was a small success: 10,385 requested ranges+became 10,144 calls in one 128-token run. Routed misses were rarely adjacent,+however, and call limits, cooldowns, adaptive policies, and asynchronous advice+never found a stable rule across workloads. Production keeps RDADVISE off+because the runtime cannot reliably identify the favorable state. [The+RDADVISE record](experiments/summaries/04-rdadvise.md) preserves both the+initial win and the later rejection.++Other read-side candidates failed for different reasons. `F_RDAHEAD=0` and+`F_NOCACHE` were neutral. `F_SPECULATIVE_READ` showed page warming and up to+10.63 GB/s in a probe, then reduced decode from 4.937 to 4.742 tok/s and raised+prefill from 82.50 to 123.64 seconds in the first end-to-end pair. Sorting+misses by file offset improved one row from 6.012 to 6.117 tok/s, then reduced+the repeated median from 6.099 to 6.067 tok/s while I/O rose from 75.0 to+76.7 ms/token. MTLIO reached 13.1-13.3 GB/s on warm reads, but only 5.4-7.5% of+observed misses were fully warm. Dedicated executor and worker-pool variants+also failed to beat bounded parallel `pread`, which remained the production+path. [The expert I/O record](experiments/summaries/01-model-install-and-expert-io.md)+keeps the individual controls and outcomes.++Packed K4/V4 KV storage also looked stronger against an obsolete control. It+used about 223 MiB at 4K versus roughly 880 MiB for the old linear FP16 cache.+An exact FP16 ring then exploited the model's 25 sliding-window layers and+required only about 305 MiB, reducing K4/V4's incremental saving to 82 MiB.+The packed path subsequently lost 5.0781 top-1 percentage points and worsened+mean negative log-likelihood. It remains an explicit experiment; exact FP16 is+the default.++Fusion produced three different outcomes. Targeted QKV, layer-tail, and+row-based head fusions reached production after parity checks and whole-step+gates. A monolithic post-attention/pre-FFN wrapper was a clear+regression: it removed launches and intermediates but achieved only 1.811+tok/s versus 2.756 for the control because adjacent operations had+incompatible geometry and data lifetimes.++Other candidates proved a local gain without proving a system gain. Tiling the+language-model head cut its GPU time from 14.2 to 13.1 ms/token. That saved+only 1.1 ms inside a 167.7 ms token step, a theoretical reduction of about+0.66%, while pipeline wait increased by 1.4 ms. The resulting 5.962 versus+5.926 tok/s comparison was therefore inconclusive, not evidence of a+regression. Fused Gumbel sampling similarly averaged 5.124 versus 5.192 tok/s,+but variation between repeats and divergent sampled paths exceeded the mean+gap. These candidates remained off by default because they did not demonstrate+a repeatable whole-step gain, not because they were proven slower. [The fusion+record](experiments/summaries/07-fusions-head-and-orchestration.md) retains the+individual gates.++Other local proxies failed in similar ways. A trace-trained expert layout with+grouped adjacent `preadv` improved natural-text replay by 3.61% but regressed+near-4K decode by 16.1%. An argument-buffer ring cut 21,217 allocations to two+yet slowed long prefill by about 9%. Fewer reads, allocations, or dispatches+describe a mechanism; only end-to-end time and quality determine whether that+mechanism belongs in production.++## The durable method++The successful experiments converged on a repeatable process: profile the+whole step, isolate the largest measured share, reproduce production shapes+and resource contracts, then return to a clean end-to-end comparison. Exact+changes require identity; reordered floating-point kernels require a quality+oracle. Controls and candidates must be interleaved when page cache, warm-up,+or thermals can bias the result.++Promotion is asymmetric. A candidate needs a repeatable gain to become the+default; calling it slower requires a repeatable loss. A narrow difference+that cannot be separated from run-to-run variation is inconclusive, so the+default stays unchanged without turning the result into a rejection.++The main gains came from explicit `pread`, persistent MoE parallelism, bounded+expert reuse, safe compute/I/O overlap, layout-aware INT4 vectorization,+split-KV attention, chunked prefill, and one-pass sampling. Their common trait+was not novelty. Each removed a measured system cost while preserving the+8 GB architecture.++For the resulting runtime, see [System design](SYSTEM_DESIGN.md). The dated+result and reproduction command live in [Benchmarks](BENCHMARKS.md).diff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.mdnew file mode 100644index 00000000..74c042d1--- /dev/null+++ b/docs/RUNTIME_CONTROLS.md@@ -0,0 +1,73 @@+# Runtime controls++The Mac app exposes a small set of runtime controls in its fixed right settings+pane. The defaults are the supported production configuration. Change one+control at a time, reload the model, and restore the defaults before normal+use.++## Generation controls++The Mac app and CLI share these interactive defaults:++| Control | Mac values | CLI flag | Default | Effect |+| --- | --- | --- | --- | --- |+| Maximum response | 1...4,096 tokens | `--max-new` | 1,024 | Caps newly generated tokens. It does not include prompt tokens. |+| Maximum context | 256...8,192 tokens | `--max-context` | 4,096 | Sets the prompt plus generation KV-cache budget. |+| Temperature | 0...2 in 0.05 steps | `--temperature` | 0.1 | `0` selects deterministic greedy decoding; positive values sample. |+| Top-K | Off or 1...256 | `--top-k` | 64 | Keeps at most K candidates. The CLI value `0` turns it off. |+| Top-P | Off or 0.01...1 | `--top-p` | 0.95 | Keeps candidates within the selected probability mass before Top-K. It is effective only while Top-K is enabled. |+| Repetition penalty | Off or 1...1.8 | `--repetition-penalty` | Off (`1.0`) | Values above `1.0` penalize tokens already present in the sequence. |++With positive temperature, a CLI Top-P below `1` requires Top-K between `1`+and `256`. To disable both truncation controls, pass `--top-k 0 --top-p 1`.+Generation controls apply to the next request and do not require a model+reload. They are interactive product settings, not the fixed community+benchmark protocol.++## Runtime settings++| Control | Values | Production default | Effect |+| --- | --- | --- | --- |+| Expert-cache slots | 8, 16, 24, 32 | 16 | More slots can retain more routed experts and reduce later reads, but values above 16 use more RAM. |+| Expert-cache policy | LFU, LRU | LFU | Selects which resident expert is evicted when a new expert needs a slot. |+| Prompt prefill | On, off | On | On processes known prompt tokens through the chunked prefill path. Off disables that path. |+| Prefill chunk | 32, 64, 128 tokens | 128 | Sets the number of prompt tokens processed per prefill chunk. It has no effect when prefill is off. |+| KV cache | FP16, TurboQuant K4/V4 | FP16 | K4/V4 reduces KV storage, but it is experimental and failed the full quality gate. |+| RDADVISE | Off, Default, Bounded, Adaptive | Off | Applies experimental read advice. Its effect depends on the workload; it may help a short decode and slow a long one. |+| Model verification | Full SHA-256, Trust verified install | Full SHA-256 | Full SHA-256 hashes the model files. Trust verified install checks the bounded install receipt and file sizes instead of hashing every model byte again. |++Changing a runtime control marks the loaded configuration as stale. Reload the+model before generating with the new setting.++## Run an experiment++1. Start from 16 LFU slots, prefill on with a 128-token chunk, FP16 KV,+ RDADVISE off, and Full SHA-256 verification.+2. Keep the prompt and generation controls fixed.+3. Record a baseline after a warmup.+4. Change one runtime control and reload the model.+5. Compare prompt prefill, request TTFT, decode rate, peak memory, and I/O per+ token over repeated runs.+6. Restore the production defaults when the experiment ends.++Use the [community benchmark protocol](COMMUNITY_BENCHMARKS.md) for a standard+production result. A run with changed runtime controls is experimental and must+name the changed setting.++## Read the results++- **Decode rate** measures generated tokens per second after prompt prefill.+- **Request TTFT** includes prompt prefill and the wait for the first generated+ token.+- **Peak memory** in Last run is the highest decode-service memory observed+ during the request. The HUD shows the service's current memory instead of the+ much smaller foreground UI process.+- **I/O / token** reports routed-expert read time per generated token.+- **Advanced** shows decode duration and per-token cb1, cb2, and output-head+ time. When RDADVISE runs, it also shows time, calls, data, and skipped advice.++During chunked prefill, the phase label reports the latest exact progress, for+example `Prefill (128/514)`. The app reports prefill mismatches, unsupported+paths, and RDADVISE failures only when they occur. Treat K4/V4 and RDADVISE as measured+experiments, not replacements for the production defaults. A result is a data+point, not a performance ceiling.diff --git a/docs/SYSTEM_DESIGN.md b/docs/SYSTEM_DESIGN.mdnew file mode 100644index 00000000..e949c473--- /dev/null+++ b/docs/SYSTEM_DESIGN.md@@ -0,0 +1,410 @@+# System design++TurboFieldfare is a model-specific Swift and Metal runtime for text generation+with Gemma 4 26B-A4B on Apple Silicon. Its defining constraint is an 8 GB+machine running a text-only model installation of about 14.5 GB. The runtime+therefore cannot treat the checkpoint as one resident allocation. It keeps the+common language-model weights and working state available to Metal, stores the+routed experts in per-layer files, and reads only the experts selected for the+current work.++This document describes the current `production` path. The major wins,+failures, and reversals belong in [the experiments that shaped+TurboFieldfare](OPTIMIZATION_JOURNEY.md).++Prefill and decode are the two execution modes used below. Prefill processes+known prompt tokens in bounded chunks; decode generates one new token at a+time. Both use the same mapped common weights, mixed KV cache, and per-layer+streamed-expert cache.++## Why the runtime has this shape++Only a few properties of Gemma 4 determine most of the system design:++- The model has 30 transformer layers: 25 sliding-window-attention layers and+ 5 full-attention layers.+- Every layer has 128 routed experts. The router selects 8 for each token.+- A dense shared expert runs in parallel with the routed branch and is added+ without a routing weight.+- The embedding and language-model head share the same quantized weights.+- The source checkpoint already uses MLX affine quantization: packed 4-bit+ values with a BF16 scale and BF16 bias for each group of 64 weights. Router+ and shared-expert projections use 8-bit overrides.++The production FP16 KV cache uses a mixed per-layer layout. The 25+sliding-window layers attend to the latest 1,024 tokens and store K/V in bounded+1,152-row rings, with 128 extra physical rows for chunked-prefill writes. The 5+full-attention layers use append-only linear storage and retain the complete+context. Full-attention layers reuse the raw K projection as the raw V source,+but the two paths immediately diverge: K receives scaled per-head normalization+and RoPE, while V receives a separate no-scale per-head normalization and no+RoPE. The cache therefore stores them separately.++The runtime also preserves Gemma-specific details that affect correctness:+NeoX RoPE, attention scale `1.0`, no router-logit softcap, parallel shared and+routed FFNs, a learned layer scalar, and a final logit softcap of `30.0`.++## Source weights and bounded repack++The installer reads the pinned+[`majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit`](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit)+checkpoint at revision+`cc499c86a958ea7f05cffaa91c7e7243240dabbe`. It does not download a complete+Hugging Face snapshot or materialize a safetensors shard.++Instead, the repacker:++1. reads the source index and tensor metadata;+2. requests bounded remote byte ranges;+3. copies packed values, scales, and biases through tile-sized scratch;+4. writes resident tensors and routed experts directly into their final+ locations;+5. omits vision and audio tensors; and+6. writes `manifest.json` only after every output file is complete and hashed.++The repack changes layout, not quantized values. There is no dequantize and+requantize step. The largest payload and scratch heap in the validated install+were each 524,288 bytes; the full 15 GB-class source never exists in a Swift+heap buffer. See the [command-line instructions](../README.md#command-line-interface)+for installation and [IO-10](experiments/summaries/01-model-install-and-expert-io.md#io-10)+for the validation record.++## The `.gturbo` directory++The installation tree is abridged below:++```text+gemma4.gturbo/+ manifest.json+ verified-install.json+ model_weights.bin+ tokenizer/+ config.json+ tokenizer.json+ tokenizer_config.json+ special_tokens_map.json # optional+ packed_experts/+ layout.json+ layer_00.bin+ ...+ layer_29.bin+```++`model_weights.bin` contains the embedding/head, attention projections,+routers, shared experts, norms, and scalar parameters. Each `layer_XX.bin`+contains 128 fixed-stride routed-expert blobs for one layer. `layout.json`+describes the packed subregions within each blob. The expert stride is page+aligned, and each sub-tensor carries its own offset; Metal kernels bind+subregions of an existing buffer rather than creating one buffer per tensor.++The final manifest is both the install commit marker and the runtime contract.+It records architecture fields, file sizes, and SHA-256 hashes; a missing+manifest means a partial install. `verified-install.json` separately binds a+completed verification to that manifest, directory path, and file set.++Full SHA-256 verification remains the default. It verifies the common files at+load and each routed-expert layer file on first use. The explicit+trusted-receipt policy still hashes `manifest.json`, `model_weights.bin`, and+`packed_experts/layout.json`; for the large layer files, it validates the+receipt binding, manifest metadata, layout, and current size instead of reading+every file end to end again. On load, TurboFieldfare rejects unknown format+flags, incompatible architecture values, missing layer files, invalid+alignment, or a failed integrity check.++## Resource split++The tables distinguish file size, virtual allocation, and physical residency.+They are not interchangeable. The common-model file is 1.51 GiB (1.62 GB in+decimal units). Its hot pages form the roughly 1.58 GB common resident working+set in the memory budget. Slot pages also consume physical memory when filled,+while macOS may keep a separate, opportunistic file-cache copy of recently read+expert data.++Resident and reusable app-owned resources:++| Resource | Current size or capacity | Ownership and behavior |+| --- | ---: | --- |+| Common model file | 1,621,403,708 bytes (1.51 GiB) | Read-only file mapping wrapped by Metal buffers; hot pages form the common resident working set. |+| FP16 KV cache at 4K | About 305 MiB | App-owned. The 25 sliding-window layers use bounded 1,152-row rings; the 5 full-attention layers use linear storage sized for the requested context. |+| Reusable runtime scratch | 15.8 MiB for the production 128-token prefill arena, plus about 2 MiB of split-attention scratch and smaller decode buffers | App-owned and reused across layers or chunks. |++Streamed expert resources:++| Resource | Current size or capacity | Ownership and behavior |+| --- | ---: | --- |+| Routed-expert slots | 16 per opened layer; one page-rounded 3,358,720-byte blob per slot | App-owned buffers allocated with 2 MiB alignment and wrapped by Metal without another copy. Opening all 30 layer streamers reserves about 1.50 GiB of slot capacity; pages become resident as reads fill them. |+| Routed-expert files | 12,897,484,800 bytes (12.01 GiB) on disk | Thirty per-layer files. Only selected blobs enter explicit slots; the files are not mapped as one resident pool. |+| macOS unified file cache | Dynamic | OS-owned second-chance cache. It may make a `pread` cheap, but it is not a guaranteed part of the app budget. |++The default 16-slot capacity is per layer, not a promise that every slot page+is resident immediately after load. Process RSS and physical footprint depend+on which layers and experts have been touched, file-cache state, and memory+pressure. For that reason, the table does not turn static byte counts into an+unmeasured peak-RSS claim.++The production FP16 KV cache is distinct from the experimental packed K4/V4+cache. At 4K, packed K4/V4 uses about 223 MiB and saves about 82 MiB relative+to the current FP16 cache, but it failed the full quality gate. It remains an+explicit experiment and does not fund a larger production expert cache.++## Load and ownership++The loader maps `model_weights.bin` read-only and wraps its aligned regions in+`MTLBuffer` objects without copying their contents into Swift collections.+Routed-expert files open lazily. Each opened layer owns one file descriptor and+a fixed group of slot buffers allocated with 2 MiB alignment. A slot is+allocated once, registered with Metal through `makeBuffer(bytesNoCopy:)`, filled+with `pread`, and reused until the layer streamer is released.++The expert cache records which expert occupies each slot. The production+policy is LFU with recency as the tie-breaker. A hit reuses the existing+buffer. A miss assigns an evictable slot and issues a bounded read. Distinct+misses can run on the I/O executor in parallel, but no two reads may write the+same slot concurrently.++```mermaid+flowchart TB+ subgraph Disk["1. Model package on SSD"]+ direction TB+ MF["Manifest, layout,\nand tokenizer"]+ MW["Common weights\nmodel_weights.bin"]+ LF["Routed experts\n30 layer files\n128 experts each"]+ MF -->|validates at load| MW+ MF -->|validates lazily| LF+ end++ subgraph Memory["2. Unified memory"]+ direction TB+ RB["Mapped common buffers\nread-only, no heap copy"]+ KV["FP16 KV cache\n25 bounded SWA rings\n5 linear full-context stores"]+ EC["Expert cache\n16 LFU slots\nper opened layer"]+ WS["Reusable activation\nand kernel scratch"]+ end++ subgraph GPU["3. Per-layer Metal execution"]+ direction TB+ AT["Attention + router"]+ SE["Shared expert\nresident branch"]+ RE["Routed MoE\ncached or streamed top-8"]+ T["Combine branches\n+ layer tail"]+ HD["Tied 4-bit head\nafter layer 30"]++ AT --> SE+ AT --> RE+ SE --> T+ RE --> T+ T --> HD+ end++ MW -->|mmap| RB+ LF -->|pread on cache miss| EC+ Memory -->|feeds each layer| GPU++ classDef disk fill:#DBEAFE,stroke:#2563EB,color:#172554,stroke-width:1.5px;+ classDef memory fill:#DCFCE7,stroke:#16A34A,color:#052E16,stroke-width:1.5px;+ classDef compute fill:#FFEDD5,stroke:#EA580C,color:#431407,stroke-width:1.5px;+ classDef output fill:#F3E8FF,stroke:#9333EA,color:#3B0764,stroke-width:1.5px;+ class MF,MW,LF disk;+ class RB,KV,EC,WS memory;+ class AT,SE,RE,T compute;+ class HD output;++ style Disk fill:#EFF6FF,stroke:#93C5FD,color:#1E3A8A,stroke-width:2px+ style Memory fill:#F0FDF4,stroke:#86EFAC,color:#14532D,stroke-width:2px+ style GPU fill:#FFF7ED,stroke:#FDBA74,color:#7C2D12,stroke-width:2px+ linkStyle default stroke:#64748B,stroke-width:1.5px+```++## Prefill++The production profile processes a prompt in chunks of at most 128 tokens.+The runner remains layer-major: it advances a bounded group of rows through+each transformer layer without materializing prompt-wide expert activations.++For each chunk and layer, TurboFieldfare:++- runs projection GEMM/QMM paths where the row count can amortize setup;+- applies causal sliding-window or full attention and writes K/V rows;+- computes router outputs for all rows in the chunk;+- groups token/expert pairs into bounded routed-MoE work;+- streams at most eight experts per routed tile; one tile may remain queued+ while the next is fetched, so both slot sets fit within the 16-slot cache+ without reusing live slots; and+- combines the resident shared branch and routed branch before the layer tail.++The staged affine MPP path is used for eligible 4-bit prefill projections. It+unpacks source-affine tiles into bounded FP16 staging and passes them to Metal+Performance Primitives. Grouped routed MoE reuses argument and activation+scratch. The language-model head runs only for the final prompt row needed to+begin generation.++## Decode++Generation advances one token at a time. Each layer has a CPU and I/O handoff+between the measured `cb1` and `cb2` phases because the CPU must read the+router's top-8 result before it knows which expert files to read. Shared-expert+and cached routed-expert work may use additional command buffers so they can+overlap that handoff.++The resident router normalizes and scales the layer's post-attention hidden+state, then projects it to 128 expert scores:++```text+router_input = rmsnorm_no_scale(hidden)+scaled_input = router_input * router_scale / sqrt(hidden_size)+logits = int8_affine(scaled_input)+top8 = highest_8(logits)+weights = softmax(logits[top8]) * per_expert_scale[top8]+```++The GPU writes eight expert IDs and eight FP16 routing weights. The CPU must+read those IDs before it can plan cache hits, evictions, and file reads. This+data-dependent handoff separates resident GPU work from streamed weights.++The last-run diagnostics divide the layer loop into three timing buckets:++| Bucket | Work |+| --- | --- |+| `cb1` | Metal runs input norm, Q/K/V projections, RoPE and KV writes, attention, output projection, post-attention setup, and the router. It completes when the top-8 IDs are ready for CPU readback. |+| `io` | The CPU looks up the top-8 experts in the layer cache and fills only missing slots with `pread`. Metal starts the resident shared-expert branch after `cb1` so it overlaps these reads. Cached routed-expert work can also begin early. |+| `cb2` | Metal finishes the routed top-8 branch, reduces it with the router weights, combines it with the shared branch, and applies the post-FFN norms, residual, and layer scalar. |++These buckets overlap; they are not three serial pauses. Shared-expert GPU work+overlaps `io`, and the command-buffer pipeline can defer the `cb2` wait while+the next layer begins.++```mermaid+flowchart TD+ H["hidden state"] --> C1["CB1: norm, QKV, RoPE, KV write,\nattention, O projection, router"]+ C1 --> R["CPU reads top-8 expert IDs"]+ R --> P["LFU plan: hits, misses, slot ownership"]+ P --> IO["parallel bounded pread for misses"]+ C1 --> S["resident shared expert"]+ IO --> M["persistent routed MoE"]+ S --> T["layer tail: combine + residual"]+ M --> T+ T --> N{"layer 30?"}+ N -->|no| H+ N -->|yes| O["tied 4-bit head, softcap,\nargmax or sampling"]+ O --> K["next token"]++ classDef compute fill:#FFEDD5,stroke:#EA580C,color:#431407,stroke-width:1.5px;+ classDef control fill:#DBEAFE,stroke:#2563EB,color:#172554,stroke-width:1.5px;+ classDef io fill:#DCFCE7,stroke:#16A34A,color:#052E16,stroke-width:1.5px;+ classDef output fill:#F3E8FF,stroke:#9333EA,color:#3B0764,stroke-width:1.5px;+ class H,C1,S,M,T compute;+ class R,P control;+ class IO io;+ class N,O,K output;+ linkStyle default stroke:#64748B,stroke-width:1.5px+```++The shared expert depends on the post-attention hidden state but not on routed+weights, so its GPU work overlaps expert reads. The routed kernel consumes the+selected slot buffers after the reads finish. Queue order ensures the layer+tail sees both branches. After layer 30, the tied 4-bit head either emits a+greedy token through the fused rows path or produces logits for sampling.+For sampled generation, the production path applies full-distribution Top-P,+then Top-K, then temperature. The default Top-K `64` path uses a specialized+1,024-to-64 reduction; temperature `0` bypasses sampling and selects greedy+output.++## Metal execution++TurboFieldfare compiles its Metal source at runtime. The decode path uses+custom affine INT4 and INT8 GEMV kernels that consume the checkpoint's packed+values, BF16 scales, and BF16 biases directly. The MPP prefill path instead+dequantizes one bounded weight tile into FP16 threadgroup memory and passes FP16+tensors to `matmul2d`. The relevant Apple API sources are collected under+[Apple Metal](IMPLEMENTATION_REFERENCES.md#apple-metal). The routed MoE kernels+fuse affine decode, GeGLU, and the weighted expert reduction.++Packed-weight load width follows the proven alignment of each live path.+Resident INT4 GEMVs and routed gate/up projections assemble each 4-byte chunk+from two `ushort` loads because their offsets are only guaranteed to be+2-byte aligned. The current routed down-projection layout satisfies 4-byte+alignment and uses `uint` loads. A wider load is incorrect when the live address+does not satisfy its alignment.++The runtime uses targeted fusions around stable dataflow boundaries: QKV+projection and epilogue, post-attention setup, shared-expert phase 1, the layer+tail, and the tied head. It does not try to make the whole transformer layer+one monolithic kernel. MPP is used where prefill supplies enough rows to suit+matrix operations; single-token decode remains a custom GEMV workload.++## Code map++These entry points lead from the design above into the implementation. Each+item names the owning types or hot-path files; follow their references for+helpers and tests.++- **Model contract and runtime path.** [`ArchConfig`](../Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swift)+ defines the fixed Gemma 4 shape; [`RuntimeConfiguration`](../Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift)+ defines the production configuration.+- **Remote install and `.gturbo` layout.** Start with+ [`SupportedModelSource`](../Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift),+ [`RemoteStreamingRepacker`](../Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift),+ and [`RepackPlanner`](../Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift)+ for the pinned source, bounded range repack, and resident/per-layer file plan.+- **Integrity and model load.** [`ManifestReader`](../Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swift),+ [`VerifiedInstallReceipt`](../Sources/TurboFieldfare/Infrastructure/ModelIO/VerifiedInstallReceipt.swift),+ and [`Model.load`](../Sources/TurboFieldfare/Runtime/Inference/Model.swift) cover+ validation, resident mapping, and lazy layer verification.+- **Resident and streamed weights.** [`ResidentBuffer`](../Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swift),+ [`ModelExpertIO`](../Sources/TurboFieldfare/Runtime/Inference/ModelExpertIO.swift),+ and [`PreadExpertStreamer`](../Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift)+ own common weights, expert-cache planning, slots, and parallel bounded reads.+- **KV cache and attention.** [`KVCacheManager`](../Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift),+ [`Attention`](../Sources/TurboFieldfare/Kernels/Attention/Attention.swift), and+ [`TurboQuantKVLayout`](../Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swift)+ cover the mixed FP16 cache, SWA/full dispatch, and experimental packed layout.+- **Prompt and decode orchestration.** [`runRawCompletion`](../Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift)+ owns the outer generation loop; [`RealForwardRunner`](../Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift)+ owns the per-layer prefill and decode graph.+- **Prefill memory and scheduling.** [`PrefillChunkScratch`](../Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift),+ [`PrefillRoutedTileScheduler`](../Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillRoutedTileScheduler.swift),+ and [`MPPPrefillInt4QMM`](../Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swift)+ show bounded scratch, slot-safe expert tiles, and staged affine MPP projections.+- **Router and routed MoE.** [`MoE`](../Sources/TurboFieldfare/Kernels/MoE/MoE.swift)+ and [`moe.metal`](../Sources/TurboFieldfare/Metal/MoE/moe.metal) implement+ top-8 selection, cached-hit work, affine GeGLU, and weighted down reduction.+- **Metal library and fusions.** [`MetalContext`](../Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift),+ [`tensorops.metal`](../Sources/TurboFieldfare/Metal/TensorCore/tensorops.metal),+ and [`fused.metal`](../Sources/TurboFieldfare/Metal/Fusions/fused.metal) show+ runtime compilation, the MPP tensor-ops kernel, and production decode fusions.++## Correctness and safety invariants++- The importer preserves source affine values. Lossless repack and load-width+ changes require exact byte or output identity.+- K and V remain distinct after their separate normalization and positional+ paths, even where the raw projection is shared.+- Every queued GPU consumer owns its slot and scratch bank until completion.+ CPU reuse cannot race an earlier command buffer.+- Reordered floating-point kernels use deterministic within-arm checks plus+ reference-relative quality gates. Exact identity is not used as a universal+ quality metric.+- No normal install, load, test, or benchmark may place a whole model, shard,+ expert, or source tensor in Swift heap memory.+- Only one real-model process runs at a time on the 8 GB validation host.+- Slow profiling modes are diagnostic evidence, not production throughput+ evidence.++## Scope and limitations++The current runtime supports text-only, single-prompt generation with the+pinned Gemma 4 26B-A4B checkpoint. The validated context envelope is through+4K. Vision, audio, training, fine-tuning, server batching, and general model+support are outside the current scope.++TurboFieldfare is a research system. The Mac app exposes a small set of typed+runtime controls. The production path uses FP16 KV, a 16-slot LFU expert cache,+chunked prefill, MLX attention geometry v2, staged affine MPP prefill, and+batched routed MoE prefill, with RDADVISE off.++## Read next++- [Benchmarks](BENCHMARKS.md)+- [The experiments that shaped TurboFieldfare](OPTIMIZATION_JOURNEY.md)+- [Complete experiment inventory](experiments/EXPERIMENT_INVENTORY.md)+- [Implementation references](IMPLEMENTATION_REFERENCES.md)diff --git a/docs/assets/turbofieldfare-app.webp b/docs/assets/turbofieldfare-app.webpnew file mode 100644index 00000000..3b95f0abBinary files /dev/null and b/docs/assets/turbofieldfare-app.webp differdiff --git a/docs/assets/turbofieldfare-logo-rounded.png b/docs/assets/turbofieldfare-logo-rounded.pngnew file mode 100644index 00000000..51f91d42Binary files /dev/null and b/docs/assets/turbofieldfare-logo-rounded.png differdiff --git a/docs/benchmark-prompts/prefill-1024.txt b/docs/benchmark-prompts/prefill-1024.txtnew file mode 100644index 00000000..b932fc92--- /dev/null+++ b/docs/benchmark-prompts/prefill-1024.txt@@ -0,0 +1,19 @@+This prefill calibration prompt describes an engineering investigation into a single-prompt inference engine. The runtime should read the prompt in order, preserve causal context, append key and value rows, route experts deterministically, and compute logits only for the final prompt token. The passage is intentionally plain text so tokenizer counts can be reported by the benchmark before any model load. It asks for a concise answer about why chunked prefill reduces time to first token while keeping memory bounded.++The model is running on a small Apple Silicon system with an eight gigabyte physical memory ceiling. The implementation must never load a whole checkpoint, a whole shard, or a whole routed expert pool into Swift heap memory. Instead it should use memory mapped resident weights, tile bounded scratch buffers, explicit key value cache ranges, and streamed expert reads. The benchmark should make these constraints visible by printing prompt tokens, prefill wall time, skipped head count, final head time, GPU command buffer buckets, routed expert I/O, advisory read counters, resident set size, and physical footprint.++The prompt is also designed to exercise normal language patterns rather than a repeated single token. It includes nouns, verbs, punctuation, numbers, and technical phrases that resemble real requests. A correct response should explain that prefill is different from decode because many known prompt tokens can be processed as a bounded block, but each generated token still depends on the previous sampled token. It should mention that streaming experts remain necessary, batching is not required for this project, and the chunk size must be chosen by measurement rather than guesswork.++For the first implementation slice, the fast path should stay opt in. A fallback prefill mode may replay tokens with the existing scalar forward pass, but it should skip the expensive final head for every prompt token except the last one. That fallback is useful because it proves the public API, cancellation behavior, cursor advancement, progress reporting, fused greedy output mode, and sampling logits mode before the chunked kernels are ready. It is not the final performance target, and benchmark output must not pretend that fallback replay is chunked prefill.++For the second implementation slice, the key value cache needs explicit range views. A chunk writes several K and V rows before the global cursor advances, so the cache manager should expose temporary views with a caller supplied valid token count. The attention kernel then masks each query row independently: token zero sees only earlier context plus itself, token one sees one more row, and no query may read future rows in the same chunk. Sliding window layers clamp the first visible key by the window size, while full layers see the whole prefix.++For the next implementation slices, the projection kernels should move from repeated vector operations toward block shaped matrix work. The first custom kernel can be simple and correctness focused, but it must preserve the MLX affine four bit format with per group BF16 scale and BF16 bias. Router work should batch token rows, select top experts, and group token expert pairs by expert only after a route diversity benchmark shows the live expert tile size. The grouped expert path must not raise the default expert cache slot count.++A careful implementation must keep streaming semantics visible. The user interface may receive fewer progress events than before, because a chunk can complete several prompt tokens at once, but progress still has to be monotonic and must end at the prompt total. If a producer reports slice local progress, the caller must add the slice base before showing prompt global progress. If cancellation or an error happens after partial key value writes, the runner state is not reusable until reset clears the cache cursor and drops stale pages.++The attention path needs separate correctness and performance stages. The correctness stage can use a simple two pass softmax per output element. It should not allocate a score matrix, it should accept element strides, and it should test nonzero Metal buffer offsets. The performance stage can later tile keys, share row maxima across lanes, and reduce repeated dot products. The important invariant is that each query row has an absolute position equal to the chunk start plus the row index, and Gemma attention scale remains one point zero.++The full attention layers have a special key value detail. The raw key projection can be reused as the value projection input, but the cached K and V rows diverge before attention. K receives its per head norm and rotary position transform, while V receives its no scale norm and no rotary transform. A chunked path must preserve this quirk. A test should compare the chunked K and V rows against the scalar runner fixture before any real decode benchmark is allowed to promote the path.++The routed mixture of experts is the largest scheduling risk. A token has several selected routed experts and a dense shared expert path, so direct writes from every routed pair into the same output row would race. The deterministic first design writes unweighted routed outputs into a token rank partial buffer, then reduces token major with route weights. That costs bounded scratch but makes correctness easy to audit. Only after route diversity data is recorded should the implementation stream grouped expert tiles and tune the tile size.diff --git a/docs/experiments/EXPERIMENT_INVENTORY.md b/docs/experiments/EXPERIMENT_INVENTORY.mdnew file mode 100644index 00000000..0fff28d7--- /dev/null+++ b/docs/experiments/EXPERIMENT_INVENTORY.md@@ -0,0 +1,230 @@+# Experiment inventory++This is the curated experiment and decision index behind [Optimizing a 14.4 GB+model for an 8 GB machine](../OPTIMIZATION_JOURNEY.md). It records what shipped,+what worked only under a named condition, what failed, what a stronger gate+later reversed, and what the project never attempted.++Most readers should start with the article above. Use this inventory to find+the variants, controls, measurements, and final disposition of a specific+experiment. The entries are design archaeology, not an independent reproduction+package: they are curated from a larger private research record, while raw logs,+traces, internal plans, and project-state documents are intentionally excluded.++The companion [implementation reference ledger](../IMPLEMENTATION_REFERENCES.md)+records the external model implementations, papers, kernels, and systems that+materially shaped the work, including sources that informed rejected paths.++## How to read the inventory++Each experiment has a stable ID and a detailed summary. The summary states the+hypothesis, variants, measured evidence, later reversal when applicable, final+disposition, and reusable lesson.++| Disposition | Meaning |+| --- | --- |+| Production | Survives in the default runtime or frozen M2 reference profile. |+| Conditional | Helps only on a named host, workload, flag, or memory budget. |+| Rejected | Measured and not promoted. |+| Correctness repair | Required for valid output, independent of speed. |+| Reversed rejection | A better gate invalidated an early rejection; the later candidate shipped. |+| Scope decision | Deliberately not attempted. |+| Unexecuted hypothesis | Plausible idea without a completed runtime gate. |++## Terms used in the summaries++Common abbreviations: **cb1/cb2** are the first and second command-buffer+phases; **TG** is a threadgroup; **SIMDgroup** is Metal's lockstep execution+group; **GEMV** is matrix-vector multiplication; **QMM** is quantized matrix+multiplication; **MPP** is Apple's Metal Performance Primitives tensor path;+**GQA** is grouped-query attention; **SWA** is sliding-window attention;+**PSO** is a pipeline state object; **TTFT** is time to first token; **RSS** is+resident set size; and **NLL** is negative log-likelihood. See+[System design](../SYSTEM_DESIGN.md) for how these pieces fit together.++## Summary package++| Area | Summary | Entries |+| --- | --- | ---: |+| Model installation and expert I/O | [Remote repack, `pread`, hints, compression, and speculative I/O](summaries/01-model-install-and-expert-io.md) | 10 |+| Decode MoE, INT4, and router | [Persistent MoE, vectorization, router, and rejected geometries](summaries/02-decode-moe-int4-and-router.md) | 18 |+| Expert cache and layout | [Replacement policy, capacity, prediction, and disk layout](summaries/03-expert-cache-prediction-and-layout.md) | 9 |+| RDADVISE | [The complete short-win to long-context-rejection arc](summaries/04-rdadvise.md) | 7 |+| Attention and KV cache | [Split attention, MLX geometry, K4/V4, and FP16 ring](summaries/05-attention-and-kv-cache.md) | 14 |+| Prefill | [Chunking, MPP, routed MoE, overlap, and allocation experiments](summaries/06-prefill.md) | 16 |+| Fusions and orchestration | [Targeted fusions, head variants, queues, and synchronization](summaries/07-fusions-head-and-orchestration.md) | 15 |+| Sampling and output | [Gumbel sampling, tokenizer caching, and detokenization](summaries/08-sampling-tokenization-and-output.md) | 4 |+| Validation methodology | [False rejections, holdouts, thermal state, and benchmark artifacts](summaries/09-validation-and-measurement-lessons.md) | 9 |+| **Total** | | **102** |++## All 102 experiments++### Model installation and expert I/O++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [IO-01](summaries/01-model-install-and-expert-io.md#io-01) — `mmap` versus `pread` | Cold expert: 9.88 ms versus 2.79 ms; full simulation 0.50 versus 3.97 tok/s. | Production; parallel bounded `pread`. |+| [IO-02](summaries/01-model-install-and-expert-io.md#io-02) — Parallel reads and coalescing | About 1.13 to 2.08 to 2.13 tok/s through the two stages. | Production. |+| [IO-03](summaries/01-model-install-and-expert-io.md#io-03) — Darwin file hints | `F_RDAHEAD=0` and `F_NOCACHE` neutral; RDADVISE probe promising. | Rejected; RDADVISE gated separately. |+| [IO-04](summaries/01-model-install-and-expert-io.md#io-04) — Dedicated I/O executor | Best executor 8.59 ms versus existing 8.42 ms. | Rejected. |+| [IO-05](summaries/01-model-install-and-expert-io.md#io-05) — Custom I/O worker pool | Repeated four-worker pairs were mixed. | Rejected; normal parallel miss reads retained. |+| [IO-06](summaries/01-model-install-and-expert-io.md#io-06) — `mlock` | Recovered 0 ms; skipping streaming recovered 12-14 ms. | Rejected; contention, not eviction. |+| [IO-07](summaries/01-model-install-and-expert-io.md#io-07) — Expert compression | Zstandard about 10%; LZ4 0.06%. | Rejected. |+| [IO-08](summaries/01-model-install-and-expert-io.md#io-08) — Speculative reads | Probe reached 10.63 GB/s; decode fell 4.937 to 4.742 tok/s. | Rejected. |+| [IO-09](summaries/01-model-install-and-expert-io.md#io-09) — MTLIO | Warm 13.1-13.3 GB/s; only 5.4-7.5% of misses fully warm. | Rejected for runtime. |+| [IO-10](summaries/01-model-install-and-expert-io.md#io-10) — Remote streaming repack | 14,952,958,284 bytes, 229 ranges, 524,288-byte heap bounds. | Production. |++### Decode MoE, INT4, and router++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [DEC-01](summaries/02-decode-moe-int4-and-router.md#dec-01) — One SIMDgroup per row | Bundled row-SIMD and wider-MoE-TG stage: 2.131 to 2.188 tok/s. | Production; contribution not isolated. |+| [DEC-02](summaries/02-decode-moe-int4-and-router.md#dec-02) — Cooperative MoE row | cb2 about 230 to 527 ms. | Rejected. |+| [DEC-03](summaries/02-decode-moe-int4-and-router.md#dec-03) — Persistent multi-TG MoE | cb2 239 to 60 ms; 2.188 to 3.313 tok/s. | Production. |+| [DEC-04](summaries/02-decode-moe-int4-and-router.md#dec-04) — Initial 16-slot cache | I/O 166 to 88 ms; 3.313 to 4.261 tok/s. | Production; 16-slot capacity. |+| [DEC-05](summaries/02-decode-moe-int4-and-router.md#dec-05) — Shared-MLP/I/O overlap | cb2 62 to 48 ms; 4.404 to 4.736 tok/s. | Production. |+| [DEC-06](summaries/02-decode-moe-int4-and-router.md#dec-06) — MoE INT4 vectorization | Routed GPU 36.5 to 31.3 ms. | Production. |+| [DEC-07](summaries/02-decode-moe-int4-and-router.md#dec-07) — Standalone INT4 vectorization | Unsafe `uint` failed live offsets; corrected head 21.5 to 16 ms. | Production; corrected live-offset path. |+| [DEC-08](summaries/02-decode-moe-int4-and-router.md#dec-08) — Multi-TG router | cb1 about 50 to 44 ms. | Production. |+| [DEC-09](summaries/02-decode-moe-int4-and-router.md#dec-09) — Parallel top-k selector | 36.94 versus 18.86 microseconds. | Rejected. |+| [DEC-10](summaries/02-decode-moe-int4-and-router.md#dec-10) — Gate/up fusion | 5.378 versus 5.266 tok/s; eight rows won. | Production. |+| [DEC-11](summaries/02-decode-moe-int4-and-router.md#dec-11) — Phase 2 plus reduce | About 19 microseconds saved; intermediate removed. | Production. |+| [DEC-12](summaries/02-decode-moe-int4-and-router.md#dec-12) — Phase-1 paired rows | 207-212 versus 194-196 microseconds. | Rejected. |+| [DEC-13](summaries/02-decode-moe-int4-and-router.md#dec-13) — Phase-1 `u16` loads | 5.961 to 5.973 tok/s. | Production; small win. |+| [DEC-14](summaries/02-decode-moe-int4-and-router.md#dec-14) — Phase-2 d2/d2p/d4 | Mixed end to end; target only 5.70 ms/token. | Rejected; default unchanged. |+| [DEC-15](summaries/02-decode-moe-int4-and-router.md#dec-15) — Group-sum reuse | Private 454.05 to 420.53 microseconds reversed to 309.98 versus 348.83 in the wrapper. | Rejected. |+| [DEC-16](summaries/02-decode-moe-int4-and-router.md#dec-16) — Adaptive geometry | One synthetic state won; real rows mixed. | Rejected. |+| [DEC-17](summaries/02-decode-moe-int4-and-router.md#dec-17) — Progressive execution | Corrected 1K/256 fell 4.799 to 4.648 tok/s. | Rejected. |+| [DEC-18](summaries/02-decode-moe-int4-and-router.md#dec-18) — Hit-first split | 5.169 versus 4.518 tok/s with forced identical IDs. | Production. |++### Expert cache, prediction, and layout++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [CACHE-01](summaries/03-expert-cache-prediction-and-layout.md#cache-01) — LRU to LFU | I/O 72.6 to 64.8 ms; 5.476 to 5.631 tok/s. | Production. |+| [CACHE-02](summaries/03-expert-cache-prediction-and-layout.md#cache-02) — Windowed LFU | Slightly fewer misses; two real-decode prompts neutral or mixed. | Rejected. |+| [CACHE-03](summaries/03-expert-cache-prediction-and-layout.md#cache-03) — 24/32 slots | Higher replay hit rate for about +769 MiB/+1.54 GiB; live 32-slot run overloaded the host. | Conditional; additional memory. |+| [CACHE-04](summaries/03-expert-cache-prediction-and-layout.md#cache-04) — Heterogeneous allocation | Exact DP lost on holdout. | Rejected. |+| [CACHE-05](summaries/03-expert-cache-prediction-and-layout.md#cache-05) — Cross-layer predictor | Jaccard 0.039; copy hit 7%. | Rejected; pre-runtime evidence. |+| [CACHE-06](summaries/03-expert-cache-prediction-and-layout.md#cache-06) — Markov prefetch | Flat/negative; later row collapsed and was not correctness-safe. | Rejected. |+| [CACHE-07](summaries/03-expert-cache-prediction-and-layout.md#cache-07) — Offset read order | First win failed to repeat. | Rejected. |+| [CACHE-08](summaries/03-expert-cache-prediction-and-layout.md#cache-08) — Packed layout | Natural text +3.61%; near-4K decode -16.1% and prefill worse. | Rejected. |+| [CACHE-09](summaries/03-expert-cache-prediction-and-layout.md#cache-09) — APFS preallocation | Fragmentation observed; candidate not built. | Unexecuted hypothesis. |++### RDADVISE++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [RAD-01](summaries/04-rdadvise.md#rad-01) — Initial miss-only signal | Plausible first real-decode improvement. | Conditional; preliminary signal. |+| [RAD-02](summaries/04-rdadvise.md#rad-02) — Repeated short gate | 5.176 to 5.449 tok/s; I/O 87.4 to 72.2 ms. | Conditional; temporary promotion later removed. |+| [RAD-03](summaries/04-rdadvise.md#rad-03) — Advice cap | Fewer advice calls, more demand I/O. | Rejected. |+| [RAD-04](summaries/04-rdadvise.md#rad-04) — Advice in I/O path | 6.432 to 6.093 tok/s. | Rejected. |+| [RAD-05](summaries/04-rdadvise.md#rad-05) — Long-context policy | Unbounded 2.334; bounded 4.966 tok/s, but bounded lost at 512. | Rejected; static default policy. |+| [RAD-06](summaries/04-rdadvise.md#rad-06) — Adaptive policy | Some state wins, no stable rule. | Rejected; opt-in retained. |+| [RAD-07](summaries/04-rdadvise.md#rad-07) — Async overlap | 4.863 to 5.300 tok/s on 1K/256. | Conditional; production off. |++### Attention and KV cache++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [KV-01](summaries/05-attention-and-kv-cache.md#kv-01) — Split-KV attention | SWA about 3.3x; full 4K about 4.1x isolated. | Production. |+| [KV-02](summaries/05-attention-and-kv-cache.md#kv-02) — GQA-aware SWA | Isolated SWA win. | Production. |+| [KV-03](summaries/05-attention-and-kv-cache.md#kv-03) — Full-GQA A3 | +21.2% at 1024, -54.6% at 4096. | Rejected. |+| [KV-04](summaries/05-attention-and-kv-cache.md#kv-04) — A4 local variants | Three 1024 wins became neutral/slower at 4096; TG widths lost. | Rejected. |+| [KV-05](summaries/05-attention-and-kv-cache.md#kv-05) — MLX geometry v1 | 65-68% isolated win, then forced-prefix failure and removal. | Rejected; corrected v2 reopened the geometry family. |+| [KV-06](summaries/05-attention-and-kv-cache.md#kv-06) — MLX geometry v2 | 71-74% isolated; quality passed; +1.30-1.59% end to end. | Production. |+| [KV-07](summaries/05-attention-and-kv-cache.md#kv-07) — Packed K4/V4 attention | Split beat packed single-pass but stayed slower than FP16. | Conditional; experiment only. |+| [KV-08](summaries/05-attention-and-kv-cache.md#kv-08) — Alternative codecs | Faster writers, much slower attention. | Rejected. |+| [KV-09](summaries/05-attention-and-kv-cache.md#kv-09) — K4/V4 quality | Mean delta-NLL +0.015197; top-1 -5.0781 points. | Rejected; production default remains FP16. |+| [KV-10](summaries/05-attention-and-kv-cache.md#kv-10) — FP16 full-attention island | Small sample looked better; 256-row top-k gates failed. | Rejected. |+| [KV-11](summaries/05-attention-and-kv-cache.md#kv-11) — Packed chunk 32 | 5.42-6.30% isolated win; holdout quality failed. | Rejected. |+| [KV-12](summaries/05-attention-and-kv-cache.md#kv-12) — FP16 KV ring | About 575-591 MiB saved; speed neutral/mixed; parity retained. | Production. |+| [KV-13](summaries/05-attention-and-kv-cache.md#kv-13) — Ring kernel follow-up | Terminal 10.9% isolated median implied only about 0.34% whole-step opportunity. | Rejected; below action gate. |+| [KV-14](summaries/05-attention-and-kv-cache.md#kv-14) — Prefill attention race | Third barrier fixed one bank but cost 5.1-14.2%; two banks recovered 2.23-6.43%. | Correctness repair. |++### Prefill++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [PF-01](summaries/06-prefill.md#pf-01) — Mixed QMM/GEMV | QMM lost for Q, helped selected projection families. | Production; shape policy. |+| [PF-02](summaries/06-prefill.md#pf-02) — Chunk 128 | 121: 15.80 to 9.34 s; 1017: 92.89 to 52.35 s. | Production. |+| [PF-03](summaries/06-prefill.md#pf-03) — Deeper lookahead | 527: 26.61 to 33.38 s; 1017: 52.35 to 73.88 s. | Rejected. |+| [PF-04](summaries/06-prefill.md#pf-04) — Routed SIMD | 1409.666 to 4618.845 microseconds. | Rejected. |+| [PF-05](summaries/06-prefill.md#pf-05) — Shared INT8 QMM | Medium wins; 1017 regressed 45.59 to 52.01 s. | Rejected on M2. |+| [PF-06](summaries/06-prefill.md#pf-06) — Metadata reduction | Allocation counts cut by two-thirds. | Production; allocation hygiene. |+| [PF-07](summaries/06-prefill.md#pf-07) — Argument-buffer reuse v1 | Runtime/lifetime gate failed. | Rejected. |+| [PF-08](summaries/06-prefill.md#pf-08) — Argument-buffer rings | 21,217 allocations to two; long M2 about 9% slower. | Rejected. |+| [PF-09](summaries/06-prefill.md#pf-09) — Shared/fetch overlap M2 | Short/mid wins; long regression. | Rejected; M2. |+| [PF-10](summaries/06-prefill.md#pf-10) — Shared/fetch overlap M5 | Stable about 2.2-2.3% at 527/1017; M2 was order-sensitive and regressed long prefill. | Rejected and removed. |+| [PF-11](summaries/06-prefill.md#pf-11) — Trusted receipt | Avoided 6.741 s hashing in one row; changes trust/cache state. | Conditional; explicit trust policy. |+| [PF-12](summaries/06-prefill.md#pf-12) — Staged affine MPP | M128 about 73.8%; 512 prefill +11.421%; quality passed. | Reversed rejection; production. |+| [PF-13](summaries/06-prefill.md#pf-13) — Direct UInt4 | Beat retired path, lost to staged MPP by 20.40% at M128. | Rejected. |+| [PF-14](summaries/06-prefill.md#pf-14) — QMM TG reuse | Families +3.2-9.7%; current opportunity about 0.41%. | Rejected. |+| [PF-15](summaries/06-prefill.md#pf-15) — Batched routed MoE | Isolated +30.91%; balanced end to end about +2%. | Reversed rejection; production. |+| [PF-16](summaries/06-prefill.md#pf-16) — Long endpoint gate | Delta-NLL +0.002588; top-1 16/16; RSS 888.3 MiB. | Production; validation result. |++### Fusions, head, and orchestration++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [ORCH-01](summaries/07-fusions-head-and-orchestration.md#orch-01) — QKV epilogue | Joint epilogue-plus-tail rollback gained about +0.076 tok/s/-2.9 ms. | Production; contribution not isolated. |+| [ORCH-02](summaries/07-fusions-head-and-orchestration.md#orch-02) — Layer tail | Parity and paired dispatch win. | Production. |+| [ORCH-03](summaries/07-fusions-head-and-orchestration.md#orch-03) — Monolithic middle fusion | 1.811 versus 2.756 tok/s. | Rejected. |+| [ORCH-04](summaries/07-fusions-head-and-orchestration.md#orch-04) — Fused QKV GEMV | Initial rejection reversed; rollback measured 6.215 versus 6.110 tok/s. | Reversed rejection; production. |+| [ORCH-05](summaries/07-fusions-head-and-orchestration.md#orch-05) — Fusion D head family | Row head won short/long gates; tiled GPU improved while end to end fell 5.962 to 5.926. | Production; row head only. |+| [ORCH-06](summaries/07-fusions-head-and-orchestration.md#orch-06) — Shader sweep | Eleven families; first-run wins disappeared. | Rejected; sweep. |+| [ORCH-07](summaries/07-fusions-head-and-orchestration.md#orch-07) — RoPE tables | Neutral/slower. | Rejected. |+| [ORCH-08](summaries/07-fusions-head-and-orchestration.md#orch-08) — LM-head width/tiles | Small local movement, no whole-step win. | Rejected. |+| [ORCH-09](summaries/07-fusions-head-and-orchestration.md#orch-09) — Single-wait pipeline | Rollback 6.416 to 5.545 tok/s. | Production. |+| [ORCH-10](summaries/07-fusions-head-and-orchestration.md#orch-10) — Second Metal queue | Slower at about 5.059 tok/s. | Rejected. |+| [ORCH-11](summaries/07-fusions-head-and-orchestration.md#orch-11) — O3 token chain | Short favored candidate; long favored rollback. | Rejected. |+| [ORCH-12](summaries/07-fusions-head-and-orchestration.md#orch-12) — CB1 encode-ahead | Smoke +; 1K/256 4.613 versus 4.801. | Rejected. |+| [ORCH-13](summaries/07-fusions-head-and-orchestration.md#orch-13) — Decode arg-buffer reuse | 4.754 to 3.998 tok/s plus divergence. | Rejected. |+| [ORCH-14](summaries/07-fusions-head-and-orchestration.md#orch-14) — All-hit fast path | Only 2.761 ms total sync across 351 states. | Rejected. |+| [ORCH-15](summaries/07-fusions-head-and-orchestration.md#orch-15) — Merge shared/hit CB | Fewer submissions; 4.013 to 3.707 tok/s. | Rejected. |++### Sampling, tokenization, and output++| Experiment | Key evidence | Disposition |+| --- | --- | --- |+| [OUT-01](summaries/08-sampling-tokenization-and-output.md#out-01) — One-pass sampling and Top-64 | 0.377 to about 5.86-5.89 tok/s; later Top-64 route 0.733 ms/sample. | Production. |+| [OUT-02](summaries/08-sampling-tokenization-and-output.md#out-02) — Fused Gumbel head | 5.124 versus 5.192 tok/s standalone. | Conditional; default off. |+| [OUT-03](summaries/08-sampling-tokenization-and-output.md#out-03) — Tokenizer process cache | Suite body 29.002 to 4.425 s; command wall 36.54 to 6.67 s; RSS 3.86 GB to 397 MB. | Production; support path. |+| [OUT-04](summaries/08-sampling-tokenization-and-output.md#out-04) — Bounded detokenizer tail | ASCII and byte fallback neutral; mixed Unicode 17.51% faster. | Production; allocation hygiene. |++### Validation and measurement++| ID | Lesson | Consequence |+| --- | --- | --- |+| [METH-01](summaries/09-validation-and-measurement-lessons.md#meth-01) | Reordered floating-point work needs a distributional quality oracle. | Corrected false rejections of MLX attention, staged MPP, and batched MoE. |+| [METH-02](summaries/09-validation-and-measurement-lessons.md#meth-02) | Claimed-lossless work still needs exact identity. | Retained strict gates for cache, storage, and load-width changes. |+| [METH-03](summaries/09-validation-and-measurement-lessons.md#meth-03) | Test production-shaped offsets. | Found the live 2-byte INT4 alignment defect. |+| [METH-04](summaries/09-validation-and-measurement-lessons.md#meth-04) | Prove synchronization scope. | Repaired one reused scratch bank; audited other paths by ownership and queue order. |+| [METH-05](summaries/09-validation-and-measurement-lessons.md#meth-05) | Profiler tok/s is diagnostic. | Use GPU spans for attribution and clean rows for promotion. |+| [METH-06](summaries/09-validation-and-measurement-lessons.md#meth-06) | Interleave warm, thermally balanced rounds. | Removed false first-run shader wins. |+| [METH-07](summaries/09-validation-and-measurement-lessons.md#meth-07) | Mechanism counts are not outcomes. | Allocation and submission reductions still lost end to end. |+| [METH-08](summaries/09-validation-and-measurement-lessons.md#meth-08) | Trace-trained policies need holdouts. | Rejected packed layout and heterogeneous cache allocation. |+| [METH-09](summaries/09-validation-and-measurement-lessons.md#meth-09) | Detect greedy repetition loops. | Reclassified apparent cache decay as period-44 cyclic thrash. |++## Important non-experiments++These boundaries are not failed performance work:++- ANE/Core ML offload was excluded by architecture and platform scope.+- Weights below INT4 were cancelled by the quality floor.+- Draft-model speculative decoding did not reach a complete runtime candidate.+- Production routing was never cache-conditional.+- Fresh APFS preallocation remains unexecuted.+- The iPhone port is deferred; these are Mac measurements.++## How these summaries were prepared++Each public ID has a private claim map that names the dated source records used+to verify it. Later revalidation overrides stale intermediate conclusions. The+public package deliberately carries summaries instead of raw captures so a+reader can follow the evidence without receiving the private working archive.++[Optimization journey](../OPTIMIZATION_JOURNEY.md) |+[Benchmarks](../BENCHMARKS.md) |+[System design](../SYSTEM_DESIGN.md) |+[Implementation references](../IMPLEMENTATION_REFERENCES.md)diff --git a/docs/experiments/summaries/01-model-install-and-expert-io.md b/docs/experiments/summaries/01-model-install-and-expert-io.mdnew file mode 100644index 00000000..0c640e86--- /dev/null+++ b/docs/experiments/summaries/01-model-install-and-expert-io.md@@ -0,0 +1,192 @@+# Model installation and expert I/O++[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Decode, MoE, INT4, and router](02-decode-moe-int4-and-router.md)++The model's routed-expert pool is much larger than physical memory, so disk+access is part of every decode step. These experiments established the bounded+remote installer and the demand-read path used by the frozen M2 reference+runtime.+The entries retain their stable ID order, so the installer that creates the+runtime artifact appears last.++| Current result | Disposition |+| --- | --- |+| Remote range repack with 512 KiB peak payload and scratch heap | Production |+| Default bounded parallel miss-read path | Production |+| Whole-pool `mmap`, `mlock`, compression, speculative reads, and MTLIO | Rejected |++## Runtime expert I/O++<a id="io-01"></a>+### IO-01: `mmap` versus `pread`++- **Hypothesis:** Faulting mapped expert pages might avoid copies and beat+ explicit reads.+- **Variants tested:** Cold and warm `mmap`, sequential and+ parallel `pread`, and a full-token simulator.+- **Evidence:** A cold expert read+ took 9.88 ms with `mmap` and 2.79 ms with `pread`, about a 3.5x difference.+ Warm `mmap` won its local comparison, but the expert working set exceeds usable+ cache on the target machine. The simulator reached 3.97 tok/s with parallel `pread` and+ 0.50 tok/s with `mmap`.+- **What changed the conclusion:** Warm-file results+ ceased to matter once the gate modeled continual cold misses.+- **Final disposition:** Production uses bounded parallel `pread`.+- **Lesson:** Benchmark+ the cache state the application can sustain, not the cache state a microbench+ can manufacture.++<a id="io-02"></a>+### IO-02: Parallel reads and command-buffer coalescing++- **Hypothesis:** Concurrent expert reads and fewer GPU submissions would reduce+ the two largest early stalls.+- **Variants tested:** The serial stage-0 path,+ parallel `pread`, and parallel `pread` plus command-buffer coalescing.+- **Evidence:** Decode moved from about 1.13 to 2.08 tok/s with parallel reads and+ to about 2.13 tok/s after coalescing.+- **What changed the conclusion:** Nothing;+ later stages kept the structure.+- **Final disposition:** Production.+- **Lesson:**+ Fix the largest wall-time bucket before tuning arithmetic inside a smaller one.++<a id="io-03"></a>+### IO-03: Darwin file hints++- **Hypothesis:** Darwin-specific caching and read-ahead controls could improve+ miss service without changing the data path.+- **Variants tested:** `F_RDAHEAD=0`, `F_NOCACHE`, and Darwin+ [`F_RDADVISE`](04-rdadvise.md), which advises the kernel about upcoming file+ ranges.+- **Evidence:** The first two were neutral.+ Untimed ahead advice reached 3.61-3.78 GB/s and justified a real-decode+ candidate.+- **What changed the conclusion:** Because advice ran outside the+ timed body, the probe justified only a separate real-decode program.+- **Final disposition:** The simple hints are rejected; RDADVISE is evaluated separately.+- **Lesson:** A+ promising system-call probe earns an end-to-end test, not immediate promotion.++<a id="io-04"></a>+### IO-04: Dedicated expert-I/O executor++- **Hypothesis:** A controlled executor and split-read schedule would outperform+ the existing concurrent reads.+- **Variants tested:** Worker and submission+ counts around the production path.+- **Evidence:** The best executor result was+ 8.59 ms; the existing path measured 8.42 ms. Real decode was unchanged at four+ and eight workers.+- **What changed the conclusion:** The candidate failed its+ first production comparison.+- **Final disposition:** Rejected.+- **Lesson:** A new+ scheduler must beat the existing concurrency, not merely expose more controls.++<a id="io-05"></a>+### IO-05: Custom I/O worker pool++- **Hypothesis:** A fixed custom worker pool could beat bounded parallel miss+ reads.+- **Variants tested:** The default path and a four-worker override in+ repeated 256-token decode.+- **Evidence:** The pairs were mixed: 5.964 to 6.132+ tok/s, then 6.093 to 6.022; profile I/O stayed at 71.3 ms/token.+- **What changed the conclusion:** The repeated pair reversed the first result.+- **Final disposition:** The custom worker override was rejected; production retains+ parallel reads over the current miss set.+- **Lesson:** A concurrency wrapper+ must beat the existing parallel work distribution across repeated rows.++<a id="io-06"></a>+### IO-06: `mlock` and resident-model pages++- **Hypothesis:** Expert streaming evicted the 1.58 GB resident model, so pinning+ it should restore GPU time.+- **Variants tested:** Locked resident buffers and a+ diagnostic run that skipped streaming.+- **Evidence:** `mlock` recovered+ essentially 0 ms. Skipping expert streaming recovered about 12-14 ms.+- **What changed the conclusion:** The mechanism was memory-system contention,+ not resident-page eviction.+- **Final disposition:** Rejected.+- **Lesson:** Prove+ the mechanism before choosing a remedy with a large memory-policy cost.++<a id="io-07"></a>+### IO-07: Expert compression++- **Hypothesis:** Compressing expert blobs could reduce bytes read enough to pay+ for decompression.+- **Variants tested:** Zstandard and LZ4 over representative+ packed experts.+- **Evidence:** Zstandard saved about 10%; LZ4 saved 0.06%.+- **What changed the conclusion:** Neither ratio supported the required CPU work+ and format complexity.+- **Final disposition:** Rejected.+- **Lesson:** Already+ quantized weights may contain too little redundancy for transparent runtime+ compression.++<a id="io-08"></a>+### IO-08: Speculative expert reads++- **Hypothesis:** Reading or advising likely future experts could convert misses+ into warm page-cache hits.+- **Variants tested:** Entry probes followed by a+ paired real decode with speculative reads enabled.+- **Evidence:** Probes showed post-advice residency and up to 10.63 GB/s. In+ the first end-to-end pair, decode fell from 4.937 to 4.742 tok/s, total+ prefill wall time rose from 82.50 to 123.64 s, and emitted IDs diverged. The+ pair therefore failed both its speed and token-parity gates.+- **What changed the conclusion:** The probe measured page residency,+ not lead time, contention, or pipeline behavior.+- **Final disposition:**+ Rejected.+- **Lesson:** A mechanism probe cannot substitute for the first clean+ end-to-end pair. Cache prediction and replacement are covered in the+ [cache summary](03-expert-cache-prediction-and-layout.md).++<a id="io-09"></a>+### IO-09: MTLIO++- **Hypothesis:** A GPU-oriented I/O queue could remove CPU staging for routed+ experts.+- **Variants tested:** Warm MTLIO reads and production miss-state+ classification.+- **Evidence:** Warm reads reached 13.1-13.3 GB/s, but only+ 5.4-7.5% of observed misses were fully warm.+- **What changed the conclusion:**+ The fast state was too rare to control token time.+- **Final disposition:**+ Rejected for the runtime.+- **Lesson:** Optimize the state distribution the+ application occupies, not the fastest state an API exposes.++## Model installation++<a id="io-10"></a>+### IO-10: Remote streaming repack++- **Hypothesis:** The installer could convert the source model directly from+ remote byte ranges without storing or loading the complete source checkpoint.+- **Variants tested:** A pinned remote revision, range planning, bounded payload+ copying, interruption guards, and final manifest verification.+- **Evidence:** A+ validated run downloaded 14,952,958,284 bytes in 229 ranges. Its largest+ transfer was 64 MiB; peak payload and scratch heap were each 524,288 bytes.+ The freshly installed output loaded in 0.97 s. A greedy eight-token smoke+ for `The capital of France is` generated at 5.015 tok/s; this validated the+ install/load path, not answer quality.+- **What changed the conclusion:** Nothing; later installs kept the same+ core path.+- **Final disposition:** Production.+- **Lesson:** Model installation+ must obey the same bounded-memory architecture as inference.++[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Decode, MoE, INT4, and router](02-decode-moe-int4-and-router.md)diff --git a/docs/experiments/summaries/02-decode-moe-int4-and-router.md b/docs/experiments/summaries/02-decode-moe-int4-and-router.mdnew file mode 100644index 00000000..195f4ac4--- /dev/null+++ b/docs/experiments/summaries/02-decode-moe-int4-and-router.md@@ -0,0 +1,305 @@+# Decode MoE, INT4, and router experiments++[Previous: Model installation and expert I/O](01-model-install-and-expert-io.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Expert cache, prediction, and layout](03-expert-cache-prediction-and-layout.md)++Decode performance improved most when the runtime exposed independent rows,+overlapped dense work with expert reads, and shortened the affine INT4+instruction chain. Several cooperative or adaptive variants lost because they+reduced parallelism or optimized the wrong cache state.++| Current result | Disposition |+| --- | --- |+| Persistent multi-TG routed MoE with hit-first execution | Production |+| Four-group INT4 paths and safe `ushort` packed loads | Production |+| Multi-TG router GEMV with scalar final selector | Production |+| Cooperative, paired-row, adaptive, and progressive variants | Rejected |++## Dispatch, cache, and overlap++<a id="dec-01"></a>+### DEC-01: One SIMDgroup per output row++- **Hypothesis:** Assigning one SIMDgroup to each output row would expose enough+ parallel work for decode GEMV.+- **Variants tested:** The baseline scalar layout+ and row-parallel INT4/INT8 kernels with a wider MoE threadgroup.+- **Evidence:**+ The bundled stage rose from 2.131 to 2.188 tok/s. The source attributes the+ roughly 9 ms cb2 movement to the wider MoE threadgroup, so it does not isolate+ the standalone GEMV contribution.+- **What changed the conclusion:** Later+ kernels retained row-cooperative SIMD GEMV.+- **Final disposition:** Production+ structure; the original speed row is bundled attribution.+- **Lesson:** Record a+ multi-change stage as a bundle unless a later gate isolates each contribution.++<a id="dec-02"></a>+### DEC-02: SIMD-cooperative MoE inner GEMV++- **Hypothesis:** Several lanes cooperating on each selected expert row would+ accelerate affine decode.+- **Variants tested:** Cooperative per-expert work+ against independent row streams.+- **Evidence:** The candidate was about 2x+ slower; cb2 grew from roughly 230 to 527 ms after 256 row streams collapsed to+ eight.+- **What changed the conclusion:** The dispatch exposed the lost+ parallelism directly.+- **Final disposition:** Rejected.+- **Lesson:** Cooperation+ can cost more than it saves when it serializes independent rows.++<a id="dec-03"></a>+### DEC-03: Persistent multi-threadgroup MoE++- **Hypothesis:** Persistent row workers could remove serialized expert+ execution.+- **Variants tested:** The prior dispatch and a multi-threadgroup+ persistent kernel.+- **Evidence:** cb2 fell from about 239 to 60 ms; decode rose+ from 2.188 to 3.313 tok/s.+- **What changed the conclusion:** Nothing.+- **Final disposition:** Production.+- **Lesson:** Dispatch structure produced a larger+ gain than the later instruction-level refinements.++<a id="dec-04"></a>+### DEC-04: Initial 16-slot expert cache++- **Hypothesis:** Reusing recently routed experts from existing buffers would+ avoid demand reads.+- **Variants tested:** No cache and a 16-slot per-layer LRU.+- **Evidence:** I/O fell from about 166 to 88 ms; decode rose from 3.313 to 4.261+ tok/s.+- **What changed the conclusion:** The cache stayed, while the replacement+ policy later changed to LFU.+- **Final disposition:** Production capacity;+ superseded policy.+- **Lesson:** Small bounded expert reuse captures meaningful+ locality without resident-model growth. The later policy and capacity work+ appears in the [expert-cache summary](03-expert-cache-prediction-and-layout.md).++<a id="dec-05"></a>+### DEC-05: Shared-MLP and I/O overlap++- **Hypothesis:** The dense shared MLP depends on cb1 output but not on routed+ expert bytes, so it can run while misses are read.+- **Variants tested:** Serial+ shared/routed work and a shared command buffer committed before asynchronous+ fetch.+- **Evidence:** cb2 wall time fell from 62 to 48 ms; decode rose from+ 4.404 to 4.736 tok/s.+- **What changed the conclusion:** Nothing.+- **Final disposition:** Production.+- **Lesson:** A dependency graph can reveal safe work+ that leaves the I/O critical path.++## INT4 and router kernels++<a id="dec-06"></a>+### DEC-06: MoE INT4 vectorization++- **Hypothesis:** Four-group blocking, `half4` activation reads, and wider packed+ loads would shorten the affine INT4 dependency chain.+- **Variants tested:** The+ scalar group loop and a four-group blocked inner GEMV.+- **Evidence:** Routed GPU+ time fell from 36.5 to 31.3 ms; cb2 fell from 48 to 42 ms; the bench reached+ 4.957 tok/s.+- **What changed the conclusion:** Later analysis showed that+ blocking and instruction-level parallelism mattered more than load width.+- **Final disposition:** Production.+- **Lesson:** “Vectorization” here means a+ shorter, more independent instruction stream, not merely a larger integer+ load.++<a id="dec-07"></a>+### DEC-07: Standalone INT4 vectorization++- **Hypothesis:** The MoE four-group technique should also accelerate Q/K/V/O+ and the tied LM-head GEMV.+- **Variants tested:** Byte loads, 32-bit `uint` loads,+ and alignment-safe 16-bit `ushort` loads with `half4` activations and+ four-group blocking.+- **Evidence:** Offset-zero tests passed for `uint`, but live+ resident tensors placed packed weights at 2-byte-aligned offsets and produced+ garbage. The corrected `ushort` path cut LM-head GPU time from about 21.5 to+ 16 ms and moved the 16-slot bench from about 4.76 to 5.07-5.38 tok/s.+- **What changed the conclusion:** Real-model offsets disproved the initial+ alignment assumption. Load-width-only movement was small; blocking and ILP+ created most of the gain.+- **Final disposition:** Corrected path in production.+- **Lesson:** Test the real offset contract, not only an aligned buffer base.++<a id="dec-08"></a>+### DEC-08: Multi-threadgroup router GEMV++- **Hypothesis:** The 128-expert router GEMV should run across threadgroups while+ the small global top-k remains separate.+- **Variants tested:** One threadgroup+ for GEMV plus selection, and a multi-TG GEMV followed by a one-TG selector.+- **Evidence:** cb1 fell from about 50 to 44 ms with identical token IDs.+- **What changed the conclusion:** Nothing.+- **Final disposition:** Production.+- **Lesson:** Parallelize the large independent projection and keep the small+ global reduction simple.++<a id="dec-09"></a>+### DEC-09: Parallel K=8 selector++- **Hypothesis:** Parallelizing top-k selection would complement the router GEMV+ split.+- **Variants tested:** Parallel and scalar final selectors.+- **Evidence:**+ The parallel selector took 36.94 microseconds; the scalar selector took 18.86.+- **What changed the conclusion:** Coordination dominated the tiny reduction.+- **Final disposition:** Rejected.+- **Lesson:** The optimal geometry can change+ abruptly at a stage boundary.++<a id="dec-10"></a>+### DEC-10: Gate/up fusion++- **Hypothesis:** Gate and up projections can share activation loads and+ per-group activation sums.+- **Variants tested:** Separate projections, fused projection, and 4, 8,+ and 16 rows per threadgroup.+- **Evidence:** Paired decode measured 5.266 tok/s for the separate control and+ 5.378 tok/s for the fused candidate; eight rows per threadgroup beat four+ and sixteen.+- **What changed the conclusion:** Nothing.+- **Final disposition:** Production at the measured+ geometry.+- **Lesson:** Shared-input fusion still needs a geometry sweep.++<a id="dec-11"></a>+### DEC-11: Phase 2 plus reduction fusion++- **Hypothesis:** Fusing down projection with expert reduction would eliminate+ partial-output traffic.+- **Variants tested:** Separate phase 2 and reduction+ against one fused kernel.+- **Evidence:** The isolated path saved about 19+ microseconds and removed the `yPartial` round trip.+- **What changed the conclusion:** Nothing.+- **Final disposition:** Production.+- **Lesson:** A small+ kernel gain becomes more useful when it also removes a dispatch and buffer.++## Rejected geometry refinements++<a id="dec-12"></a>+### DEC-12: Phase-1 paired-row variants++- **Hypothesis:** Each lane could compute two output rows and amortize affine+ work.+- **Variants tested:** `f2`, widened-load `f2`, and miss-subset forms.+- **Evidence:** Some isolated rows looked promising, but production-shaped pairs+ took about 207-212 microseconds versus 194-196 for the control. Miss-subset+ forms also lost in the common four-to-seven-hit state.+- **What changed the conclusion:** Production hit/miss geometry reversed the small synthetic signal.+- **Final disposition:** Rejected.+- **Lesson:** Weight geometry by the runtime's+ state distribution.++<a id="dec-13"></a>+### DEC-13: Phase-1 `u16` packed loads++- **Hypothesis:** Safe 16-bit packed loads could reduce load count without+ changing row geometry.+- **Variants tested:** Byte and `ushort` loads.+- **Evidence:** Median decode moved from 5.961 to 5.973 tok/s; routed GPU time+ fell from about 30.65 to 30.30 ms.+- **What changed the conclusion:** Nothing,+ but the gain remained small.+- **Final disposition:** Production.+- **Lesson:**+ This load-width refinement is distinct from the larger four-group INT4 win.++<a id="dec-14"></a>+### DEC-14: Phase-2 d2, d2p, and d4++- **Hypothesis:** Computing two or four down rows together could preserve vector+ work and share setup.+- **Variants tested:** d2, paired d2, and d4.+- **Evidence:** d2 showed a tiny isolated win, and d2p improved some buckets.+ Repeated end-to-end rows remained mixed. A fresh profile placed phase 2 at+ 5.70 ms/token, while the previously measured 0.6-1.1 ms/token improvement+ implied only 0.3-0.6% of the diagnostic step, below run-to-run variation.+- **What changed the conclusion:** Current whole-step share made the attainable+ gain small.+- **Final disposition:** Rejected as default.+- **Lesson:** Reprofile a+ candidate after earlier optimizations shrink its target.++<a id="dec-15"></a>+### DEC-15: Affine group-sum reuse++- **Hypothesis:** Reusing activation sums across affine groups would remove+ repeated work.+- **Variants tested:** Phase-1 x-sum and phase-2 activation-sum+ forms.+- **Evidence:** A development microbenchmark improved from 454.05 to 420.53+ microseconds. In the production wrapper, the default took 309.98 microseconds+ and x-sum took 348.83.+- **What changed the conclusion:** The production wrapper+ reversed the helper result; this gate did not isolate why.+- **Final disposition:**+ Rejected.+- **Lesson:** Measure the optimized helper inside its actual wrapper.++<a id="dec-16"></a>+### DEC-16: Adaptive MoE geometry++- **Hypothesis:** Cache-hit count could select the fastest geometry for each+ token.+- **Variants tested:** Profiled choices across hit states.+- **Evidence:** Qualitative screening found one candidate favored in a six-hit+ synthetic state, while short and long real-decode rows remained mixed.+- **What changed the conclusion:** One state-specific winner did not+ form a reliable policy.+- **Final disposition:** Rejected.+- **Lesson:** Adaptive+ dispatch needs a stable decision surface, not an isolated winning point.++<a id="dec-17"></a>+### DEC-17: Progressive expert execution++- **Hypothesis:** Launching ready experts in chunks would overlap their GPU work+ with later reads.+- **Variants tested:** Chunk sizes one, two, and four plus a+ corrected event-order implementation.+- **Evidence:** After the event-order fix, the 1K/256 candidate diverged from+ the control and regressed from 4.799 to 4.648 tok/s. Earlier chunk-two+ evidence came from a short row; longer rows were nearly flat.+- **What changed the conclusion:** Early+ evidence depended on an unsafe or unrepresentative schedule.+- **Final disposition:** Rejected and runtime-disabled.+- **Lesson:** Validate synchronization+ before trusting speed from overlapping work.++## Hit-first execution++<a id="dec-18"></a>+### DEC-18: Hit-first phase-1 split++- **Hypothesis:** Cached experts can execute while missing experts arrive, with a+ second phase for misses only.+- **Variants tested:** The default hit-first split+ and a rollback with identical forced token IDs.+- **Evidence:** The rollback+ produced 4.518 tok/s; hit-first produced 5.169, a 14.4% advantage.+- **What changed the conclusion:** Nothing; the forced-ID gate removed route divergence+ as a confounder.+- **Final disposition:** Production.+- **Lesson:** Coarse hit/miss+ overlap succeeded where progressive multi-chunk scheduling failed.++[Previous: Model installation and expert I/O](01-model-install-and-expert-io.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Expert cache, prediction, and layout](03-expert-cache-prediction-and-layout.md)diff --git a/docs/experiments/summaries/03-expert-cache-prediction-and-layout.md b/docs/experiments/summaries/03-expert-cache-prediction-and-layout.mdnew file mode 100644index 00000000..73094330--- /dev/null+++ b/docs/experiments/summaries/03-expert-cache-prediction-and-layout.md@@ -0,0 +1,163 @@+# Expert cache, prediction, and layout experiments++[Previous: Decode, MoE, INT4, and router](02-decode-moe-int4-and-router.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: RDADVISE](04-rdadvise.md)++The production runtime keeps 16 expert slots per layer and uses LFU+replacement. More memory improves hit rate, but trace-trained allocation,+prediction, and disk-layout policies failed representative holdouts. The+[resource split](../../SYSTEM_DESIGN.md#resource-split) explains the slot+capacity and memory cost.++| Current result | Disposition |+| --- | --- |+| Uniform 16-slot LFU | Production |+| 24/32 slots | Conditional +memory experiments |+| Predictor, Markov, read sorting, and single-trace layout | Rejected |+| Fresh preallocated expert artifact | Unexecuted hypothesis |++## Cache policy and capacity++<a id="cache-01"></a>+### CACHE-01: LRU to LFU++- **Hypothesis:** Frequency would retain recurring experts better than recency+ under a fixed 16-slot budget.+- **Variants tested:** LRU and LFU on canonical and+ long decode rows.+- **Evidence:** Canonical decode rose from 5.476 to 5.631 tok/s+ and I/O fell from 72.6 to 64.8 ms. Long-run I/O fell from 110.5 to 97.9 ms.+- **What changed the conclusion:** Nothing.+- **Final disposition:** Production.+- **Lesson:** Replacement policy captured more reuse without spending memory.++<a id="cache-02"></a>+### CACHE-02: Windowed LFU++- **Hypothesis:** Aging frequency counts would adapt faster when routing changed.+- **Variants tested:** Monotonic LFU and a 64-token window.+- **Evidence:** The+ window reduced misses slightly, but two real-decode prompts were neutral or+ mixed. Belady's offline-optimal policy, which knows all future requests,+ remained about 8.4 percentage points above LFU on the France prompt and 10.8+ percentage points above it on the corrected two-prompt corpus.+- **What changed the conclusion:** Better miss counts did not reduce the measured+ step.+- **Final disposition:** Rejected.+- **Lesson:** Cache-policy simulation needs+ an end-to-end I/O gate.++<a id="cache-03"></a>+### CACHE-03: 24 and 32 expert slots++- **Hypothesis:** More resident experts would buy enough I/O reduction to justify+ the memory.+- **Variants tested:** 16, 24, and 32 slots per layer.+- **Evidence:**+ Relative to the 16-slot control, trace replay gave 24 slots another 12.6-14.9+ hit-rate points for 769 MiB and 32 slots another 20.9-23.7 points for 1.54+ GiB. A live 32-slot row fell to 1.578 tok/s as I/O reached 318.3 ms/token and+ pipeline wait reached 238.3 ms/token on the 8 GB Mac.+- **What changed the conclusion:** The hit-rate win remained real,+ but it violated the memory objective for the default.+- **Final disposition:**+ Conditional +memory experiment; production stays at 16.+- **Lesson:** Report+ memory-funded speed separately from memory-free optimization.++<a id="cache-04"></a>+### CACHE-04: Fixed-total heterogeneous allocation++- **Hypothesis:** Layers should receive different slot counts under the same+ 480-slot total.+- **Variants tested:** Uniform `16 x 30` allocation and an exact dynamic+ program that distributed the same 480 total slots across layers to minimize+ misses on related training traces.+- **Evidence:** The optimized allocation lost on the+ held-out near-4K trace.+- **What changed the conclusion:** Holdout routing did not+ match the training traces.+- **Final disposition:** Rejected.+- **Lesson:** A+ trace-trained cache layout needs representative holdouts before runtime work.++## Prediction and disk layout++<a id="cache-05"></a>+### CACHE-05: Cross-layer expert predictor++- **Hypothesis:** One layer's expert choices could predict the next layer's+ misses.+- **Variants tested:** Cross-layer set overlap and direct copied-expert+ prediction.+- **Evidence:** Mean Jaccard was 0.039; copied predictions hit only+ 7%.+- **What changed the conclusion:** The offline signal failed the threshold+ for a runtime candidate.+- **Final disposition:** Rejected before implementation.+- **Lesson:** Measure predictability before adding speculative I/O.++<a id="cache-06"></a>+### CACHE-06: Markov warming and prefetch++- **Hypothesis:** Recent expert transitions could predict future demand.+- **Variants tested:** Early Markov warming and later demand-adjacent prefetch.+- **Evidence:** The first version was flat or negative. Later rows collapsed from+ values such as 5.413 to 2.256 tok/s and changed output.+- **What changed the conclusion:** Background reads contended with foreground NVMe and memory+ traffic; the later implementation also reused the foreground slot pool and was+ not correctness-safe.+- **Final disposition:** Rejected.+- **Lesson:** Prefetch accuracy alone+ cannot justify traffic that delays the demand path.++<a id="cache-07"></a>+### CACHE-07: File-offset read ordering++- **Hypothesis:** Sorting misses by file offset would improve storage locality.+- **Variants tested:** Route order and physical-offset order.+- **Evidence:** The+ first row improved from 6.012 to 6.117 tok/s. Repeats reversed the result:+ 6.099 to 6.067 tok/s, with I/O rising from 75.0 to 76.7 ms.+- **What changed the conclusion:** The first win did not repeat.+- **Final disposition:**+ Rejected.+- **Lesson:** Interleave repeated I/O-policy comparisons.++<a id="cache-08"></a>+### CACHE-08: Packed expert layout++- **Hypothesis:** Reordering experts from a natural-text trace and combining+ adjacent reads would reduce calls and seek distance.+- **Variants tested:** The+ identity layout and one trace-specialized layout with grouped reads.+- **Evidence:** Natural-text replay improved 3.61% with about 49.7 MB extra RSS,+ using the unit recorded by the source artifact.+ The near-4K gate reversed it: decode fell from 4.111 to 3.449 tok/s and prefill+ rose from 168.85 to 312.48 seconds total.+- **What changed the conclusion:** The+ training-like trace did not generalize.+- **Final disposition:** Rejected.+- **Lesson:** On-disk order is a workload policy and needs multi-workload gates.++<a id="cache-09"></a>+### CACHE-09: APFS extent preallocation++- **Hypothesis:** A freshly preallocated expert artifact might reduce file+ fragmentation.+- **Variants tested:** Existing-file extent inspection only.+- **Evidence:** The files were fragmented, but no clean preallocated artifact+ received an end-to-end gate.+- **What changed the conclusion:** No runtime+ conclusion was reached.+- **Final disposition:** Unexecuted hypothesis.+- **Lesson:**+ A plausible filesystem mechanism is neither a win nor a rejection until the+ artifact is built and measured.++[Previous: Decode, MoE, INT4, and router](02-decode-moe-int4-and-router.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: RDADVISE](04-rdadvise.md)diff --git a/docs/experiments/summaries/04-rdadvise.md b/docs/experiments/summaries/04-rdadvise.mdnew file mode 100644index 00000000..a669a036--- /dev/null+++ b/docs/experiments/summaries/04-rdadvise.md@@ -0,0 +1,135 @@+# RDADVISE experiments++[Previous: Expert cache, prediction, and layout](03-expert-cache-prediction-and-layout.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Attention and KV cache](05-attention-and-kv-cache.md)++Darwin's `F_RDADVISE` tells the kernel which file ranges an application expects+to read. It produced a repeatable short-run win and was briefly a default+candidate. Longer and differently scheduled runs exposed severe stalls and no+single policy that stayed safe across contexts. Production keeps it off.++| Current result | Disposition |+| --- | --- |+| Static miss-only advice | Rejected as a default |+| Capped policy | Rejected |+| Adaptive and asynchronous policies | Rejected as defaults; opt-in retained |+| Production profile | RDADVISE off |++## Discovery and repeat++<a id="rad-01"></a>+### RAD-01: Initial miss-only real-decode signal++- **Hypothesis:** Advising the kernel about upcoming miss ranges would start+ page-cache work before demand reads.+- **Variants tested:** Real decode with+ miss-only advice off and on.+- **Evidence:** The first row showed a plausible I/O+ and token-rate improvement.+- **What changed the conclusion:** One row could not+ establish a default.+- **Final disposition:** Promising conditional result.+- **Lesson:** System advice needs repeats and context sweeps.++<a id="rad-02"></a>+### RAD-02: Repeated short-run default gate++- **Hypothesis:** The initial result would survive paired same-session repeats.+- **Variants tested:** Default miss-only advice against no advice.+- **Evidence:**+ Median decode rose from 5.176 to 5.449 tok/s, about 5.3%; I/O fell from 87.4 to+ 72.2 ms.+- **What changed the conclusion:** Later long-context tests found unsafe+ stalls.+- **Final disposition:** Temporarily promoted, later removed.+- **Lesson:**+ The early win was real for its state, but its state was too narrow.++## Policy variants++<a id="rad-03"></a>+### RAD-03: Advice-call cap++- **Hypothesis:** Limiting advice calls would preserve prefetch value while+ reducing overhead.+- **Variants tested:** Unbounded and capped miss-only advice.+- **Evidence:** The cap reduced advisory work but increased demand-read I/O.+- **What changed the conclusion:** Call count was not the controlling metric.+- **Final disposition:** Rejected.+- **Lesson:** Fewer system calls can still+ produce worse page-cache timing.++<a id="rad-04"></a>+### RAD-04: Advice inside the I/O path++- **Hypothesis:** Moving advice into the planned fetch path might remove serial+ decode-thread advice time without losing its I/O benefit.+- **Variants tested:**+ Plan-time advice and I/O-path advice.+- **Evidence:** Decode fell from 6.432 to 6.093 tok/s; I/O rose from 71.3 to+ 84.8 ms.+- **What changed the conclusion:** Placement increased interference+ with the demand path.+- **Final disposition:** Rejected.+- **Lesson:** Advice timing+ is part of the I/O schedule, not a free hint.++<a id="rad-05"></a>+### RAD-05: Long-context policy gate++- **Hypothesis:** The short-run default would remain safe as context and miss+ state changed.+- **Variants tested:** Unbounded advice, bounded advice, and no+ advice across context lengths.+- **Evidence:** At 1,024 context tokens, unbounded advice+ fell to 2.334 tok/s and spent 86.39 ms in advice calls; bounded advice reached+ 4.966 tok/s. The bounded policy then regressed the 512-token context.+- **What changed the conclusion:** No static cap covered both states.+- **Final disposition:** The bounded static cap was rejected for default promotion at+ this gate; later runtime policy moved production to RDADVISE off.+- **Lesson:** A policy must+ survive the context transition where its mechanism changes.++<a id="rad-06"></a>+### RAD-06: Adaptive policy++- **Hypothesis:** Miss count, byte count, slow-call thresholds, and cooldown could+ select advice only in favorable states.+- **Variants tested:** Several adaptive threshold combinations across repeated+ 1,536-token gates, followed by a fresh policy that capped the total advised+ ranges at 512 MiB.+- **Evidence:** One 1,536-token row improved from+ 4.634 to 4.756 tok/s, but the 512 MiB candidate later fell from 4.823 to 3.397.+- **What changed the conclusion:** State-specific wins failed to generalize.+- **Final disposition:**+ Rejected for default promotion; adaptive remains opt-in.+- **Lesson:** Adaptation adds value only when the observed signals+ predict the safe state reliably.++## Final conditional result++<a id="rad-07"></a>+### RAD-07: Asynchronous advice overlap++- **Hypothesis:** Moving advice off the demand critical path could keep its page+ warming while hiding call latency.+- **Variants tested:** Synchronous RDADVISE+ and asynchronous-overlap RDADVISE on a 1K/256 decode.+- **Evidence:** The candidate improved+ from 4.863 to 5.300 tok/s. Its first rejection also relied on an exact-ID oracle+ later judged inappropriate near known ties.+- **What changed the conclusion:** The later+ [quality-gate audit](09-validation-and-measurement-lessons.md#meth-01)+ corrected the exact-ID reasoning. The project still found no stable+ selection rule, then froze new M2 performance work without reopening this+ candidate.+- **Final disposition:** Conditional positive result; production remains off.+- **Lesson:** The accurate conclusion is “no stable production policy,” not+ “every RDADVISE variant was slow.”++[Previous: Expert cache, prediction, and layout](03-expert-cache-prediction-and-layout.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Attention and KV cache](05-attention-and-kv-cache.md)diff --git a/docs/experiments/summaries/05-attention-and-kv-cache.md b/docs/experiments/summaries/05-attention-and-kv-cache.mdnew file mode 100644index 00000000..14cdc874--- /dev/null+++ b/docs/experiments/summaries/05-attention-and-kv-cache.md@@ -0,0 +1,261 @@+# Attention and KV-cache experiments++[Previous: RDADVISE](04-rdadvise.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Prefill](06-prefill.md)++The current runtime uses split-KV attention, MLX-derived full-attention+geometry, and an exact FP16 KV ring. Packed K4/V4 remains an explicit+experiment because its quality loss outweighed its roughly 82 MiB saving+relative to the final FP16 ring.++| Current result | Disposition |+| --- | --- |+| Split-KV plus GQA-aware SWA | Production |+| MLX full-attention geometry v2 | Production after reversed rejection |+| FP16 KV ring | Production |+| Packed K4/V4 and alternate codecs | Experimental or rejected |++## Decode attention geometry++<a id="kv-01"></a>+### KV-01: Split-KV attention++- **Hypothesis:** Partitioning the sequence and combining partial online-softmax+ states would expose decode parallelism.+- **Variants tested:** Single-pass and+ split-KV attention across SWA, full attention, and long context.+- **Evidence:**+ SWA improved from about 995 to 289-302 microseconds; full attention from 1473+ to 360-382; full 4K from 6103 to 1471, about 4.1x. Long-context cb1 GPU time+ fell about 28%, while short-context end-to-end speed stayed nearly flat.+- **What changed the conclusion:** Whole-step share explained the short-row+ neutrality.+- **Final disposition:** Production.+- **Lesson:** A large kernel win+ matters only where that kernel occupies enough of the step.++<a id="kv-02"></a>+### KV-02: GQA-aware sliding-window attention++- **Hypothesis:** Query heads that share KV heads should share decode work.+- **Variants tested:** Generic and GQA-aware SWA kernels.+- **Evidence:** The generic split-partial control took 295.04 microseconds; the+ GQA-aware candidate took 273.69 microseconds and passed the runtime gate.+ Full attention required a different geometry.+- **What changed the conclusion:**+ Nothing.+- **Final disposition:** Production for SWA.+- **Lesson:** Architectural+ reuse helps only when the kernel maps the sharing relationship directly.++<a id="kv-03"></a>+### KV-03: Full-attention GQA staging++- **Hypothesis:** The SWA GQA strategy would transfer to full attention.+- **Variants tested:** Default full attention and the A3 full-GQA candidate at+ 1024 and 4096.+- **Evidence:** In isolated kernel rows, the candidate was 21.2% faster at 1024 and 54.6%+ slower at 4096.+- **What changed the conclusion:** Long-context scaling reversed+ the short-row win.+- **Final disposition:** Rejected.+- **Lesson:** Attention+ geometry needs at least one long-sequence gate.++<a id="kv-04"></a>+### KV-04: Local full-attention variants++- **Hypothesis:** Broadcast softmax, `exp2`, K16 combine, or another threadgroup+ width would trim the full-attention floor.+- **Variants tested:** Each change at+ 1024 and 4096, including 64, 128, and 256 threads.+- **Evidence:** In isolated+ rows, broadcast softmax, `exp2`, and K16 improved 1024 by 0.9%, 1.5%, and 3.1%,+ respectively, but were neutral or slower at 4096. TG64, TG128, and TG256+ regressed at both lengths.+- **What changed the conclusion:** The sweep showed a+ geometry problem rather than one expensive instruction.+- **Final disposition:**+ Rejected.+- **Lesson:** Stop local tweaking when all nearby variants preserve the+ same bound.++<a id="kv-05"></a>+### KV-05: MLX geometry v1++- **Hypothesis:** MLX's vectorized full-attention layout would solve the geometry+ problem.+- **Variants tested:** The current split kernel and the first MLX-style+ mapping.+- **Evidence:** Isolated time improved 65-68%; early end-to-end rows+ improved 2.8-3.7%. A forced-prefix exact-output gate then failed and the+ candidate was removed.+- **What changed the conclusion:** A corrected v2 later+ passed a distributional quality gate and exposed shared control nondeterminism,+ so the project reopened the geometry family rather than treating v1's stop as+ final.+- **Final disposition:** V1 remained removed; v2 reversed the geometry-family+ rejection.+- **Lesson:** Select the quality oracle from the candidate's mathematical+ contract without retroactively declaring an old candidate safe. See+ [METH-01](09-validation-and-measurement-lessons.md#meth-01).++<a id="kv-06"></a>+### KV-06: MLX geometry v2++- **Hypothesis:** A corrected MLX-style mapping could retain the speed signal and+ pass an appropriate quality gate.+- **Variants tested:** Exact reference repair,+ isolated geometry, a 9,216-row quality corpus, and balanced M2 end-to-end+ rows.+- **Evidence:** Isolated speed improved 71-74%; the quality gate passed;+ balanced decode improved 1.30-1.59%.+- **What changed the conclusion:** The+ distributional gate replaced the invalid exact-output rejection.+- **Final disposition:** Production; reversed rejection.+- **Lesson:** Revalidate a strong speed signal when the rejection instrument+ was wrong. See [METH-01](09-validation-and-measurement-lessons.md#meth-01).++## Packed KV and quality++<a id="kv-07"></a>+### KV-07: Packed K4/V4 attention++- **Hypothesis:** Keeping K and V in packed 4-bit form would save memory and+ reduce bandwidth enough to pay for decode.+- **Variants tested:** Single-pass and+ split packed attention, Q pretransform, function constants, K staging, and+ full-GQA forms.+- **Evidence:** Split packed attention beat packed single-pass by+ about 2.4x but remained slower than FP16. Q pretransform and function constants+ helped; K staging and full-GQA regressed.+- **What changed the conclusion:**+ Optimization could not erase packed access and dequantization cost.+- **Final disposition:** Explicit experiment, not production.+- **Lesson:** Improve a+ candidate against the production control, not only against its first version.++<a id="kv-08"></a>+### KV-08: Alternative K/V codecs++- **Hypothesis:** `vllm4nc` or `affine4g32` could improve the packed-cache+ balance.+- **Variants tested:** Current K4/V4 stores one scale per head role;+ `vllm4nc` uses norm metadata for K and affine scale/zero metadata for V;+ `affine4g32` stores scale/zero metadata per group of 32. Each ran in isolated+ writer and packed-attention rows, with FP16 as a separate production control.+- **Evidence:** The+ alternate codecs improved some writer rows but made packed attention much slower.+- **What changed the conclusion:** Writer speed was not the controlling end-to-end cost.+- **Final disposition:** Rejected.+- **Lesson:** Evaluate a storage format across+ write, read, attention, quality, and memory together.++<a id="kv-09"></a>+### KV-09: K4/V4 quality characterization++- **Hypothesis:** The packed cache's memory saving would fit the quality budget.+- **Variants tested:** Packed K4/V4 against FP16 over the full quality corpus.+- **Evidence:** Mean delta-NLL was +0.015197, p95 +0.287202, top-1 agreement+ dropped 5.0781 percentage points, and top-8 dropped 5.5990 points. Every split+ failed. Against the final FP16 ring, packed storage saves only about 82 MiB.+- **What changed the conclusion:** The full corpus and ring-relative memory+ comparison replaced earlier short and obsolete-linear comparisons.+- **Final disposition:** Rejected as production; experiment remains available.+- **Lesson:** Approximation must clear quality against the best exact memory+ layout.++<a id="kv-10"></a>+### KV-10: FP16 full-attention island++- **Hypothesis:** Keeping five full-attention layers exact while packing SWA+ layers could recover most quality.+- **Variants tested:** All-packed and an FP16+ full-attention island.+- **Evidence:** A 16-row sample looked better. At 256 rows,+ mean delta-NLL improved relative to all-packed, but top-1 still fell 1.5625+ points and top-8 fell 0.5371. Advancement required mean delta-NLL to improve+ by at least 0.002 nat/token and both agreement metrics to improve by at least+ 1.0 percentage point.+- **What changed the conclusion:** The larger gate+ reversed the small sample.+- **Final disposition:** Rejected and removed.+- **Lesson:** Small quality samples are useful for screening, not promotion.++<a id="kv-11"></a>+### KV-11: Packed-attention chunk 32++- **Hypothesis:** More final SWA chunks would improve packed-attention occupancy.+- **Variants tested:** 16 and 32 final chunks with isolated, short-decode,+ and independent quality rows.+- **Evidence:** Isolated speed improved 5.42-6.30%;+ an earlier short decode rose from 6.511 to 7.110 tok/s. Holdout delta-NLL was+ +0.005853 and top-1 agreement fell 0.846 points, both outside the gate.+- **What changed the conclusion:** The independent quality holdout rejected the+ speed winner.+- **Final disposition:** Rejected and removed.+- **Lesson:** Keep the+ quality holdout independent from candidate selection.++## Exact FP16 ring++<a id="kv-12"></a>+### KV-12: FP16 KV ring++- **Hypothesis:** Sliding-window layers need only a ring, not the retired linear+ 4K allocation.+- **Variants tested:** Linear and ring FP16 storage with split-KV+ attention.+- **Evidence:** Against the retired linear FP16 allocation, the ring saved about+ 575-591 MiB. Near-4K decode was neutral to slightly faster, 4.357 to 4.417+ tok/s; 1K was slightly slower.+ Token parity held after a PSO-selection asymmetry was fixed.+- **What changed the conclusion:** Correctness repair established an exact storage optimization.+- **Final disposition:** Production.+- **Lesson:** Reclaim exact lifetime waste+ before spending quality on compression.++<a id="kv-13"></a>+### KV-13: Ring-specific kernel follow-up++- **Hypothesis:** The promoted ring kernel still had meaningful local headroom.+- **Variants tested:** The retired linear control and current ring-1152 kernel,+ used to decide whether a new modulo-hoist or segment-split candidate was+ justified.+- **Evidence:** The initial ring row improved 4.5% over the linear control,+ implying about 0.14% whole-step opportunity. A terminal alternating median+ favored ring by 10.9%, but weighted opportunity remained about 0.34%, below+ the 0.5% action gate.+- **What changed the conclusion:** Earlier work had reduced the target's share.+- **Final disposition:**+ Stopped without promotion.+- **Lesson:** Recompute whole-step value after every+ major stack change.++## Prefill attention correctness++<a id="kv-14"></a>+### KV-14: Prefill tiled-attention race++- **Hypothesis:** Production-shaped validation could expose synchronization+ defects hidden by toy tests.+- **Variants tested:** The original shared scratch+ plus a corrected single-bank path with a third barrier, then a two-bank layout.+- **Evidence:** The unsafe bank lacked a reader-to-next-writer edge. A third+ barrier made it correct but slowed production shapes 5.1-14.2%. Two alternating+ banks retained byte-identical output and recovered 2.23-6.43% versus corrected+ single-bank.+- **What changed the conclusion:** The layout removed the cost of an+ otherwise necessary barrier.+- **Final disposition:** Two-bank correctness repair+ in production.+- **Lesson:** Every reused threadgroup-memory cycle needs an explicit+ reader-to-next-writer edge. The surrounding compute path is covered in the+ [prefill summary](06-prefill.md).++[Previous: RDADVISE](04-rdadvise.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Prefill](06-prefill.md)diff --git a/docs/experiments/summaries/06-prefill.md b/docs/experiments/summaries/06-prefill.mdnew file mode 100644index 00000000..f22f593d--- /dev/null+++ b/docs/experiments/summaries/06-prefill.md@@ -0,0 +1,272 @@+# Prefill experiments++[Previous: Attention and KV cache](05-attention-and-kv-cache.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Fusions, head, and orchestration](07-fusions-head-and-orchestration.md)++Production prefill uses 128-token chunks, projection-specific GEMV/QMM+selection, bounded staged affine MPP for INT4 projections, and batched routed+MoE. Several candidates improved one shape, allocation count, or host but+failed the M2 long-row gate.++| Current result | Disposition |+| --- | --- |+| Chunk 128, staged affine MPP, and batched routed MoE | Production |+| Shared/fetch overlap v3 | Rejected and removed |+| Shared INT8 QMM, deeper lookahead, and argument-buffer rings | Rejected on M2 |++## Shape and scheduling++<a id="pf-01"></a>+### PF-01: Mixed QMM and GEMV dispatch++- **Hypothesis:** Matrix kernels help only where token count and projection shape+ amortize setup.+- **Variants tested:** QMM and repeated GEMV by projection at `T = 32`.+- **Evidence:** QMM was slower for full Q and neutral for SWA Q; KV/O and+ other projection families benefited.+- **What changed the conclusion:** The+ shape matrix replaced a single global rule.+- **Final disposition:** Production+ policy.+- **Lesson:** Select prefill kernels by projection and shape.++<a id="pf-02"></a>+### PF-02: Chunk size 128++- **Hypothesis:** Larger chunks would amortize per-chunk work without breaking+ the 8 GB budget.+- **Variants tested:** 32 and 128 tokens per chunk on M2.+- **Evidence:** Prefill fell from 15.80 to 9.34 s at 121 tokens, 49.80 to 26.61 s+ at 527, and 92.89 to 52.35 s at 1017.+- **What changed the conclusion:** Nothing;+ memory and correctness gates passed.+- **Final disposition:** Production.+- **Lesson:** A configuration sweep can unlock more than a new kernel.++<a id="pf-03"></a>+### PF-03: Deeper tile lookahead++- **Hypothesis:** Two pending tiles and four experts per tile would hide more+ expert reads.+- **Variants tested:** Production depth one/eight experts and depth+ two/four experts.+- **Evidence:** The candidate regressed 527-token prefill from+ 26.61 to 33.38 s and 1017 from 52.35 to 73.88 s because tile dispatches+ doubled.+- **What changed the conclusion:** Scheduling cost exceeded hidden I/O.+- **Final disposition:** Rejected.+- **Lesson:** More lookahead is useful only when+ it does not multiply dispatch work.++<a id="pf-04"></a>+### PF-04: SIMD-cooperative routed MoE++- **Hypothesis:** SIMD cooperation would accelerate grouped routed prefill.+- **Variants tested:** Row/expert-parallel and SIMD-cooperative kernels.+- **Evidence:** Kernel time regressed from 1.410 to 4.619 ms.+- **What changed the conclusion:** Cooperation removed useful row and expert+ parallelism.+- **Final disposition:** Rejected and removed.+- **Lesson:** The decode+ parallelism lesson also applies to prefill's grouped expert work.++<a id="pf-05"></a>+### PF-05: Shared-expert INT8 QMM v2++- **Hypothesis:** The dense shared expert should use QMM once token count exceeds+ the `M = 1` regime.+- **Variants tested:** Legacy GEMV, full QMM v2, and a phase-1+ hybrid.+- **Evidence:** QMM was faster for `M >= 16` and slower at `M = 1`. Medium rows+ improved modestly, but the final 1017-token M2 row regressed from 45.59 to+ 52.01 s. The hybrid beat legacy but not full v2.+- **What changed the conclusion:**+ Long-row M2 behavior broke the shape-local promotion case.+- **Final disposition:** Rejected as production.+- **Lesson:** A mixed-length policy needs+ representative short, medium, and long gates.++## Allocation and overlap++<a id="pf-06"></a>+### PF-06: Routed metadata reduction++- **Hypothesis:** One sorted-pair buffer could replace three routed metadata+ buffers.+- **Variants tested:** Three-buffer and one-buffer grouping.+- **Evidence:** Allocations fell from 90 to 30 in the small case and 360 to 120+ in the larger case.+- **What changed the conclusion:** No throughput claim was+ needed; the change improved bounded allocation and clarity.+- **Final disposition:** Production; bounded-allocation cleanup.+- **Lesson:** Record allocation improvements+ without inventing a speed result.++<a id="pf-07"></a>+### PF-07: Argument-buffer reuse v1++- **Hypothesis:** Reusing bindings across streamed tiles would reduce encoder+ work.+- **Variants tested:** Per-tile allocation and a first reuse design.+- **Evidence:** The candidate failed its runtime gate and raised lifetime+ concerns.+- **What changed the conclusion:** Allocation reduction did not improve+ the production schedule.+- **Final disposition:** Rejected and removed.+- **Lesson:** GPU resource reuse requires both lifetime proof and wall-time value.++<a id="pf-08"></a>+### PF-08: Argument-buffer ring v2 and v3++- **Hypothesis:** A small ring could eliminate most argument-buffer allocations.+- **Variants tested:** Per-dispatch allocation and two ring designs on M2 and M5.+- **Evidence:** Allocations fell from 21,217 to two, but M2 1,017-token prefill+ and TTFT regressed about 9%. On M5, v3 improved prefill and TTFT by only+ 0.2-0.3%, below the 2% action gate, and one 527-token repeat reversed+ direction slightly.+- **What changed the conclusion:** Allocation count moved dramatically while wall time did not.+- **Final disposition:** Rejected and removed.+- **Lesson:** Mechanism counters are+ diagnostics, not acceptance metrics.++<a id="pf-09"></a>+### PF-09: Shared/fetch overlap on M2++- **Hypothesis:** Decode's shared-MLP/I/O overlap would transfer to chunked+ prefill.+- **Variants tested:** Serial and overlapping shared expert/fetch paths.+- **Evidence:** The candidate improved 121 and 527 tokens by about 1% and 5.3%,+ then materially regressed 1017 tokens.+- **What changed the conclusion:** The+ long M2 row reversed the short and medium gains.+- **Final disposition:**+ Rejected on production M2.+- **Lesson:** A successful decode schedule may not+ transfer to long prefill.++<a id="pf-10"></a>+### PF-10: Shared/fetch overlap v3 on M5++- **Hypothesis:** M5 scheduling and tensor paths might change the overlap+ trade-off.+- **Variants tested:** Balanced, thermally controlled control/candidate rows+ at 527 and 1017 tokens.+- **Evidence:** The candidate improved about 2.2-2.3% at+ both lengths.+- **What changed the conclusion:** The balanced M2 revalidation was+ order-sensitive and materially regressed long prefill. The user judged the+ 2.2-2.3% M5 gain too small to justify a separate scheduler branch.+- **Final disposition:** Rejected and removed.+- **Lesson:** A small host-specific win may cost more complexity than it+ returns.++## Installation and startup policy++<a id="pf-11"></a>+### PF-11: Trusted installation receipt++- **Hypothesis:** A trusted receipt could skip model SHA verification and reduce+ time to first token.+- **Variants tested:** Full hash and receipt-trusted load.+- **Evidence:** The receipt avoided 6.741 s of hashing in one 527-token+ attribution row. Clean medians improved 37.95% at 121 tokens and 11.52% at+ 527, but regressed 38.65% at 1,017 because full hashing had warmed expert-file+ pages.+- **What changed the conclusion:** The switch changed+ integrity semantics and cache state.+- **Final disposition:** Conditional integrity policy, not a production+ kernel-speed claim.+- **Lesson:** Separate trust policy from+ compute performance.++## Production compute paths and gates++<a id="pf-12"></a>+### PF-12: Staged affine MPP INT4++- **Hypothesis:** Expand only a 32x64 affine INT4 tile into 4 KiB threadgroup+ memory, then use MPP matmul without a full expanded buffer.+- **Variants tested:**+ Packed QMM and bounded staged MPP across projection shapes and quality+ endpoints.+- **Evidence:** Weighted M128 work improved about 73.8%; stable+ 512-token prefill improved 11.421% and TTFT 10.947%. A 36-endpoint quality gate+ passed.+- **What changed the conclusion:** An initial 0.09375 logit delta had+ caused a false rejection; distributional quality showed acceptable or improved+ behavior.+- **Final disposition:** Production; reversed rejection.+- **Lesson:**+ Bounded dequantization can unlock matrix hardware without violating the model+ memory rule. See [METH-01](09-validation-and-measurement-lessons.md#meth-01).++<a id="pf-13"></a>+### PF-13: Direct shader-local UInt4++- **Hypothesis:** A direct packed UInt4 path could avoid staged half tiles.+- **Variants tested:** Retired packed QMM, direct UInt4, and current staged MPP.+- **Evidence:** At M128, direct UInt4 beat the retired path by 68.46% but lost to+ staged MPP by 20.40%; at M32 it lost to staged MPP by 38.61%.+- **What changed the conclusion:** The current winner, not the retired baseline, set the gate.+- **Final disposition:** Rejected.+- **Lesson:** Compare new work with today's best+ path.++<a id="pf-14"></a>+### PF-14: QMM threadgroup reuse++- **Hypothesis:** Reusing activation tiles across output rows would accelerate+ the remaining packed QMM families.+- **Variants tested:** Current and reuse+ kernels by projection.+- **Evidence:** Individual families improved 3.2-9.7%+ with exact output, but fresh attribution left only about 0.41% whole-prefill+ opportunity.+- **What changed the conclusion:** Earlier promotions had shrunk the+ target.+- **Final disposition:** Rejected after re-attribution.+- **Lesson:** Local+ speedup times current share determines value.++<a id="pf-15"></a>+### PF-15: Batched routed MoE++- **Hypothesis:** Grouping same-expert token rows would amortize affine setup+ within the existing bounded scratch budget.+- **Variants tested:** Pair and+ batched routes with 495,616 bytes of scratch, isolated kernels, balanced M2+ rows, and quality endpoints.+- **Evidence:** Isolated time fell from 4943.704 to+ 3415.312 microseconds, a 30.91% gain. Balanced 121/527 prefill improved about+ 2.0-2.2%; quality matched the reference gate.+- **What changed the conclusion:**+ The first removal used invalid exact cross-process output comparison. A later+ same-process/distributional gate reversed it.+- **Final disposition:** Production;+ reversed rejection.+- **Lesson:** Batching can improve streamed MoE without+ expanding model-scale scratch. See+ [METH-01](09-validation-and-measurement-lessons.md#meth-01).++<a id="pf-16"></a>+### PF-16: Long prefill endpoint gate++- **Hypothesis:** Chunked production prefill would retain quality and bounded RSS+ beyond the short fixtures.+- **Variants tested:** Sixteen endpoints through 3707+ tokens against the scalar reference.+- **Evidence:** Aggregate delta-NLL was+ +0.002588; top-1 matched 16/16. Chunked RSS was 888.3 MiB versus 1517.9 MiB for+ scalar, with no model-scale heap staging.+- **What changed the conclusion:** A single sensitive 1,024-token endpoint+ outlier did not persist at neighboring lengths.+- **Final disposition:** Production validation.+- **Lesson:** Long endpoint sweeps+ separate a local tie from a systematic quality change.++[Previous: Attention and KV cache](05-attention-and-kv-cache.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Fusions, head, and orchestration](07-fusions-head-and-orchestration.md)diff --git a/docs/experiments/summaries/07-fusions-head-and-orchestration.md b/docs/experiments/summaries/07-fusions-head-and-orchestration.mdnew file mode 100644index 00000000..290946fb--- /dev/null+++ b/docs/experiments/summaries/07-fusions-head-and-orchestration.md@@ -0,0 +1,250 @@+# Fusions, head, and orchestration experiments++[Previous: Prefill](06-prefill.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Sampling, tokenization, and output](08-sampling-tokenization-and-output.md)++Targeted fusions and dependency-aware I/O overlap survived. Larger wrapper+fusions, extra queues, cross-token event chains, and resource reuse often lost+end-to-end even when they removed dispatches or allocations.++| Current result | Disposition |+| --- | --- |+| QKV epilogue, layer tail, QKV GEMV, and single-wait pipeline | Production |+| Row Fusion D greedy head | Production |+| Monolithic, chunk, tiled, wide, and late-wait head variants | Rejected |+| Extra queue, encode-ahead, merge, and reuse candidates | Rejected |++## Targeted fusions++<a id="orch-01"></a>+### ORCH-01: QKV epilogue fusion++- **Hypothesis:** Per-head norm, RoPE, and KV write could share one projection+ epilogue.+- **Variants tested:** Separate operations and the fused epilogue.+- **Evidence:** The first full run was noisy. A later joint rollback showed the+ enabled QKV-epilogue/layer-tail stack ahead by about 0.076 tok/s and lower by+ 2.9 ms/token. That row supports the stack but does not isolate the+ epilogue's share.+- **What changed the conclusion:** Better paired measurement recovered a+ small stack-level signal.+- **Final disposition:** Production; exact attribution+ remains bundled.+- **Lesson:** Do not assign a joint rollback's gain to one+ member of the bundle.++<a id="orch-02"></a>+### ORCH-02: Layer-tail fusion++- **Hypothesis:** Residual, scale, and the following norm could share one kernel.+- **Variants tested:** Separate tail operations and the fused tail.+- **Evidence:** Parity held. In the historical paired attribution row, the+ fused path measured 2.693 tok/s and 371.3 ms/token, versus 2.056 tok/s and+ 486.3 ms/token for the legacy chain. The absolute row predates the current+ stack and is not a current baseline.+- **What changed the conclusion:** Nothing.+- **Final disposition:** Production.+- **Lesson:** Small+ targeted fusions work when their data lifetime and dependency boundary align.++<a id="orch-03"></a>+### ORCH-03: Monolithic post-attention/pre-FFN fusion++- **Hypothesis:** Combining most of the block middle would remove more launches+ and intermediates.+- **Variants tested:** A broad monolithic wrapper and the+ legacy path.+- **Evidence:** The candidate produced 1.811 tok/s versus 2.756 for+ the control. Later, narrower post-attention and shared phase-1 fusions+ succeeded.+- **What changed the conclusion:** The failure identified a bad+ fusion boundary, not a universal fusion no-go.+- **Final disposition:** Rejected.+- **Lesson:** Fuse operations with shared data and compatible geometry, not every+ adjacent operation.++<a id="orch-04"></a>+### ORCH-04: Fused QKV GEMV++- **Hypothesis:** Q, K, and V projections could share activation reads.+- **Variants tested:** Separate and fused projection dispatch.+- **Evidence:** A repeated 256-token rollback gate measured the fused path at+ 6.215 tok/s and the unfused control at 6.110 tok/s.+- **What changed the conclusion:** The initial short real-decode gate regressed+ despite a synthetic win; later repeated rows and a post-promotion rollback+ favored fusion.+- **Final disposition:** Production; reversed rejection.+- **Lesson:** A modest fusion belongs in the default only after a repeated+ whole-step gate.++<a id="orch-05"></a>+### ORCH-05: LM-head Fusion D family++- **Hypothesis:** Final norm, INT4 head, softcap, and selection could collapse+ into a faster chain.+- **Variants tested:** Chunk, row, tiled, wide, and late-wait+ designs.+- **Evidence:** The chunk version improved a local stage but lost about+ 0.9% end-to-end. The row design later improved the repeated short median by+ 1.0% and the long pair by 2.8%, removed CPU argmax, and became the default+ greedy head. Tiling cut head GPU time from 14.2 to 13.1 ms while decode fell+ from 5.962 to 5.926 tok/s; late wait was worse.+- **What changed the conclusion:**+ The row redesign passed whole-step gates that the other variants failed.+- **Final disposition:** Row Fusion D is production; the other variants were+ rejected.+- **Lesson:** Judge each design in a family separately. Sampled-head fusion is+ covered separately in [OUT-02](08-sampling-tokenization-and-output.md#out-02).++## Shader and head variants++<a id="orch-06"></a>+### ORCH-06: Shader-only sweep++- **Hypothesis:** Packed width, paired rows, remainder specialization, and local+ attention mappings could yield low-risk speedups.+- **Variants tested:** Scale/bias SIMD broadcast, threadgroup-staged+ activations, `ushort`/`uint` packed loads, metadata AoS/AoSoA, two rows per+ SIMDgroup, INT8 paired/multi-row loads, down-row padding, paired-row phase 1,+ SIMD-per-position attention, tiled attention, full-GQA attention, and an+ attention chunk sweep.+- **Evidence:** No variant earned promotion. INT8 already reached+ about 114 GB/s. Apparent first-run 2x wins vanished under interleaved warm+ rounds.+- **What changed the conclusion:** Thermal and first-run state explained+ the large early signals.+- **Final disposition:** Rejected sweep.+- **Lesson:**+ Interleave warm controls before believing a small shader delta.++<a id="orch-07"></a>+### ORCH-07: RoPE frequency tables++- **Hypothesis:** Precomputed frequencies would remove repeated trigonometric+ work.+- **Variants tested:** Current computation and table lookup.+- **Evidence:**+ The table path was neutral or slower.+- **What changed the conclusion:** Extra loads and indexing offset the saved+ arithmetic.+- **Final disposition:** Rejected.+- **Lesson:** Replacing arithmetic with memory traffic is not automatically a+ win on a GPU.++<a id="orch-08"></a>+### ORCH-08: LM-head width and tile sweep++- **Hypothesis:** Wider threadgroups and different vocab tiling would improve the+ large tied head.+- **Variants tested:** Several widths and tile layouts.+- **Evidence:** Isolated movement was small and no repeatable end-to-end gain+ appeared.+- **What changed the conclusion:** The system path absorbed or reversed+ local changes.+- **Final disposition:** Rejected.+- **Lesson:** Stop sweeping a+ family when end-to-end sensitivity stays below noise.++## Scheduling and synchronization++<a id="orch-09"></a>+### ORCH-09: Single-wait I/O pipeline++- **Hypothesis:** Coarser waits and a pipelined hit/miss schedule would reduce+ per-layer serialization.+- **Variants tested:** Production pipeline and rollback+ forms.+- **Evidence:** Production measured 6.416 tok/s. The full pipeline rollback+ measured 5.545 tok/s, and the hit-split-only rollback measured 5.926 tok/s.+- **What changed the conclusion:** Rollback+ isolated the value with the current stack.+- **Final disposition:** Production.+- **Lesson:** Synchronization removal helps when it preserves useful overlap and+ valid dependencies.++<a id="orch-10"></a>+### ORCH-10: Second Metal queue++- **Hypothesis:** Shared and routed GPU branches could run independently on two+ queues.+- **Variants tested:** Single and secondary queue schedules.+- **Evidence:** The single-queue control measured 5.592 tok/s; the+ secondary-queue candidate measured 5.059 tok/s.+- **What changed the conclusion:** Added synchronization+ and resource contention offset queue-level parallelism.+- **Final disposition:**+ Rejected.+- **Lesson:** Multiple queues do not create independent hardware.++<a id="orch-11"></a>+### ORCH-11: O3 cross-token chain++- **Hypothesis:** Carrying events across token boundaries would reduce CPU waits.+- **Variants tested:** Default orchestration and the O3 event chain on short and+ long rows.+- **Evidence:** The short median favored O3, 6.524 versus 6.385 tok/s;+ the long gate favored rollback, 6.756 versus 6.737.+- **What changed the conclusion:** Context-dependent mixed results did not justify the added state.+- **Final disposition:** Rejected and removed.+- **Lesson:** Cross-token complexity+ needs a stable gain across the supported context range.++<a id="orch-12"></a>+### ORCH-12: CB1 encode-ahead++- **Hypothesis:** Encoding the next token's cb1 while the current token completed+ would hide CPU work.+- **Variants tested:** Default and encode-ahead schedules.+- **Evidence:** The sustained 1K/256 candidate diverged from the control at+ emitted index 51 and regressed from the control's 4.801 tok/s to 4.613. An+ earlier tiny smoke had moved from 6.032 to 6.098 tok/s.+- **What changed the conclusion:** The sustained row reversed the smoke result.+- **Final disposition:** Rejected.+- **Lesson:** Use a sustained row for pipeline overlap decisions.++<a id="orch-13"></a>+### ORCH-13: Decode argument-buffer reuse++- **Hypothesis:** Recycling MoE bindings would reduce per-layer allocation and+ encode work.+- **Variants tested:** Fresh and reused argument buffers.+- **Evidence:** The reuse path had an unsafe lifetime and divergent output.+ Decode also fell from 4.754 to 3.998 tok/s, and prefill rose 9.6%.+- **What changed the conclusion:** Lifetime and speed both failed.+- **Final disposition:** Rejected+ and removed.+- **Lesson:** Resource reuse is invalid until GPU ownership and+ completion are explicit.++<a id="orch-14"></a>+### ORCH-14: All-hit fast path++- **Hypothesis:** Tokens with all experts cached could skip synchronization.+- **Variants tested:** General and all-hit-specialized paths across 351 states.+- **Evidence:** Total relevant synchronization was only 2.761 ms; decode remained+ neutral, 3.746 versus 3.736 tok/s.+- **What changed the conclusion:** The measured+ target was too small.+- **Final disposition:** Rejected.+- **Lesson:** Size the+ overhead before specializing it.++<a id="orch-15"></a>+### ORCH-15: Merge shared and hit command buffers++- **Hypothesis:** One command buffer would halve submissions without changing+ work.+- **Variants tested:** Separate and merged schedules.+- **Evidence:**+ Submissions fell, but decode regressed from 4.013 to 3.707 tok/s.+- **What changed the conclusion:** Submission reduction neither improved speed nor preserved+ output; the sequence diverged at index 36.+- **Final disposition:** Rejected.+- **Lesson:** Submission count is not a performance result.++[Previous: Prefill](06-prefill.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Sampling, tokenization, and output](08-sampling-tokenization-and-output.md)diff --git a/docs/experiments/summaries/08-sampling-tokenization-and-output.md b/docs/experiments/summaries/08-sampling-tokenization-and-output.mdnew file mode 100644index 00000000..183189b2--- /dev/null+++ b/docs/experiments/summaries/08-sampling-tokenization-and-output.md@@ -0,0 +1,92 @@+# Sampling, tokenization, and output experiments++[Previous: Fusions, head, and orchestration](07-fusions-head-and-orchestration.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Validation and measurement lessons](09-validation-and-measurement-lessons.md)++The main sampling win came from replacing a repeated-vocabulary algorithm with+one pass. Tokenizer caching produced a second large support-path win. Further+fusion and allocation work had mixed end-to-end value.++| Current result | Disposition |+| --- | --- |+| One-pass sampling with Top-P/Top-K | Production |+| Fused Gumbel head | Conditional; default off |+| Tokenizer process cache | Production; support path |+| Bounded detokenizer tail | Production; allocation hygiene |++## Sampling and head++<a id="out-01"></a>+### OUT-01: One-pass Gumbel sampling++- **Hypothesis:** One Gumbel-max pass over the vocabulary would replace repeated+ top-k extraction.+- **Variants tested:** The old repeated extraction, greedy+ selection, and one-pass sampled selection.+- **Evidence:** The old path took+ about 2.651 s/token and produced 0.377 tok/s. One-pass sampling restored about+ 5.86-5.89 tok/s, near greedy throughput.+- **What changed the conclusion:** The product path later added+ full-distribution Top-P, Top-K, then temperature. The default Top-K `64`+ case uses a specialized 1,024-to-64 reduction measured at 0.733 ms/sample.+- **Final disposition:** Production sampling path, including the specialized+ Top-64 truncation route.+- **Lesson:** Removing+ an avoidable algorithmic factor can dwarf kernel tuning.++<a id="out-02"></a>+### OUT-02: Fused Gumbel head++- **Hypothesis:** Sampling inside the LM-head reduction would avoid standalone+ logits and another pass.+- **Variants tested:** Fused sampling and standalone logits+ plus one-pass sampling, both using plain seeded temperature sampling.+- **Evidence:** The isolated candidate looked competitive, but end-to-end sampled+ decode produced 5.124 tok/s versus 5.192 tok/s for the standalone control.+- **What changed the conclusion:** Removing an+ intermediate did not shorten the whole pipeline.+- **Final disposition:** Conditional; default off. This is the sampling half of+ the wider fusion result in [ORCH-05](07-fusions-head-and-orchestration.md#orch-05).+- **Lesson:** Fusion needs a whole-step win even+ when it removes a visible buffer.++## Tokenization and output++<a id="out-03"></a>+### OUT-03: Tokenizer process cache++- **Hypothesis:** Reusing tokenizer state would avoid repeated model and table+ loading across tests and requests.+- **Variants tested:** Per-use load and a+ process cache.+- **Evidence:** The tokenizer suite body fell from 29.002 to 4.425+ s; command wall fell from 36.54 to 6.67 s, and peak RSS fell from 3.86 GB to+ 397 MB.+- **What changed the conclusion:**+ Nothing.+- **Final disposition:** Production; support-path cache.+- **Lesson:** Bounded+ reuse can improve both time and peak memory when initialization dominates.++<a id="out-04"></a>+### OUT-04: Bounded detokenizer tail++- **Hypothesis:** Avoiding growing trailing slices would remove quadratic+ allocation behavior.+- **Variants tested:** Original and bounded-tail+ detokenization over ASCII, byte-heavy, and mixed Unicode text.+- **Evidence:**+ ASCII and byte-heavy cases were neutral; mixed Unicode improved 17.51%, while+ the change removed explicit growing stable/trailing slices.+- **What changed the conclusion:** The cleanup bounded avoidable allocation without claiming linear+ scaling or an end-to-end decode win.+- **Final disposition:** Production; bounded-allocation hygiene.+- **Lesson:** State the resource goal separately+ from local microbenchmark movement.++[Previous: Fusions, head, and orchestration](07-fusions-head-and-orchestration.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |+[Next: Validation and measurement lessons](09-validation-and-measurement-lessons.md)diff --git a/docs/experiments/summaries/09-validation-and-measurement-lessons.md b/docs/experiments/summaries/09-validation-and-measurement-lessons.mdnew file mode 100644index 00000000..fa094adc--- /dev/null+++ b/docs/experiments/summaries/09-validation-and-measurement-lessons.md@@ -0,0 +1,204 @@+# Validation and measurement lessons++[Previous: Sampling, tokenization, and output](08-sampling-tokenization-and-output.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md)++Several conclusions changed because the original measurement answered the+wrong question. The project now separates exact lossless gates from numerical+quality gates, profiler attribution from clean throughput, and training traces+from representative holdouts.++| Current rule | Purpose |+| --- | --- |+| Exact identity for claimed-lossless changes | Detect unintended math or storage changes |+| Distributional quality for reordered floating-point work | Avoid false rejection near ties |+| Interleaved production A/B plus isolated attribution | Separate mechanism from outcome |+| Short, medium, long, and holdout rows | Detect scaling and generalization failures |++## Correctness and quality gates++<a id="meth-01"></a>+### METH-01: Numerical reordering needs a quality oracle++- **Hypothesis:** Exact cross-process tokens or raw logits could validate any+ candidate.+- **Variants tested:** That oracle was applied to MLX attention,+ staged MPP INT4 prefill, and batched routed MoE.+- **Evidence:** Each candidate+ had a strong speed signal but crossed known near ties under reordered+ floating-point work. Reference-relative delta-NLL, top-k agreement, and+ endpoint gates later passed.+- **What changed the conclusion:** The validation+ contract, not the candidates, was wrong.+- **Final disposition:** Methodology+ corrected; three false rejections reversed.+- **Lesson:** Numerical equivalence+ is a distributional claim, not a bit-identity claim.++<a id="meth-02"></a>+### METH-02: Lossless changes still require exact identity++- **Hypothesis:** Once quality gates replaced universal exact comparison, exact+ checks might be unnecessary.+- **Variants tested:** Cache policy, packed-load+ width, FP16 ring storage, and lossless fusion rollbacks.+- **Evidence:** These+ changes claim identical model math and therefore passed identical bits or+ tokens.+- **What changed the conclusion:** Nothing; the gate depends on the+ claim.+- **Final disposition:** Methodology retained.+- **Lesson:** Use the strictest gate appropriate to the candidate's contract,+ not one universal tolerance.++<a id="meth-03"></a>+### METH-03: Production-shaped offsets++- **Hypothesis:** An offset-zero parity buffer represented the standalone INT4+ path.+- **Variants tested:** Aligned test buffers and live resident tensors.+- **Evidence:** `uint` loads passed at offset zero but failed when BF16 planes+ left packed weights only 2-byte aligned.+- **What changed the conclusion:** The+ real layout invalidated the test's alignment assumption.+- **Final disposition:**+ Real-shape offset tests became required.+- **Lesson:** Include live offset and+ stride contracts in kernel fixtures.++<a id="meth-04"></a>+### METH-04: Threadgroup versus grid synchronization++- **Hypothesis:** A local barrier fix could stand in for a complete ownership and+ scope proof.+- **Variants tested:** The production shader inventory was audited+ across threadgroup scratch, disjoint device partials, and queue-ordered+ dispatches.+- **Evidence:** The only proven bug was a reused FP16 prefill+ reduction bank whose old cycle lacked a reader-to-next-writer edge. Other+ cross-threadgroup data relied on disjoint ownership and queue order, not a+ threadgroup barrier.+- **What changed the conclusion:** Synchronization scope+ became an explicit part of the proof.+- **Final disposition:** Methodology and correctness repair retained; the+ concrete failure is recorded in [KV-14](05-attention-and-kv-cache.md#kv-14).+- **Lesson:** Name the producer, consumer, memory+ region, ownership, and synchronization domain before choosing a barrier.++## Measurement discipline++<a id="meth-05"></a>+### METH-05: Profiler throughput is diagnostic++- **Hypothesis:** A profiled run's tok/s could serve as a production comparison.+- **Variants tested:** A clean production row, an attribution profile, and a+ production-behavior timeline row.+- **Evidence:** The clean row measured 6.144+ tok/s. Profile instrumentation disabled the normal command-buffer pipeline and+ measured 4.228 tok/s; the timeline retained production behavior and measured+ 6.337 tok/s.+- **What changed the conclusion:** Clean, profile, and timeline rows answer+ different questions: production throughput, detailed attribution, and+ production-behavior timing. They are not interchangeable throughput samples.+- **Final disposition:** Methodology retained.+- **Lesson:** Use profiler+ spans to choose a target and clean A/B rows to decide promotion.++<a id="meth-06"></a>+### METH-06: First-run and thermal state++- **Hypothesis:** One control/candidate pair could establish a small shader win.+- **Variants tested:** Single-order runs, interleaved warm rounds, and balanced+ M5 thermal sequences.+- **Evidence:** Apparent 15-100% swings, including apparent 2x wins on the first+ run, disappeared under interleaving.+- **What changed the conclusion:**+ Order and thermal state explained the signal.+- **Final disposition:** Balanced+ interleaved measurement adopted.+- **Lesson:** Small GPU deltas require an order+ that cannot assign warm-up or throttling to one variant.++<a id="meth-07"></a>+### METH-07: Mechanism counts are not outcomes++- **Hypothesis:** Fewer allocations, dispatches, or command buffers implied a+ faster path.+- **Variants tested:** Argument-buffer rings and merged command+ buffers.+- **Evidence:** The ring cut 21,217 allocations to two but slowed long+ prefill about 9%. The merge cut submissions but slowed decode from 4.013 to+ 3.707 tok/s.+- **What changed the conclusion:** Both mechanism counts improved+ while their end-to-end gates regressed.+- **Final disposition:** End-to-end time+ remains the promotion gate.+- **Lesson:** Mechanism counters explain results; they do not replace results.++<a id="meth-08"></a>+### METH-08: Training traces need holdouts++- **Hypothesis:** A policy optimized on one or several related traces would+ generalize.+- **Variants tested:** Single-trace packed layout and trace-trained+ heterogeneous cache allocation.+- **Evidence:** The layout won natural-text+ replay and failed near 4K; the allocation lost on its held-out trace.+- **What changed the conclusion:** Workload-specific locality did not transfer.+- **Final disposition:** Representative holdouts required; see+ [CACHE-04](03-expert-cache-prediction-and-layout.md#cache-04) and+ [CACHE-08](03-expert-cache-prediction-and-layout.md#cache-08).+- **Lesson:** Treat+ layout and cache policies like learned models.++<a id="meth-09"></a>+### METH-09: Greedy repetition-loop artifact++- **Hypothesis:** The long fixture's hit-rate decline revealed a general cache+ defect.+- **Variants tested:** Offline token-period and route-period analysis of+ the existing trace.+- **Evidence:** Late output locked into a period-44 loop with+ 94-100% rolling ID match. One cycle touched a median 62 distinct experts per+ layer versus 16 slots. The apparent hit-rate decline from 66.6% to 54.2% was+ cyclic thrash from repeated text.+- **What changed the conclusion:** The fixture+ was an artificial routing workload.+- **Final disposition:** Long-decode+ methodology corrected.+- **Lesson:** Label repetition onset before treating a+ greedy long run as representative generation.++## Boundaries that were not failed experiments++- ANE/Core ML offload was excluded by the platform and architecture decision;+ no failed ANE performance candidate exists.+- Requantizing weights below INT4 was cancelled by the quality floor; no 3-bit+ or 2-bit weight runtime was built.+- Draft-model speculative decoding and n-gram verification stopped at limited+ scope analysis; they were not complete runtime candidates.+- Cache-conditional routing remains a quality-changing hypothesis. Production+ routing was never cache-conditional.+- APFS preallocation remains unexecuted.+- The iPhone port is deferred; all performance results here are Mac results.++## False rejections and attribution corrections++Three experiment conclusions are genuine reversed quality rejections:++1. [MLX full-attention geometry](05-attention-and-kv-cache.md#kv-06) had a+ genuine speed signal and later shipped as v2 after the quality oracle was+ repaired.+2. [Staged affine MPP INT4 prefill](06-prefill.md#pf-12) shipped after a+ distributional quality gate replaced an exact raw-logit comparison.+3. [Batched routed MoE prefill](06-prefill.md#pf-15) shipped after the same+ class of validation error was corrected.++QKV epilogue fusion is a separate attribution warning. An early row was noisy;+a later joint rollback supported the targeted fusion stack but did not isolate+the epilogue's share.++[Previous: Sampling, tokenization, and output](08-sampling-tokenization-and-output.md) |+[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Optimization journey](../../OPTIMIZATION_JOURNEY.md)