Modern Apps git

← Modern-Apps.git

chess: replace Stockfish with Maia3-5M int8 on :library:ml

Commit
0cde9d838e37595bc525960fdfdd021d3c8c5bd0
Author
vayun-mathur <[email protected]>
When
2026-09-04 07:16 UTC (3 months ago)
Parents
eacebf3

Diff

SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex cfdb8d57b7..cdec62b4f3 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -82,9 +82,15 @@ It also came out **more accurate**, not less, because reading each model's fp32  Both are **build-host** dependencies only, pinned by upstream revision *and* file SHA-256 in `scripts/ml/fetch_and_convert.sh`, with provenance in a `README.md` beside each asset and the source ONNX SHA-256 baked into each `.maml` header. If either vanished, shipped builds keep working. The ONNX itself is not vendored: it is twice the size and nothing reads it at run time. -The trade-off accepted is **GPU-only**: `:library:ml` needs Vulkan 1.1 plus `VK_KHR_shader_float16_int8`, which was promoted to core only in Vulkan 1.2 and so is optional at the 1.1 floor minSdk 31 guarantees. On a device without it, portrait bokeh, auto-select-subject, OCR, speech synthesis and translation turn off rather than falling back to CPU.+The trade-off accepted is **GPU-only**: `:library:ml` needs Vulkan 1.1 plus `VK_KHR_shader_float16_int8`, which was promoted to core only in Vulkan 1.2 and so is optional at the 1.1 floor minSdk 31 guarantees. On a device without it, portrait bokeh, auto-select-subject, OCR, speech synthesis, translation and the chess AI turn off rather than falling back to CPU. -**ncnn is gone from the tree.** `:translate` was its last consumer, and SMaLL-100 now runs on `:library:ml` too, so `libncnn_android.so` is in no APK here and the self-built `com.github.vayun-mathur:ncnn-android` AAR — a JitPack fork of a third-party runtime, built from a local checkout and resolved through `mavenLocal()` — has left the supply chain entirely. `mavenLocal()` went with it: it existed only so a freshly built ncnn resolved ahead of a rate-limited JitPack, and a local repository ahead of the remotes means any coordinate in `~/.m2` silently outranks the pinned one. The JitPack declaration stays, scoped to `com.github.*`, for `Stockfish-Library` and `com.github.luben:zstd-jni`.+**ncnn is gone from the tree.** `:translate` was its last consumer, and SMaLL-100 now runs on `:library:ml` too, so `libncnn_android.so` is in no APK here and the self-built `com.github.vayun-mathur:ncnn-android` AAR — a JitPack fork of a third-party runtime, built from a local checkout and resolved through `mavenLocal()` — has left the supply chain entirely. `mavenLocal()` went with it: it existed only so a freshly built ncnn resolved ahead of a rate-limited JitPack, and a local repository ahead of the remotes means any coordinate in `~/.m2` silently outranks the pinned one. The JitPack declaration stays, scoped to `com.github.*`, for `com.github.luben:zstd-jni`.++**Stockfish is gone too, and with it the last personal JitPack fork.** `games/chess` played against `com.github.vayun-mathur:Stockfish-Library` — a prebuilt AAR from a personal GitHub repo, driven over raw UCI text, with an 86 MB NNUE bundled as an APK asset. It now plays against **Maia3-5M** on `:library:ml`: an encoder-only transformer that predicts *human* moves at a requested rating, one forward pass per move and no search. Upstream is **`UofTCSSLab/Maia3-5M`**, a **build-host** dependency pinned by HF revision and checkpoint SHA-256 in `scripts/ml/fetch_maia.py`.++Three things improve at once. The remaining JitPack coordinate is a third-party library (`zstd-jni`) rather than a personal fork, so no build here depends on a repo one person can delete. The APK loses **~79 MB**: the 86 MB NNUE is replaced by a 6.8 MiB int8 `.maml`. And the AI plays better chess in the sense that matters for a casual app — Stockfish at `Skill Level 0` blundered in ways no beginner does, where Maia at 1100 blunders the way an 1100 does.++The int8 was chosen on measured **move agreement** rather than on the per-tensor cosine gate, because a cosine says nothing about whether a chess model still picks the same move: `scripts/ml/maia_quant_eval.py` puts int8 at 99.0–99.5% agreement with fp32 across the four difficulties with no disagreement wider than fp16 rounding, and rejects int4 at 87–91% with 14–29 genuine changes of mind at any group size.  The port also removed the only two tagged-memory faults this tree has seen, both inside `libncnn_android.so`, and cut the translation model's download from **1.14 GB across seven files to 320 MB across two** — ncnn could not quantise the 131M-parameter embedding, so the shipped model was fp16 and carried it twice; the `.maml` is int8 per output channel and carries it once, because it is tied. Upstream is **`alirezamsh/small100`** (MIT), a **build-host** dependency pinned by revision and file SHA-256 in `scripts/ml/fetch_small100.py`. Nothing about the model is built locally any more. @@ -96,7 +102,7 @@ Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `conta  ### Build Infrastructure -- **Maven repositories**: `google()` (filtered), `mavenCentral()`, `gradlePluginPortal()` in `build-logic/settings`, plus **`https://jitpack.io`** in root `settings.gradle.kts`, scoped to `com.github.*`. JitPack now serves **one** personal fork, `Stockfish-Library` (games:chess), plus `com.github.luben:zstd-jni`; `ncnn-android` is gone with ncnn itself (✅ above), and `mavenLocal()` — which existed only to resolve it — is gone with it. `nanojson` was vendored to `:third_party:nanojson` (✅ mitigation #2). JitPack remains a reproducible-build SPOF for Stockfish.+- **Maven repositories**: `google()` (filtered), `mavenCentral()`, `gradlePluginPortal()` in `build-logic/settings`, plus **`https://jitpack.io`** in root `settings.gradle.kts`, scoped to `com.github.*`. JitPack now serves **no personal forks at all**, only `com.github.luben:zstd-jni`: `ncnn-android` is gone with ncnn itself (✅ above), `Stockfish-Library` is gone with Stockfish (✅ above), and `mavenLocal()` — which existed only to resolve the former — is gone with it. `nanojson` was vendored to `:third_party:nanojson` (✅ mitigation #2). JitPack is still a reproducible-build SPOF, but now only for a third-party library rather than for a repo one person can delete. - **Launch icon generator**: `build-logic/src/main/kotlin/LauncherIconGen.kt` downloads `https://raw.githubusercontent.com/google/material-design-icons/819d786.../symbols/android/{icon}/...24px.xml` at build time, cached under `~/.gradle/material-symbols-cache`. Build needs GitHub availability on first (uncached) build. ⚠️ Not yet mitigated. - **Alpha toolchain**: `agp = 9.4.0-alpha04`, `composeBom = 2026.06.01` (future-dated), `navigation3 = 1.2.0-alpha05`, `material3 = 1.5.0-alpha23`, `biometric = 1.4.0-alpha07`, `camerax = 1.7.0-alpha02`, `datastore = 1.3.0-alpha09`. ⚠️ Stable release branch should pin stable versions (not yet done). - **Version drift**: `okhttp 4.12.0` (2y old, 5.x exists) ⚠️ still pinned. `ktor` fully removed (`:messages` migrated to `:library:network` ✅) and `mediapipe tasks-vision` unified at `0.10.35` (camera inline `0.10.14` removed ✅).@@ -146,7 +152,7 @@ Summed old per-crate locks (before workspace) = 712 total (641 excluding voxels)  | Library | Version | Used By | Why High Risk | File | |---|---|---|---|---|-| `com.github.vayun-mathur:Stockfish-Library` via JitPack | `1.1.0` | `games/chess` | Personal fork on JitPack, if GitHub repo deleted build breaks. Only remaining JitPack dep | `games/chess/build.gradle.kts` |+| `com.github.luben:zstd-jni` via JitPack | — | see `libs.versions.toml` | The only remaining JitPack coordinate. Third-party rather than a personal fork, so lower risk than `Stockfish-Library` was | `settings.gradle.kts` | | `jitpack.io` itself | — | above | Supply chain SPOF | `settings.gradle.kts` | | `io.github.dokar3:quickjs-kt` | `1.0.5` | `youpipe` | Single maintainer (dokar3), JS eval for YouTube signature decipher — critical path | `youpipe/build.gradle.kts`, `libs.versions.toml:8` | | `dev.whyoleg.cryptography:cryptography-core` + `cryptography-provider-jdk` | `0.6.0` | `library:e2ee-p2p` → `office` E2EE | Single person (whyoleg), crypto-critical for PQC KEM | `library:e2ee-p2p/build.gradle.kts`, `libs.versions.toml:75` |
games/chess/build.gradle.kts
diff --git a/games/chess/build.gradle.kts b/games/chess/build.gradle.ktsindex 9474f2b636..7963be58e7 100644--- a/games/chess/build.gradle.kts+++ b/games/chess/build.gradle.kts@@ -14,12 +14,14 @@ android {         applicationId = "com.vayunmathur.games.chess"     }     androidResources {-        noCompress += "nnue"+        // Maia3's weights are read in place through an `AssetFileDescriptor`, and+        // `AssetManager.openFd` throws for a deflated entry. Costs nothing on download size:+        // fp16 weights barely compress.+        noCompress += "maml"     } }  dependencies {     implementation(project(":sdk:games"))-    implementation(libs.stockfish.library)-+    implementation(project(":library:ml")) }
games/chess/src/main/assets/README.md
diff --git a/games/chess/src/main/assets/README.md b/games/chess/src/main/assets/README.mdnew file mode 100644index 0000000000..a8ff0f5eb9--- /dev/null+++ b/games/chess/src/main/assets/README.md@@ -0,0 +1,69 @@+# `maia3-5m.maml`++Maia3-5M, the chess AI. Converted from **[`UofTCSSLab/Maia3-5M`](https://huggingface.co/UofTCSSLab/Maia3-5M)**+(`maia3-5m.pt`, 20.0 MB fp32) to 6.8 MiB of int8.++Rebuild it byte for byte with:++    python scripts/ml/fetch_maia.py++which pins the upstream revision and the checkpoint's SHA-256, asserts the parameter inventory,+and writes this file. Committed rather than gitignored, for the same reason `:speech`'s voice+bundle is: a fresh checkout that silently ships a chess app with no opponent is worse than the+history.++## What it is++An encoder-only transformer over 64 square tokens — width 256, 8 blocks, 8 heads, 5,230,084+parameters. Upstream calls the architecture "Chessformer"; the code is+[CSSLab/maia3](https://github.com/CSSLab/maia3).++It **predicts human moves** rather than searching for good ones. One forward pass per move, no+tree. Strength is a model input (`SelfElo` / `OppoElo`, 0..5000), so this one file covers all+four difficulty levels — see `Difficulty` in+`games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt`.++It replaces Stockfish and its 86 MB `nn-71d6d32cb962.nnue`, which is where the APK's ~79 MB+reduction comes from. It also removed the last personal JitPack fork from the tree; see+`SUPPLY_CHAIN_RISKS.md`.++## Precision++Every `1x1` convolution is int8, quantised per output channel; the norms, the biases and the+two elo embeddings stay fp16 and are 1% of the parameters. Worst per-tensor correlation against+fp32 is 0.999941.++That was chosen on **move agreement**, not on the cosine gate, because a cosine says nothing+about whether the model still picks the same move:++| | size | move agreement vs fp32 | disagreements wider than fp16 rounding |+|---|---|---|---|+| fp16 | 13.3 MiB | — | — |+| **int8, per channel** | **6.8 MiB** | **99.0–99.5%** | **0** |+| int4, per 16 | 4.2 MiB | 91.2% | 14 |+| int4, per channel | 3.5 MiB | 88.0% | 29 |++int4 is rejected: its disagreements are the model changing its mind, not losing a coin flip,+and sub-row grouping gives back most of the saving without fixing it. 5.2M parameters have no+redundancy to spare. Re-measure any of this with `python scripts/ml/maia_quant_eval.py`.++## How it is checked++* `scripts/ml/test/test_maia.py` — the converter's tensor order, the int8 triple, and the two+  structural rewrites (the fused q/k/v split, the eight-fold attention-bias replication),+  against a toy model.+* `scripts/ml/maia_parity.py` — the real weights through the Rust interpreter against the+  PyTorch reference, over `maia_parity_fixture.json`. Agreement on the best **legal** move as+  well as on the numbers, because a wrong board encoding still plays legal chess.+* `scripts/ml/maia_quant_eval.py` — what the quantisation costs, in moves, over hundreds of+  positions at every shipping rating.+* `MaiaEncodingTest` in `src/test/` — the board planes, the move vocabulary and perft.++The forward pass is `library/ml/src/main/rust/src/nets/maia.rs`, which documents the parts that+fail silently: the post-norm block order, the RMS norms, and why the attention bias is a grouped+convolution.++## Licence++Maia3's weights are released by the University of Toronto's Computational Social Science Lab.+See the model card at the link above for terms.
games/chess/src/main/assets/maia3-5m.maml
diff --git a/games/chess/src/main/assets/maia3-5m.maml b/games/chess/src/main/assets/maia3-5m.mamlnew file mode 100644index 0000000000..604f2827f4Binary files /dev/null and b/games/chess/src/main/assets/maia3-5m.maml differ
games/chess/src/main/assets/nn-71d6d32cb962.nnue
diff --git a/games/chess/src/main/assets/nn-71d6d32cb962.nnue b/games/chess/src/main/assets/nn-71d6d32cb962.nnuedeleted file mode 100644index e25c9fb420..0000000000Binary files a/games/chess/src/main/assets/nn-71d6d32cb962.nnue and /dev/null differ
games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.ktindex 8beee6345a..d10b7b7e65 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt@@ -77,7 +77,7 @@ import com.vayunmathur.games.chess.util.LearnStatus import com.vayunmathur.games.chess.util.LearnProgress import com.vayunmathur.games.chess.data.LearnCategory import com.vayunmathur.games.chess.data.square-import com.vayunmathur.games.chess.util.StockfishEngine+import com.vayunmathur.games.chess.util.Difficulty import com.vayunmathur.games.chess.data.Piece import com.vayunmathur.games.chess.data.PieceColor import com.vayunmathur.games.chess.data.PieceType@@ -168,10 +168,7 @@ class MainActivity : ComponentActivity() {                         entry<Route.Game>(metadata = SiblingPage()) {                             val viewModel: ChessViewModel = viewModel()                             var showNewGameDialog by remember { mutableStateOf(false) }--                            LaunchedEffect(Unit) {-                                StockfishEngine.start(this@MainActivity)-                            }+                            val aiAvailable by viewModel.aiAvailable.collectAsState()                              ChessGame(                                 viewModel = viewModel,@@ -185,7 +182,8 @@ class MainActivity : ComponentActivity() {                                     onNewGame = {                                         viewModel.onNewGame(it)                                         showNewGameDialog = false-                                    }+                                    },+                                    aiAvailable = aiAvailable                                 )                             }                         }@@ -234,13 +232,20 @@ class MainActivity : ComponentActivity() {  } +/**+ * The new-game picker.+ *+ * [aiAvailable] defaults true so the store-listing preview renders the full dialog. On a real+ * device it comes from [ChessViewModel.aiAvailable], and the AI button is hidden rather than+ * disabled when the model cannot run: a mode that can never move is not worth explaining.+ */ @Composable-fun NewGameDialog(onNewGame: (GameMode) -> Unit) {-    var showSettings by remember { mutableStateOf<((PieceColor, StockfishEngine.Difficulty) -> Unit)?>(null) }+fun NewGameDialog(onNewGame: (GameMode) -> Unit, aiAvailable: Boolean = true) {+    var showSettings by remember { mutableStateOf<((PieceColor, Difficulty) -> Unit)?>(null) }      showSettings?.let { startGame ->         var selectedColor by remember { mutableStateOf(PieceColor.WHITE) }-        var selectedDifficulty by remember {mutableStateOf(StockfishEngine.Difficulty.INTERMEDIATE)}+        var selectedDifficulty by remember {mutableStateOf(Difficulty.INTERMEDIATE)}         AlertDialog(             properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),             modifier = Modifier.fillMaxWidth(0.9f),@@ -272,7 +277,7 @@ fun NewGameDialog(onNewGame: (GameMode) -> Unit) {                     }                     Spacer(Modifier.height(16.dp))                     SingleChoiceSegmentedButtonRow {-                        StockfishEngine.Difficulty.entries.zip(listOf(stringResource(R.string.difficulty_easy), stringResource(R.string.difficulty_medium), stringResource(R.string.difficulty_hard), stringResource(R.string.difficulty_master))).forEachIndexed { idx, (value, label) ->+                        Difficulty.entries.zip(listOf(stringResource(R.string.difficulty_easy), stringResource(R.string.difficulty_medium), stringResource(R.string.difficulty_hard), stringResource(R.string.difficulty_master))).forEachIndexed { idx, (value, label) ->                             SegmentedButton(                                 shape = SegmentedButtonDefaults.itemShape(idx, 4),                                 onClick = { selectedDifficulty = value },@@ -301,12 +306,14 @@ fun NewGameDialog(onNewGame: (GameMode) -> Unit) {                         Text(stringResource(R.string.two_player_local))                     }                     Spacer(modifier = Modifier.height(8.dp))-                    Button(onClick = {-                        showSettings = { color, difficulty ->-                            onNewGame(GameMode.VsAI(color, difficulty))+                    if (aiAvailable) {+                        Button(onClick = {+                            showSettings = { color, difficulty ->+                                onNewGame(GameMode.VsAI(color, difficulty))+                            }+                        }) {+                            Text(stringResource(R.string.human_vs_ai))                         }-                    }) {-                        Text(stringResource(R.string.human_vs_ai))                     }                 }             },@@ -364,7 +371,7 @@ fun ChessGame(                 achievementsManager.onAchievementUnlocked("won_fast")             } -            if (mode is GameMode.VsAI && mode.difficulty >= StockfishEngine.Difficulty.ADVANCED) {+            if (mode is GameMode.VsAI && mode.difficulty >= Difficulty.ADVANCED) {                 achievementsManager.onAchievementUnlocked("win_vs_ai_hard")             }         }@@ -381,7 +388,7 @@ fun ChessGame( /**  * The play screen, with no dependency on the ViewModel so it can be rendered from a  * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.- * Nothing here touches Stockfish; the engine is only ever reached through the ViewModel.+ * Nothing here touches the model; the engine is only ever reached through the ViewModel.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable
games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.ktindex fcb91d867f..873f9002b9 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt@@ -222,12 +222,69 @@ data class Board(      /** True if [color] has at least one legal move (move that doesn't leave its own king in check). */     fun hasLegalMoves(color: PieceColor): Boolean {-        return pieces.flatMapIndexed { row, cols ->-            cols.mapIndexedNotNull { col, piece ->-                if (piece != null && piece.color == color) Position(row, col) else null+        var any = false+        walkLegalMoves(color) { _, _ ->+            any = true+            false+        }+        return any+    }++    /**+     * Every legal move [color] can play, with the four promotion choices expanded.+     *+     * The engine's move list and the mate/stalemate test are the same generator, so the rules+     * cannot disagree with themselves — [hasLegalMoves] is this with an early exit.+     *+     * Promotions are the one thing [isValidMove] cannot express: it validates a pawn's step to+     * the last rank without saying what it becomes, and [movePiece] handles the choice+     * out-of-band through [promotionPosition]. An engine has to choose up front, so a promoting+     * step appears here four times, once per [PROMOTION_CHOICES] entry.+     */+    fun legalMoves(color: PieceColor): List<Move> {+        val moves = mutableListOf<Move>()+        walkLegalMoves(color) { start, end ->+            val piece = pieces[start.row][start.col] ?: return@walkLegalMoves true+            // En passant captures a pawn that is not on the destination square, so the captured+            // piece is read the way `movePiece` reads it rather than off `end`.+            val captured = if (piece.type == PieceType.PAWN && isEnPassant(start, end)) {+                pieces[enPassantCaptureRow(piece.color, end.row)][end.col]+            } else {+                pieces[end.row][end.col]+            }+            if (isPromotionSquare(piece, end)) {+                for (promotion in PROMOTION_CHOICES) {+                    moves.add(Move(start, end, piece, captured, promotedTo = promotion))+                }+            } else {+                moves.add(Move(start, end, piece, captured))+            }+            true+        }+        return moves+    }++    /**+     * Visit every legal `(start, end)` pair for [color], stopping when [visit] returns false.+     *+     * The same 64x64 scan [hasLegalMoves] always did. It is cheap in practice because+     * `isValidMoveIgnoringCheck` rejects almost all 4096 pairs before [isValidMove] clones the+     * board, leaving around forty clones in a typical position.+     */+    private fun walkLegalMoves(color: PieceColor, visit: (Position, Position) -> Boolean) {+        for (row in 0..7) {+            for (col in 0..7) {+                val piece = pieces[row][col] ?: continue+                if (piece.color != color) continue+                val start = Position(row, col)+                for (endRow in 0..7) {+                    for (endCol in 0..7) {+                        val end = Position(endRow, endCol)+                        if (!isValidMove(start, end)) continue+                        if (!visit(start, end)) return+                    }+                }             }-        }.any { pos ->-            (0..7).any { i -> (0..7).any { j -> isValidMove(pos, Position(i, j)) } }         }     } @@ -420,6 +477,20 @@ data class Board(     }      companion object {+        /**+         * What a pawn may become, in the order Maia3's move vocabulary lists them.+         *+         * The order is load-bearing for `MaiaEngine.moveIndex`, which turns a promotion into+         * `4096 + fromFile * 32 + toFile * 4 + PROMOTION_CHOICES.indexOf(piece)`. Reordering it+         * would silently score every promotion as a different piece.+         */+        val PROMOTION_CHOICES = listOf(+            PieceType.QUEEN,+            PieceType.ROOK,+            PieceType.BISHOP,+            PieceType.KNIGHT,+        )+         val initialState = Board(             pieces = listOf(                 listOf(
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessApi.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessApi.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessApi.ktindex c495c7cc99..834ba6ff8b 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessApi.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessApi.kt@@ -1,33 +1,38 @@ package com.vayunmathur.games.chess.util++import android.content.Context import com.vayunmathur.games.chess.data.Board import com.vayunmathur.games.chess.data.Move-import com.vayunmathur.games.chess.data.Position-import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.PieceColor++/**+ * The app's one call into the chess engine.+ *+ * A seam rather than a wrapper: everything that knows the engine exists is on this side of it,+ * so [com.vayunmathur.games.chess.util.ChessViewModel] asks for a move and nothing else in the+ * app can reach a model. The store-listing previews render through+ * [ChessActions.Noop] and never construct this, which is what keeps a screenshot run from+ * trying to bring up Vulkan on a JVM.+ */+class ChessApi(context: Context) {++    private val engine = MaiaEngine(context)++    /** Whether the AI can play at all on this device. See [MaiaEngine.isAvailable]. */+    suspend fun isAvailable(): Boolean = engine.isAvailable() -class ChessApi {     /**-     * Returns the engine's best move, or null when the engine reports it has no move to play-     * ("bestmove (none)" / "0000" — i.e. the AI is checkmated or stalemated). Callers must treat-     * null as "no move available" rather than parsing it as a board coordinate.+     * The engine's move, or null when there is none to play.+     *+     * Null means the AI is checkmated or stalemated, or the model is unavailable. Callers must+     * treat it as "no move" rather than as a failure to parse one.+     *+     * [turn] comes from the UI's state, not from [board]: the rules model infers the side to+     * move from its last move, and the puzzle path seeds that with a synthetic king move.      */-    suspend fun getBestMove(board: Board): Move? {-        StockfishEngine.nextMove(board)-        while (true) {-            val lineSplit = StockfishEngine.outputChannel.receive().split(" ")-            if (lineSplit[0] == "bestmove") {-                val moveString = lineSplit.getOrNull(1) ?: return null-                if (moveString == "(none)" || moveString == "0000" || moveString.length < 4) return null-                val startPosition = Position(8 - (moveString[1] - '0'), moveString[0] - 'a')-                val endPosition = Position(8 - (moveString[3] - '0'), moveString[2] - 'a')-                val promotedTo = when (moveString.getOrNull(4)) {-                    'q' -> PieceType.QUEEN-                    'r' -> PieceType.ROOK-                    'b' -> PieceType.BISHOP-                    'n' -> PieceType.KNIGHT-                    else -> null-                }-                return Move(startPosition, endPosition, board.pieces[startPosition.row][startPosition.col]!!, promotedTo = promotedTo)-            }-        }-    }+    suspend fun getBestMove(board: Board, turn: PieceColor, difficulty: Difficulty): Move? =+        engine.bestMove(board, turn, difficulty)++    /** Free the model. Idempotent; called from the view model's `onCleared`. */+    fun close() = engine.close() }
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.ktindex f451b614a9..0abc6b5be4 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt@@ -9,8 +9,8 @@ import com.vayunmathur.games.chess.data.Position  * The screens take their state ([ChessUiState] / [PuzzleUiState], both declared next to their  * ViewModel) plus an actions interface rather than the ViewModel itself, so they can be  * rendered by a `@Preview` — which is what the store listing images are generated from. That- * also keeps the engine out of the picture: nothing here can reach Stockfish, so a preview- * renders a static position and never starts a native search.+ * also keeps the engine out of the picture: nothing here can reach the model, so a preview+ * renders a static position and never brings up a Vulkan device.  *  * Every method has a no-op default, so `Noop` is the whole implementation a preview needs.  */
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.ktindex fb7f65f168..ddf5fc111b 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt@@ -17,7 +17,7 @@ import kotlinx.coroutines.launch  sealed class GameMode {     data object TwoPlayer : GameMode()-    data class VsAI(val playerColor: PieceColor, val difficulty: StockfishEngine.Difficulty) : GameMode()+    data class VsAI(val playerColor: PieceColor, val difficulty: Difficulty) : GameMode() }  /** Terminal outcome of a game, or null while it is still in progress. */@@ -43,14 +43,27 @@ class ChessViewModel(application: Application) : AndroidViewModel(application),      private val _uiState = MutableStateFlow(ChessUiState())     val uiState: StateFlow<ChessUiState> = _uiState.asStateFlow()-    private val chessApi = ChessApi()+    private val chessApi = ChessApi(application)++    /**+     * Whether the "play against the AI" option is offered.+     *+     * False on a device that cannot run the model — no `libmodelrunner.so` for its ABI, or no+     * Vulkan device with fp16 compute. Offering a mode that can never move would be worse than+     * not offering it, so the picker hides it. Mirrors `translationAvailable`.+     */+    private val _aiAvailable = MutableStateFlow(false)+    val aiAvailable: StateFlow<Boolean> = _aiAvailable.asStateFlow()++    init {+        viewModelScope.launch { _aiAvailable.value = chessApi.isAvailable() }+    }      fun onNewGame(gameMode: GameMode) {         val isFlipped = gameMode is GameMode.VsAI && gameMode.playerColor == PieceColor.BLACK         _uiState.value = ChessUiState(gameMode = gameMode, isBoardFlipped = isFlipped)-        if (gameMode is GameMode.VsAI) {-            StockfishEngine.difficulty = gameMode.difficulty-            if (gameMode.playerColor == PieceColor.BLACK) makeAiMove()+        if (gameMode is GameMode.VsAI && gameMode.playerColor == PieceColor.BLACK) {+            makeAiMove()         }     } @@ -110,13 +123,17 @@ class ChessViewModel(application: Application) : AndroidViewModel(application),     }      private fun makeAiMove() {+        val mode = _uiState.value.gameMode as? GameMode.VsAI ?: return         viewModelScope.launch {-            val board = _uiState.value.board-            // Returns null when the engine has no move to make (mate/stalemate against the AI);-            // without this guard the "bestmove (none)" reply would be parsed as a coordinate and crash.-            val bestMove = chessApi.getBestMove(board) ?: return@launch-            val newBoard = board.movePiece(bestMove.start, bestMove.end, bestMove.promotedTo)-            val nextTurn = _uiState.value.turn.opposite+            val state = _uiState.value+            // The side to move comes from the UI's own state rather than from the board: the+            // rules model infers a turn from its last move, which the puzzle path fakes.+            // Returns null when the engine has no move to make (mate or stalemate against the+            // AI, or an unavailable model).+            val bestMove = chessApi.getBestMove(state.board, state.turn, mode.difficulty)+                ?: return@launch+            val newBoard = state.board.movePiece(bestMove.start, bestMove.end, bestMove.promotedTo)+            val nextTurn = state.turn.opposite             val (result, status) = statusFor(newBoard, nextTurn)             _uiState.update {                 it.copy(board = newBoard, turn = nextTurn, gameStatus = status, gameResult = result)@@ -124,6 +141,10 @@ class ChessViewModel(application: Application) : AndroidViewModel(application),         }     } +    override fun onCleared() {+        chessApi.close()+    }+     /** Terminal result for [board] when it is [turn]'s move, or null if play continues. */     private fun resultFor(board: Board, turn: PieceColor): GameResult? = when {         board.isCheckmate(turn) -> GameResult.Checkmate(turn.opposite)
games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.ktnew file mode 100644index 0000000000..3f9a9a38f7--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt@@ -0,0 +1,271 @@+package com.vayunmathur.games.chess.util++import android.content.Context+import android.util.Log+import com.vayunmathur.games.chess.data.Board+import com.vayunmathur.games.chess.data.Move+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.data.opposite+import com.vayunmathur.library.ml.MaiaHandle+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlin.math.exp+import kotlin.random.Random++/**+ * How strong the AI plays, as a rating the model is asked to imitate.+ *+ * Maia3 takes strength as an **input** rather than as a search handicap, so these are Elo+ * ratings and not depth or skill settings. A level plays like a human of that rating: it makes+ * the mistakes that rating makes, rather than playing well and then discarding a move.+ *+ * Ratings are from Lichess blitz, which is what the model was trained on. `GRANDMASTER` at 2500+ * is near the top of that distribution; asking for much more extrapolates past what the model+ * has seen rather than getting stronger.+ *+ * Sampling is deliberately not argmax — the upstream `maia3-5m` launcher runs at temperature 0,+ * which plays the identical game from the identical position every time. A little temperature+ * with nucleus sampling keeps the strength while varying the game, and it narrows as the level+ * rises because a stronger player has fewer moves worth considering.+ *+ * **Four entries in ascending order**, and that is a contract with two places:+ * `MainActivity`'s picker zips them positionally against four localized labels, and its+ * `win_vs_ai_hard` achievement gate compares ordinals against [ADVANCED].+ *+ * Declared here as a top-level enum rather than inside [MaiaEngine] on purpose: the store+ * listing screenshots render `NewGameDialog`, which reads [entries], on a JVM with no device.+ * Reaching it must not pull in a class whose initialiser loads a `.so`.+ */+enum class Difficulty(val elo: Int, val temperature: Float, val topP: Float) {+    BEGINNER(1100, 0.5f, 0.95f),+    INTERMEDIATE(1500, 0.4f, 0.95f),+    ADVANCED(1900, 0.35f, 0.95f),+    GRANDMASTER(2500, 0.3f, 0.95f),+}++/**+ * The chess AI: Maia3-5M on `:library:ml`'s Vulkan runtime.+ *+ * One forward pass per move and no search. It replaces Stockfish, which was an 86 MB NNUE and a+ * depth-8 tree behind a JitPack AAR driven over UCI text through two channels; none of that+ * survives, including the UCI, which was only ever Stockfish's transport.+ *+ * # What a move costs+ *+ * Encode the board to 12 planes, one inference, mask 4352 logits to the legal moves, sample.+ * The mask is what makes the model safe to use: it scores every from-to pair on the board,+ * including the ~4000 that are not moves, so the legal list is not an optimisation.+ *+ * # Black is mirrored+ *+ * The model only ever sees a position from the mover's side: when black is to move the board is+ * flipped vertically and the colours are swapped. That is also why the vocabulary has no black+ * promotions at all — every promotion is rank 7 to rank 8. [moveIndex] does the flip in one+ * place, for both squares of a move, so encoding and scoring cannot disagree about it.+ *+ * # The lock+ *+ * [MaiaHandle] is not thread-safe, so the mutex covers the whole of [bestMove] and the lazy+ * load inside it. Modelled on `NllbTranslator`, including [close] being non-suspending because+ * its only caller is `ViewModel.onCleared`.+ */+class MaiaEngine(private val context: Context) {++    private val lock = Mutex()+    private var model: MaiaHandle? = null+    private var attempts = 0+    private var closed = false+    private val random = Random.Default++    /**+     * Whether the AI can play at all, loading the model to find out.+     *+     * False when the device has no `libmodelrunner.so` for its ABI, or no Vulkan device with+     * fp16 compute. The caller hides the "play against the AI" option rather than offering a+     * mode that cannot move.+     */+    suspend fun isAvailable(): Boolean = withContext(Dispatchers.Default) {+        lock.withLock { ensure() != null }+    }++    /**+     * The move the AI plays for [turn] on [board], or null if it has none or the model failed.+     *+     * [turn] is the side to move and comes from the UI's own state, not from the board: the+     * rules model infers the turn from its last move, and the puzzle path seeds that with a+     * synthetic zero-length king move.+     *+     * Runs on [Dispatchers.Default] because a forward pass is synchronous and would otherwise+     * block whichever thread called it.+     */+    suspend fun bestMove(board: Board, turn: PieceColor, difficulty: Difficulty): Move? =+        withContext(Dispatchers.Default) {+            val legal = board.legalMoves(turn)+            if (legal.isEmpty()) return@withContext null+            lock.withLock {+                val handle = ensure() ?: return@withContext null+                val logits = try {+                    handle.logits(encodePlanes(board, turn), difficulty.elo, difficulty.elo)+                } catch (t: Throwable) {+                    Log.e(TAG, "inference failed", t)+                    null+                } ?: return@withContext null+                choose(legal, logits, turn, difficulty)+            }+        }++    /**+     * Free the model. Terminal: nothing loads again afterwards, and it is idempotent.+     *+     * Deliberately not `suspend`, because the only caller is `ViewModel.onCleared`, which is+     * not. It therefore does not take [lock], which is safe only because `viewModelScope` is+     * cancelled before `onCleared` runs and the UI cannot ask for another move afterwards.+     */+    fun close() {+        closed = true+        model?.close()+        model = null+    }++    /**+     * The loaded model, loading it on first use.+     *+     * Capped rather than latched on the first failure, for the same reason `NllbTranslator`+     * caps: a transient failure should not be permanent. There is no download here, so the cap+     * is low — a bundled asset that failed to open once will fail again.+     */+    private fun ensure(): MaiaHandle? {+        model?.let { return it }+        if (closed || attempts >= MAX_ATTEMPTS) return null+        attempts+++        val handle = MaiaHandle.inAssets(context.assets)+        if (!handle.isAvailable) {+            handle.close()+            return null+        }+        model = handle+        return handle+    }++    /**+     * Pick one of [legal] by nucleus sampling its logits at [Difficulty.temperature].+     *+     * The candidate set is the legal moves, scored by looking each one up in the vocabulary —+     * rather than taking the vector's argmax and decoding it, which would have to cope with the+     * ~4000 entries that are not moves in this position.+     */+    private fun choose(+        legal: List<Move>,+        logits: FloatArray,+        turn: PieceColor,+        difficulty: Difficulty,+    ): Move {+        val scored = legal.map { move ->+            move to (logits.getOrNull(moveIndex(move, turn)) ?: Float.NEGATIVE_INFINITY)+        }.sortedByDescending { it.second }++        val top = scored.first().second+        if (!top.isFinite()) return scored.first().first+        val temperature = difficulty.temperature.coerceAtLeast(MIN_TEMPERATURE)+        // Subtract the maximum before exponentiating, so a large logit cannot overflow.+        val weights = scored.map { exp(((it.second - top) / temperature).toDouble()) }+        val total = weights.sum()+        if (total <= 0.0 || !total.isFinite()) return scored.first().first++        // Nucleus: keep the shortest prefix of the sorted moves whose probability reaches topP,+        // so a blunder three orders of magnitude down cannot be sampled even at temperature.+        var mass = 0.0+        var keep = 0+        while (keep < weights.size) {+            mass += weights[keep] / total+            keep+++            if (mass >= difficulty.topP) break+        }++        var target = random.nextDouble() * mass * total+        for (index in 0 until keep) {+            target -= weights[index]+            if (target <= 0.0) return scored[index].first+        }+        return scored[keep - 1].first+    }++    companion object {+        private const val TAG = "MaiaEngine"++        /** One retry. A bundled asset that failed to open once will fail again. */+        private const val MAX_ATTEMPTS = 2++        /** A floor, so a zero temperature is argmax rather than a division by zero. */+        private const val MIN_TEMPERATURE = 1e-3f++        /**+         * The plane a piece type occupies, in `maia3/dataset.py`'s `PIECE_MAP` order.+         *+         * Planes 0..5 are the mover's pieces and 6..11 the opponent's, both in this order. Note+         * that it is **not** [PieceType]'s own declaration order, which starts at the king.+         */+        private val PLANE_ORDER = listOf(+            PieceType.PAWN,+            PieceType.KNIGHT,+            PieceType.BISHOP,+            PieceType.ROOK,+            PieceType.QUEEN,+            PieceType.KING,+        )++        /**+         * [board] as the 12 planes the model reads, from [turn]'s side.+         *+         * `12 * 64` floats, plane-major, square `rank * 8 + file` so a1 is 0 and h8 is 63. When+         * black is to move the board is mirrored vertically **and** the colours are swapped, so+         * the result is indistinguishable from the same position with white to move — which is+         * the whole of why one set of six "own piece" planes is enough.+         */+        fun encodePlanes(board: Board, turn: PieceColor): FloatArray {+            val planes = FloatArray(MaiaHandle.PLANE_COUNT * MaiaHandle.SQUARES)+            for (row in 0..7) {+                for (col in 0..7) {+                    val piece = board.pieces[row][col] ?: continue+                    val colour = if (turn == PieceColor.BLACK) piece.color.opposite else piece.color+                    val plane = PLANE_ORDER.indexOf(piece.type) ++                        if (colour == PieceColor.BLACK) 6 else 0+                    planes[plane * MaiaHandle.SQUARES + squareOf(Position(row, col), turn)] = 1f+                }+            }+            return planes+        }++        /**+         * Where [move] sits in the 4352-entry vocabulary, from [turn]'s side.+         *+         * `from * 64 + to` for an ordinary move; for a promotion,+         * `4096 + fromFile * 32 + toFile * 4 + piece` with the piece index from+         * [Board.PROMOTION_CHOICES]. Promotions carry no rank because they are always rank 7 to+         * rank 8 once the board is from the mover's side.+         */+        fun moveIndex(move: Move, turn: PieceColor): Int {+            val from = squareOf(move.start, turn)+            val to = squareOf(move.end, turn)+            val promotion = move.promotedTo ?: return from * MaiaHandle.SQUARES + to+            val piece = Board.PROMOTION_CHOICES.indexOf(promotion)+            return 4096 + (from % 8) * 32 + (to % 8) * 4 + piece+        }++        /**+         * [position] as a model square index, mirrored when black is to move.+         *+         * The rules model has row 0 at rank 8; the model numbers squares `rank * 8 + file` from+         * a1. Both conversions are here so nothing else has to know either convention.+         */+        private fun squareOf(position: Position, turn: PieceColor): Int {+            val rank = 7 - position.row+            val fromMoversSide = if (turn == PieceColor.BLACK) 7 - rank else rank+            return fromMoversSide * 8 + position.col+        }+    }+}
games/chess/src/main/java/com/vayunmathur/games/chess/util/StockfishEngine.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/StockfishEngine.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/StockfishEngine.ktdeleted file mode 100644index 5c49a2f417..0000000000--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/StockfishEngine.kt+++ /dev/null@@ -1,73 +0,0 @@-package com.vayunmathur.games.chess.util--import android.content.Context-import android.util.Log-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.channels.Channel-import kotlinx.coroutines.launch-import com.vayunmathur.games.chess.data.Board-import com.vayunmathur.stockfish.Stockfish--object StockfishEngine {-    val inputChannel = Channel<String>(Channel.UNLIMITED)-    val outputChannel = Channel<String>(Channel.UNLIMITED)-    private var engineStarted = false--    enum class Difficulty(val depth: Int, val skill: Int) {-        BEGINNER(8, 0),-        INTERMEDIATE(8, 5),-        ADVANCED(8, 12),-        GRANDMASTER(8, 20)-    }--    var difficulty: Difficulty = Difficulty.BEGINNER--    suspend fun nextMove(board: Board) {-        inputChannel.send("position fen ${board.toFen()}")-        inputChannel.send("setoption name Skill Level value ${difficulty.skill}")-        inputChannel.send("go depth ${difficulty.depth}")-    }--    fun start(context: Context) {-        if (engineStarted) return-        engineStarted = true--        Stockfish.init { line ->-            Log.d("StockfishEngine", "Stockfish output: $line")-            outputChannel.trySend(line)-        }--        val evalFileSpec = nnueEvalFileSpec(context, "nn-71d6d32cb962.nnue")--        CoroutineScope(Dispatchers.IO).launch {-            for (cmd in inputChannel) {-                Log.d("StockfishEngine", "Stockfish Input: $cmd")-                Stockfish.sendCommand(cmd)-            }-        }--        CoroutineScope(Dispatchers.IO).launch {-            inputChannel.send("uci")-            inputChannel.send("setoption name EvalFile value $evalFileSpec")-            inputChannel.send("isready")-        }-    }--    /**-     * Points Stockfish at the NNUE stored uncompressed inside the APK, read in-     * place via a file descriptor instead of being copied to internal storage.-     * Returns an "fd:<fd>:<offset>:<length>" spec understood by the engine's-     * EvalFile loader. The fd is detached (ownership handed to native, which-     * closes it after loading). Requires `noCompress += "nnue"` so the asset is-     * page-aligned and openable as a descriptor.-     */-    private fun nnueEvalFileSpec(context: Context, fileName: String): String {-        val afd = context.assets.openFd(fileName)-        val offset = afd.startOffset-        val length = afd.length-        val fd = afd.parcelFileDescriptor.detachFd()-        afd.close()-        return "fd:$fd:$offset:$length"-    }-}
games/chess/src/screenshotTest/kotlin/com/vayunmathur/games/chess/MetadataPreviews.kt
diff --git a/games/chess/src/screenshotTest/kotlin/com/vayunmathur/games/chess/MetadataPreviews.kt b/games/chess/src/screenshotTest/kotlin/com/vayunmathur/games/chess/MetadataPreviews.ktindex bbdd2c2a9d..2f1d6dac2c 100644--- a/games/chess/src/screenshotTest/kotlin/com/vayunmathur/games/chess/MetadataPreviews.kt+++ b/games/chess/src/screenshotTest/kotlin/com/vayunmathur/games/chess/MetadataPreviews.kt@@ -26,9 +26,15 @@ private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"  *  * Positions are reached by replaying real moves through [Board], which is a pure rules model  * — so the move list, the captured pieces and the check markers are all genuinely derived- * rather than faked. Crucially none of this reaches Stockfish: the engine is only ever driven+ * rather than faked. Crucially none of this reaches the model: the engine is only ever driven  * from [com.vayunmathur.games.chess.util.ChessViewModel], and these render with- * [ChessActions.Noop], so no native search is ever started.+ * [ChessActions.Noop], so no Vulkan device is ever brought up.+ *+ * `NewGameDialog` is the one exception worth naming, because it *is* rendered here: it reads+ * `Difficulty.entries`, which is a top-level enum with no native handle behind it, and takes+ * the availability flag as a parameter that defaults true. Neither reaches+ * [com.vayunmathur.games.chess.util.MaiaEngine], whose initialiser would try to load a `.so`+ * that a JVM screenshot run does not have.  */ class MetadataPreviews { 
games/chess/src/test/java/com/vayunmathur/games/chess/data/MaiaEncodingTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/data/MaiaEncodingTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/data/MaiaEncodingTest.ktnew file mode 100644index 0000000000..03cadc4f91--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/data/MaiaEncodingTest.kt@@ -0,0 +1,234 @@+package com.vayunmathur.games.chess.data++import com.vayunmathur.games.chess.util.MaiaEngine+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * The three encodings between the rules model and Maia3, each of which fails silently.+ *+ * A wrong square index, a wrong mirror or a wrong vocabulary entry all produce a legal move+ * that is simply not the one the model chose — the game keeps working and the AI just plays+ * badly. Nothing else in the app can catch that, so it is checked here against values derived+ * by hand.+ *+ * `scripts/ml/maia_parity.py` checks the same encodings against the real model on the real+ * weights. This is the half of it that runs without a 13 MB asset or a GPU.+ */+class MaiaEncodingTest {++    // file 'a'..'h', rank 1..8  ->  internal Position(row, col) where row 0 = rank 8, col 0 = file a+    private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++    private fun board(vararg placements: Pair<Position, Piece>): Board {+        val grid = MutableList(8) { MutableList<Piece?>(8) { null } }+        for ((pos, piece) in placements) grid[pos.row][pos.col] = piece+        return Board(grid.map { it.toList() })+    }++    /** The model's square index for a plane-major offset: plane `p`, square `s` at `p * 64 + s`. */+    private fun planeAt(planes: FloatArray, plane: Int, square: Int) = planes[plane * 64 + square]++    /** Which `(plane, square)` pairs are set, so a test can assert the whole encoding at once. */+    private fun occupied(planes: FloatArray): Set<Pair<Int, Int>> =+        planes.indices.filter { planes[it] != 0f }.map { it / 64 to it % 64 }.toSet()++    @Test+    fun planes_areIndexedFromA1_withWhitePiecesFirst() {+        // A white rook on a1 (square 0) and a black king on h8 (square 63). Planes are+        // P,N,B,R,Q,K for the mover then the same six for the opponent, so a rook is plane 3+        // and an opposing king plane 11.+        val b = board(+            sq('a', 1) to Piece(PieceType.ROOK, PieceColor.WHITE),+            sq('h', 8) to Piece(PieceType.KING, PieceColor.BLACK),+        )+        val planes = MaiaEngine.encodePlanes(b, PieceColor.WHITE)+        assertEquals(12 * 64, planes.size)+        assertEquals(setOf(3 to 0, 11 to 63), occupied(planes))+    }++    @Test+    fun planes_useTheDatasetPieceOrderAndNotPieceTypesOwn() {+        // `PieceType` is declared KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN; the model wants+        // P, N, B, R, Q, K. Taking the enum's own ordinal would reverse every plane, which is+        // a wrong-but-plausible encoding this pins down.+        val order = listOf(+            PieceType.PAWN, PieceType.KNIGHT, PieceType.BISHOP,+            PieceType.ROOK, PieceType.QUEEN, PieceType.KING,+        )+        order.forEachIndexed { plane, type ->+            val b = board(sq('a', 1) to Piece(type, PieceColor.WHITE))+            assertEquals(1f, planeAt(MaiaEngine.encodePlanes(b, PieceColor.WHITE), plane, 0), "$type")+        }+    }++    @Test+    fun planes_forBlackToMove_mirrorTheRankAndSwapTheColour() {+        // A black rook on a8 with black to move must encode exactly as a white rook on a1 with+        // white to move: the model only ever sees a position from the mover's side.+        val white = board(sq('a', 1) to Piece(PieceType.ROOK, PieceColor.WHITE))+        val black = board(sq('a', 8) to Piece(PieceType.ROOK, PieceColor.BLACK))+        assertTrue(+            MaiaEngine.encodePlanes(white, PieceColor.WHITE)+                .contentEquals(MaiaEngine.encodePlanes(black, PieceColor.BLACK))+        )+    }++    @Test+    fun planes_forBlackToMove_leaveTheFileAlone() {+        // The mirror is vertical only. A piece on b1 must not come back on g8: flipping the+        // file as well is the other plausible mirror, and it is wrong.+        val b = board(sq('b', 1) to Piece(PieceType.KNIGHT, PieceColor.BLACK))+        val planes = MaiaEngine.encodePlanes(b, PieceColor.BLACK)+        // b1 mirrors to b8, which is square 57, and the knight becomes the mover's (plane 1).+        assertEquals(setOf(1 to 57), occupied(planes))+    }++    @Test+    fun planes_ofTheOpeningPosition_areTwoSolidRanksPerSide() {+        val planes = MaiaEngine.encodePlanes(Board.initialState, PieceColor.WHITE)+        assertEquals(32, planes.count { it != 0f })+        // Eight white pawns on rank 2, squares 8..15.+        for (square in 8..15) assertEquals(1f, planeAt(planes, 0, square), "square $square")+        // The white king on e1 is square 4; the black king on e8 is 60, plane 11.+        assertEquals(1f, planeAt(planes, 5, 4))+        assertEquals(1f, planeAt(planes, 11, 60))+    }++    @Test+    fun planes_ofTheOpeningPosition_areTheSameFromEitherSide() {+        // The start is symmetric, so the mover's view of it does not depend on who moves.+        assertTrue(+            MaiaEngine.encodePlanes(Board.initialState, PieceColor.WHITE)+                .contentEquals(MaiaEngine.encodePlanes(Board.initialState, PieceColor.BLACK))+        )+    }++    @Test+    fun moveIndex_forAnOrdinaryMove_isFromTimes64PlusTo() {+        // e2e4: e2 is square 12, e4 is square 28.+        val pawn = Piece(PieceType.PAWN, PieceColor.WHITE)+        val move = Move(sq('e', 2), sq('e', 4), pawn)+        assertEquals(12 * 64 + 28, MaiaEngine.moveIndex(move, PieceColor.WHITE))+    }++    @Test+    fun moveIndex_forBlackToMove_mirrorsBothSquares() {+        // e7e5 played by black is e2e4 from the mover's side, so it must land on the same index.+        val pawn = Piece(PieceType.PAWN, PieceColor.BLACK)+        val move = Move(sq('e', 7), sq('e', 5), pawn)+        assertEquals(12 * 64 + 28, MaiaEngine.moveIndex(move, PieceColor.BLACK))+    }++    @Test+    fun moveIndex_forAPromotion_isFilesAndPieceWithNoRank() {+        // Promotions are always rank 7 to rank 8, so only the files and the piece are encoded:+        // 4096 + fromFile * 32 + toFile * 4 + piece, with piece in q, r, b, n.+        val pawn = Piece(PieceType.PAWN, PieceColor.WHITE)+        Board.PROMOTION_CHOICES.forEachIndexed { piece, type ->+            val move = Move(sq('c', 7), sq('d', 8), pawn, promotedTo = type)+            assertEquals(4096 + 2 * 32 + 3 * 4 + piece, MaiaEngine.moveIndex(move, PieceColor.WHITE))+        }+    }++    @Test+    fun moveIndex_forABlackPromotion_landsInTheSameRange() {+        // The vocabulary has no black promotions at all: c2c1 for black is c7c8 mirrored.+        val pawn = Piece(PieceType.PAWN, PieceColor.BLACK)+        val move = Move(sq('c', 2), sq('c', 1), pawn, promotedTo = PieceType.QUEEN)+        assertEquals(4096 + 2 * 32 + 2 * 4 + 0, MaiaEngine.moveIndex(move, PieceColor.BLACK))+    }++    @Test+    fun moveIndex_isDistinctAcrossTheWholeVocabulary() {+        // Every from-to pair and every promotion must land on its own entry, and all of them+        // must fall inside the 4352 the model emits. A collision would make two moves share a+        // logit, which no single-move test can see.+        val pawn = Piece(PieceType.PAWN, PieceColor.WHITE)+        val seen = mutableSetOf<Int>()+        for (from in 0 until 64) {+            for (to in 0 until 64) {+                val move = Move(position(from), position(to), pawn)+                val index = MaiaEngine.moveIndex(move, PieceColor.WHITE)+                assertTrue(seen.add(index), "duplicate index $index")+                assertTrue(index in 0 until 4096, "index $index outside the from-to range")+            }+        }+        for (fromFile in 0 until 8) {+            for (toFile in 0 until 8) {+                for (type in Board.PROMOTION_CHOICES) {+                    val move = Move(+                        position(48 + fromFile),+                        position(56 + toFile),+                        pawn,+                        promotedTo = type,+                    )+                    val index = MaiaEngine.moveIndex(move, PieceColor.WHITE)+                    assertTrue(seen.add(index), "duplicate promotion index $index")+                    assertTrue(index in 4096 until 4352, "index $index outside the promotion range")+                }+            }+        }+        assertEquals(4352, seen.size)+    }++    /** A model square index back to a [Position]: square `rank * 8 + file`, row 0 = rank 8. */+    private fun position(square: Int) = Position(7 - square / 8, square % 8)++    @Test+    fun legalMoves_ofTheOpeningPosition_areTheTwentyEveryoneKnows() {+        val moves = Board.initialState.legalMoves(PieceColor.WHITE)+        assertEquals(20, moves.size)+        assertNotNull(moves.find { it.start == sq('e', 2) && it.end == sq('e', 4) })+        assertNotNull(moves.find { it.start == sq('g', 1) && it.end == sq('f', 3) })+        // No promotions are available, so nothing carries one.+        assertTrue(moves.all { it.promotedTo == null })+    }++    @Test+    fun legalMoves_expandAPromotionIntoFour() {+        // A white pawn on c7 with the c8 square empty: c7c8 is one step but four moves.+        val b = board(+            sq('c', 7) to Piece(PieceType.PAWN, PieceColor.WHITE),+            sq('e', 1) to Piece(PieceType.KING, PieceColor.WHITE),+            sq('e', 8) to Piece(PieceType.KING, PieceColor.BLACK),+        )+        val promotions = b.legalMoves(PieceColor.WHITE).filter { it.start == sq('c', 7) }+        assertEquals(4, promotions.size)+        assertEquals(Board.PROMOTION_CHOICES.toSet(), promotions.mapNotNull { it.promotedTo }.toSet())+    }++    @Test+    fun legalMoves_andHasLegalMoves_agree() {+        // `hasLegalMoves` is `legalMoves` with an early exit, and mate/stalemate detection+        // rides on it — so the two must not be able to disagree.+        val mate = board(+            sq('a', 8) to Piece(PieceType.KING, PieceColor.BLACK),+            sq('b', 7) to Piece(PieceType.QUEEN, PieceColor.WHITE),+            sq('c', 6) to Piece(PieceType.KING, PieceColor.WHITE),+        )+        assertTrue(mate.legalMoves(PieceColor.BLACK).isEmpty())+        assertTrue(!mate.hasLegalMoves(PieceColor.BLACK))+        assertTrue(Board.initialState.legalMoves(PieceColor.WHITE).isNotEmpty())+        assertTrue(Board.initialState.hasLegalMoves(PieceColor.WHITE))+    }++    @Test+    fun legalMoves_perftToDepthThree() {+        // 20, 400 and 8902 are the standard perft counts from the starting position. They are+        // the check that the generator is the rules and not an approximation of them: a+        // missing castle, a missing en passant or a missing pin all move the depth-3 number.+        fun perft(board: Board, turn: PieceColor, depth: Int): Int {+            val moves = board.legalMoves(turn)+            if (depth == 1) return moves.size+            return moves.sumOf { move ->+                perft(board.movePiece(move.start, move.end, move.promotedTo), turn.opposite, depth - 1)+            }+        }+        assertEquals(20, perft(Board.initialState, PieceColor.WHITE, 1))+        assertEquals(400, perft(Board.initialState, PieceColor.WHITE, 2))+        assertEquals(8902, perft(Board.initialState, PieceColor.WHITE, 3))+    }+}
games/hub/src/screenshotTest/kotlin/com/vayunmathur/games/hub/ui/screens/MetadataPreviews.kt
diff --git a/games/hub/src/screenshotTest/kotlin/com/vayunmathur/games/hub/ui/screens/MetadataPreviews.kt b/games/hub/src/screenshotTest/kotlin/com/vayunmathur/games/hub/ui/screens/MetadataPreviews.ktindex 0caa445997..b519111ad6 100644--- a/games/hub/src/screenshotTest/kotlin/com/vayunmathur/games/hub/ui/screens/MetadataPreviews.kt+++ b/games/hub/src/screenshotTest/kotlin/com/vayunmathur/games/hub/ui/screens/MetadataPreviews.kt@@ -39,7 +39,7 @@ class MetadataPreviews {     private val now = System.currentTimeMillis()      private val games = listOf(-        HubGameEntity("chess", "com.vayunmathur.games.chess", "Chess", "Classic chess with puzzles and Stockfish", "1.0", registeredAt = now - 28 * DAY, lastSeenAt = now - HOUR, lastPlayedAt = now - HOUR, totalPlaytimeMs = 5 * HOUR + 23 * 60_000L, totalSessions = 42),+        HubGameEntity("chess", "com.vayunmathur.games.chess", "Chess", "Classic chess with puzzles and a human-like AI", "1.0", registeredAt = now - 28 * DAY, lastSeenAt = now - HOUR, lastPlayedAt = now - HOUR, totalPlaytimeMs = 5 * HOUR + 23 * 60_000L, totalSessions = 42),         HubGameEntity("alchemist", "com.vayunmathur.games.alchemist", "Alchemist", "Combine elements", registeredAt = now - 25 * DAY, lastSeenAt = now - 3 * HOUR, lastPlayedAt = now - 3 * HOUR, totalPlaytimeMs = 3 * HOUR, totalSessions = 28),         HubGameEntity("pipes", "com.vayunmathur.games.pipes", "Pipes", "Connect the pipes", registeredAt = now - 20 * DAY, lastSeenAt = now - 5 * HOUR, lastPlayedAt = now - 5 * HOUR, totalPlaytimeMs = 2 * HOUR + 45 * 60_000L, totalSessions = 35),         HubGameEntity("solitaire", "com.vayunmathur.games.solitaire", "Solitaire", "Classic Klondike", registeredAt = now - 18 * DAY, lastSeenAt = now - 8 * HOUR, lastPlayedAt = now - 8 * HOUR, totalPlaytimeMs = 4 * HOUR, totalSessions = 51),
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 935a5d6c45..f3a8210475 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -127,9 +127,6 @@ robolectric = "4.14.1" stripe = "21.12.0" appauth = "0.11.1" -# Own libraries (vayun-mathur, via JitPack)-stockfishLibrary = "1.1.0"- # AppStore – Play install via Aurora gplayapi = "3.6.4" @@ -302,9 +299,6 @@ robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectr stripe-android = { module = "com.stripe:stripe-android", version.ref = "stripe" } appauth = { group = "net.openid", name = "appauth", version.ref = "appauth" } -# Own libraries (vayun-mathur, via JitPack)-stockfish-library = { module = "com.github.vayun-mathur:Stockfish-Library", version.ref = "stockfishLibrary" }- # AppStore – Play install via Aurora auroraoss-gplayapi = { module = "com.auroraoss:gplayapi", version.ref = "gplayapi" } 
library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.ktnew file mode 100644index 0000000000..bd5582703b--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.kt@@ -0,0 +1,170 @@+package com.vayunmathur.library.ml++import android.content.res.AssetManager+import android.os.ParcelFileDescriptor+import android.util.Log++/**+ * On-device human-move prediction for chess: Maia3-5M on the Vulkan compute runtime.+ *+ * An encoder-only transformer over 64 square tokens — width 256, 8 blocks, 8 heads — at 5.23+ * million parameters. See `library/ml/src/main/rust/src/nets/maia.rs`.+ *+ * # It predicts, it does not search+ *+ * One forward pass per move and no tree at all, which is the point rather than a compromise.+ * Maia3 is trained on human games to predict what a player *of a given rating* would play, so+ * a weak setting blunders the way a beginner does. It replaces Stockfish at `Skill Level 0`,+ * which searched eight ply and then threw a move away in ways no human ever does.+ *+ * # Strength is an input+ *+ * [logits] takes `selfElo` and `oppoElo` in 0..5000 — clamped, not rejected — and they enter+ * the model as a blend of two learned embeddings. One weights file therefore covers every+ * difficulty; there is nothing to reload when the player changes it.+ *+ * # One bundled asset, 6.8 MiB+ *+ * `maia3-5m.maml` ships inside the APK, so this has an [inAssets] and no download. Every+ * convolution is int8, quantised per output channel from the fp32 checkpoint; the norms, the+ * biases and the two elo embeddings stay fp16 and are 1% of the parameters. It replaces an+ * 86 MB NNUE, so the APK is about 79 MB smaller.+ *+ * int8 rather than fp16 because it was measured: `scripts/ml/maia_quant_eval.py` puts move+ * agreement against fp32 at 99.0% to 99.5% across the four difficulties, and every+ * disagreement is a position where the top two legal moves are closer together than fp16+ * rounding alone would separate them. The same harness rejects int4 at 87% to 91%.+ *+ * An asset must be stored **uncompressed** for this to work at all: `AssetManager.openFd`+ * throws for a deflated entry. That is what `noCompress += "maml"` in+ * `games/chess/build.gradle.kts` is for.+ *+ * # The caller owns the chess+ *+ * [logits] returns the raw 4352-entry move vector. Legal masking, temperature and sampling all+ * need a legal move list, which this library has no idea how to produce — `MaiaEngine` in+ * `:games:chess` does all three, and also does the mirror-and-swap that [logits] requires for+ * black.+ *+ * # Availability+ *+ * Construction never throws. [isAvailable] is false when `libmodelrunner.so` is missing for+ * this ABI, when the asset is absent, compressed or malformed, or when the device cannot give+ * us a Vulkan device with fp16 compute — and then [logits] returns null. The chess app gates+ * its "play against the AI" option on it rather than offering a mode that cannot move.+ *+ * # Threading+ *+ * Not thread-safe. A caller must hold a lock across [logits] and [close].+ */+class MaiaHandle private constructor(private val source: String) : AutoCloseable {+    private var handle: Long = 0L++    /** True if the graph came up and is the file this runtime was built against. */+    val isAvailable: Boolean get() = handle != 0L++    /**+     * The [MOVES] move logits for a board, or null on failure.+     *+     * [planes] is `PLANE_COUNT * SQUARES` floats, plane-major, with square `rank * 8 + file`+     * so a1 is 0 and h8 is 63. The planes are white P, N, B, R, Q, K then black P, N, B, R, Q,+     * K.+     *+     * **The board must already be from the mover's side.** When black is to move the caller+     * mirrors it vertically and swaps the colours, and un-mirrors the move it picks. Passing+     * an unmirrored black position produces plausible nonsense rather than an error.+     *+     * Indices 0..4095 are `from * 64 + to`; 4096..4351 are+     * `4096 + fromFile * 32 + toFile * 4 + piece` for queen, rook, bishop, knight. Promotions+     * are always rank 7 to rank 8, because the board is mirrored for black.+     */+    fun logits(planes: FloatArray, selfElo: Int, oppoElo: Int): FloatArray? {+        if (handle == 0L) return null+        if (planes.size != PLANE_COUNT * SQUARES) return null+        return MlNative.maiaLogits(handle, planes, selfElo, oppoElo)+    }++    /** Free the network and close the weights file. Idempotent. */+    override fun close() {+        val live = handle+        handle = 0L+        if (live != 0L) MlNative.destroyMaia(live)+    }++    override fun toString(): String = "Maia3-5M from $source"++    companion object {+        private const val TAG = "MaiaHandle"++        /** Board squares, and so the model's sequence length. One token per square. */+        const val SQUARES = 64++        /** Board planes: six piece types for each colour. */+        const val PLANE_COUNT = 12++        /** Entries in the move vocabulary: 64x64 from-to pairs plus 8x8x4 promotions. */+        const val MOVES = 4352++        /** The highest rating the model interpolates to. Higher inputs clamp to it. */+        const val MAX_ELO = 5000++        /** The one graph. Native checks its graph id, so a wrong file fails at load. */+        const val GRAPH = "maia3-5m.maml"++        /**+         * The model from the APK's assets, which is the only place it lives.+         *+         * No `inDirectory` counterpart: at 6.8 MiB this is bundled, so there is no download+         * directory to look in.+         */+        fun inAssets(assets: AssetManager, path: String = GRAPH): MaiaHandle {+            val instance = MaiaHandle("the APK's $path")+            instance.handle = if (!MlNative.isAvailable) {+                0L+            } else {+                try {+                    create(assets, path)+                } catch (e: Throwable) {+                    Log.e(TAG, "cannot open $path", e)+                    0L+                }+            }+            return instance+        }++        /**+         * Open the asset and hand the descriptor over.+         *+         * `use` rather than a bare `close`, and it is load-bearing in both directions — the+         * same argument [ClipHandle]'s asset path makes. On the happy path the descriptor has+         * already been detached and `AssetFileDescriptor.close` only releases the wrapper; if+         * `detachFd` throws instead, the close is the real one, and a leaked descriptor onto+         * the APK would last the life of the process.+         *+         * The inner `finally` covers the remaining window: after the descriptor has been given+         * up but before native has adopted it.+         */+        private fun create(assets: AssetManager, path: String): Long =+            assets.openFd(path).use { afd ->+                val fd = afd.parcelFileDescriptor.detachFd()+                var handed = false+                try {+                    val handle = MlNative.createMaia(fd, afd.startOffset, afd.length)+                    handed = true+                    handle+                } finally {+                    if (!handed) closeFd(fd)+                }+            }++        /**+         * Close a bare descriptor.+         *+         * Adopting it into a [ParcelFileDescriptor] is the only way to reach `close(2)` from+         * Kotlin. Failures are swallowed because the caller is already on an error path.+         */+        private fun closeFd(fd: Int) {+            runCatching { ParcelFileDescriptor.adoptFd(fd).close() }+        }+    }+}
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 7ce552dc89..011edeae56 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -273,6 +273,59 @@ internal object MlNative {      */     external fun destroyTinyclip(handle: Long) +    /**+     * Bring up Maia3-5M from its one bundled `.maml`. Returns 0 on failure.+     *+     * One forward pass per move and no search, so unlike [createTinyclip] there is only ever+     * one plan and native never re-records.+     *+     * The plan arrives as a **file descriptor** because it is a bundled asset: [offset] and+     * [length] are the `AssetFileDescriptor`'s, since an asset is a *range of the APK* rather+     * than a file of its own. `AssetManager.openFd` throws for a deflated entry, which is what+     * `noCompress += "maml"` in `games/chess/build.gradle.kts` is for.+     *+     * Native keeps the descriptor open for the life of the handle, because the two elo+     * embeddings are blended on the host — the blend weight is an input, so it cannot be+     * folded into the upload.+     *+     * **The descriptor must be detached.** Native takes ownership and closes it, on the failure+     * paths as much as the successful one, so a caller must not close it itself.+     *+     * Freed by [destroyMaia], not [destroy], [destroyOcr] or [destroySupertonic].+     */+    external fun createMaia(fd: Int, offset: Long, length: Long): Long++    /**+     * The 4352 move logits for a board, or null on failure.+     *+     * [planes] is `12 * 64` floats, plane-major, with square `rank * 8 + file` so a1 is 0 and+     * h8 is 63. The planes are white P, N, B, R, Q, K then black P, N, B, R, Q, K.+     *+     * **The board must already be from the mover's side.** When black is to move the caller+     * mirrors it vertically and swaps the colours, and un-mirrors the move it picks. The model+     * was trained that way and the move vocabulary has no black promotions at all, so passing+     * an unmirrored black position produces legal-looking nonsense rather than an error.+     *+     * [selfElo] and [oppoElo] are 0..5000 and are clamped, not rejected. They are what makes+     * one weights file cover every difficulty.+     *+     * The logits are **raw**: indices 0..4095 are `from * 64 + to` and 4096..4351 are+     * `4096 + fromFile * 32 + toFile * 4 + piece` for q, r, b, n. Legal masking, temperature+     * and sampling all need the caller's move list and stay in Kotlin.+     */+    external fun maiaLogits(+        handle: Long,+        planes: FloatArray,+        selfElo: Int,+        oppoElo: Int,+    ): FloatArray?++    /**+     * Free Maia3's network and its open weights file.+     * Exactly once per non-zero handle from [createMaia].+     */+    external fun destroyMaia(handle: Long)+     /**      * Bring up whisper-base from its one `.maml` and the ids read from `generation_config.json`.      * Returns 0 on failure.
library/ml/src/main/rust/shaders/attn_apply_cached.comp
diff --git a/library/ml/src/main/rust/shaders/attn_apply_cached.comp b/library/ml/src/main/rust/shaders/attn_apply_cached.compindex 224009f19e..d1608848ad 100644--- a/library/ml/src/main/rust/shaders/attn_apply_cached.comp+++ b/library/ml/src/main/rust/shaders/attn_apply_cached.comp@@ -31,8 +31,13 @@ //! //! # Push fields //!-//! `p.in0` is `S` at `[heads, 1, keys]`, `p.in1` the cache, `p.in_c` and `p.out_c` are `d_model`,-//! `p.in_w` the key count and `p.group` the head count. No new field.+//! `p.in0` is `S` at `[heads, 1, key_stride]`, `p.in1` the cache, `p.in_c` and `p.out_c` are+//! `d_model`, `p.in_w` the key stride and `p.group` the head count.+//!+//! When `p.dyn_keys` is set, `p.in_w` remains the distance between rows of `S` — the maximum the+//! plan was built for — while the number of keys summed over is `step_params.prefix + 1`. The two+//! must not be conflated: using the attended count as the row stride would read head `h`'s row+//! from the wrong offset the moment the step is shorter than the maximum.  #include "common.glsl" @@ -43,10 +48,11 @@ void main() {     }     // The output is `[d_model, 1, 1]`, so the index *is* the channel.     uint channel = index;-    uint keys = p.in_w;+    uint stride = p.in_w;+    uint keys = attended_keys(stride);     uint head_dim = p.out_c / p.group;     // `S[head][*]`, contiguous in the key index because there is one query.-    uint row = p.in0 + (channel / head_dim) * keys;+    uint row = p.in0 + (channel / head_dim) * stride;      float total = 0.0;     for (uint j = 0u; j < keys; j++) {
library/ml/src/main/rust/shaders/attn_scores_cached.comp
diff --git a/library/ml/src/main/rust/shaders/attn_scores_cached.comp b/library/ml/src/main/rust/shaders/attn_scores_cached.compindex a0a29002f9..76cd68f564 100644--- a/library/ml/src/main/rust/shaders/attn_scores_cached.comp+++ b/library/ml/src/main/rust/shaders/attn_scores_cached.comp@@ -35,8 +35,13 @@ //! //! `p.in0` is Q at `[d_model, 1, 1]`, so channel `c` is simply element `c`. `p.in1` is the cache. //! `p.in_c` is `d_model` and doubles as the cache's per-position stride, `p.group` is the head-//! count, `p.out_w` is the key count and `p.param0_bits` is `1 / sqrt(head_dim)` as raw f32 bits —-//! all fields that already exist, so the 26-slot push block does not grow.+//! count, `p.out_w` is the key stride and `p.param0_bits` is `1 / sqrt(head_dim)` as raw f32 bits.+//!+//! When `p.dyn_keys` is set the plan was built once at a maximum length and the step supplies the+//! real one, so `p.out_w` is the *stride* between rows of the score map while the attended count+//! is `step_params.prefix + 1`. Entries past that are left untouched rather than written with a+//! sentinel: `softmax_prefix.comp` reads only the attended span, so what is beyond it never+//! reaches the result.  #include "common.glsl" @@ -45,9 +50,14 @@ void main() {     if (index >= p.count) {         return;     }-    // The output is `[heads, 1, keys]`, so `unpack` gives head and key directly.+    // The output is `[heads, 1, key_stride]`, so `unpack` gives head and key directly.     uint head, unused_row, key;     unpack(index, head, unused_row, key);+    // Past the keys this step actually attends over. Only possible when the plan is built at a+    // maximum, in which case the dispatch covers the whole stride.+    if (key >= attended_keys(p.out_w)) {+        return;+    }     uint head_dim = p.in_c / p.group;     // Q is one position, so its channels are consecutive from `p.in0`.     uint query = p.in0 + head * head_dim;
library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex e014a55774..3b13fa26ad 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -55,6 +55,22 @@ layout(std430, binding = 2) readonly buffer Weights32 {     uint weights32[]; }; +// Values that change per step without the command buffer being re-recorded.+//+// Push constants below are baked into the recording, so anything that varies between two submits+// of the *same* recording has to be read from memory. A decode step's key count is the case that+// matters: it grows by one every token, and re-recording for it cost a `device_wait_idle` and a+// full re-emit per token.+//+// Mirrors `StepParams` in `src/vulkan/run.rs` field for field. `std430` packs a struct of `uint`s+// with no padding, so neither side has to restate an alignment rule.+layout(std430, binding = 3) readonly buffer Params {+    // Cache positions already written; a cached-attention op attends over `prefix + 1` keys.+    uint prefix;+    // First position a sliding window may attend to. Zero attends from the start.+    uint window_start;+} step_params;+ layout(push_constant) uniform Push {     uint in0;     uint in1;@@ -82,8 +98,20 @@ layout(push_constant) uniform Push {     uint param0_bits;     uint param1_bits;     uint count;+    // Non-zero when the key count comes from `step_params.prefix + 1` rather than from+    // `in_w`/`out_w`, which then carry only the stride. See `Push::dyn_keys` in `nets/mod.rs`.+    uint dyn_keys; } p; +// Keys a cached-attention op attends over, and the stride between rows of its score map.+//+// The two are equal for a plan built at a fixed length, and differ once the plan is built once at+// a maximum and the step supplies the length. Kept here so the three cached shaders cannot+// disagree about which of `p.in_w` / `p.out_w` is which.+uint attended_keys(uint stride) {+    return p.dyn_keys != 0u ? step_params.prefix + 1u : stride;+}+ // `nets::Act`. #define ACT_NONE 0u #define ACT_RELU 1u
library/ml/src/main/rust/shaders/rmsnorm.comp
diff --git a/library/ml/src/main/rust/shaders/rmsnorm.comp b/library/ml/src/main/rust/shaders/rmsnorm.compnew file mode 100644index 0000000000..fd6719b399--- /dev/null+++ b/library/ml/src/main/rust/shaders/rmsnorm.comp@@ -0,0 +1,50 @@+#version 450+//! Root-mean-square normalisation over the **channel** axis, with a per-channel gain.+//!+//! Sixteen uses, all in Maia3's eight post-norm encoder blocks (`norm1` and `norm2`).+//!+//! # The difference from `layernorm.comp`+//!+//! Two lines, both subtractions that are not there: the mean is never computed and never+//! removed, and there is no beta. `x / sqrt(mean(x^2) + eps) * gamma` against layer norm's+//! `(x - mean) / sqrt(var + eps) * gamma + beta`. That also means one pass over the input+//! instead of two, because the sum of squares does not depend on a previously computed mean.+//!+//! `Kind::RmsNorm` reads a single rank-1 tensor, so unlike `Kind::LayerNorm` the `bias`+//! field of the push block is unused. `torch.nn.RMSNorm` with the default+//! `elementwise_affine=True` stores exactly this one `weight`, which is why the Maia3+//! checkpoint has `norm1.weight` with no matching `norm1.bias`.+//!+//! # Layout+//!+//! Identical to layer norm's: the sequence is `[d_model, 1, T]`, one invocation per+//! position, and the reduction strides by `in_h * in_w`. See `nets::Kind::LayerNorm` for+//! why the layout is that way round.++#include "common.glsl"++void main() {+    uint position = global_index();+    if (position >= p.count) {+        return;+    }+    // `count` is `in_h * in_w`, so `position` walks the spatial extent and the channel+    // stride is that same extent.+    uint stride = p.in_h * p.in_w;+    float epsilon = uintBitsToFloat(p.param1_bits);++    float squares = 0.0;+    for (uint c = 0u; c < p.in_c; c++) {+        float value = float(arena[p.in0 + c * stride + position]);+        squares += value * value;+    }+    // Epsilon is inside the square root, matching `torch.nn.RMSNorm`.+    float inverse = 1.0 / sqrt(squares / float(p.in_c) + epsilon);++    for (uint c = 0u; c < p.in_c; c++) {+        uint at = c * stride + position;+        float value = float(arena[p.in0 + at]);+        float gamma = float(weights[p.weight + c]);+        arena[p.out_at + at] = float16_t(value * inverse * gamma);+    }+}
library/ml/src/main/rust/shaders/softmax_prefix.comp
diff --git a/library/ml/src/main/rust/shaders/softmax_prefix.comp b/library/ml/src/main/rust/shaders/softmax_prefix.compnew file mode 100644index 0000000000..5141c21fb4--- /dev/null+++ b/library/ml/src/main/rust/shaders/softmax_prefix.comp@@ -0,0 +1,53 @@+#version 450+//! Softmax over the first `step_params.prefix + 1` entries of each row, not the whole row.+//!+//! # Why not a flag in `softmax.comp`+//!+//! `softmax.comp` is shared by PP-OCRv5 recognition, both Supertonic encoders, whisper, maia and+//! NLLB's encoder. It is the one shader a decode change most wants to touch and least should: a+//! branch added there is a branch every one of those nets executes on every row, and a mistake in+//! it is a mistake in all of them at once. This is a separate pipeline, reached only by+//! `Kind::SoftmaxPrefix`, so nothing that does not decode can be affected by it.+//!+//! # Row length versus row stride+//!+//! The plan is built once at a maximum context, so a score map row is `p.out_w` elements wide but+//! only the leading `step_params.prefix + 1` of them were written by+//! `attn_scores_cached.comp` this step. The rest are stale values from earlier steps — not zeros,+//! not `-inf`. Reading them would put finite garbage into both the maximum and the sum, so every+//! one of the three passes stops at the attended count while the row *offset* keeps using the+//! full stride.+//!+//! The output is written over the same leading span. Entries past it keep whatever they held,+//! which is safe precisely because `attn_apply_cached.comp` sums over the same bound.++#include "common.glsl"++void main() {+    uint row = global_index();+    if (row >= p.count) {+        return;+    }+    uint stride = p.out_w;+    uint keys = attended_keys(stride);+    uint at = p.in0 + row * stride;++    // The most negative fp16 rather than -inf, matching `softmax.comp`: a decode step always+    // attends over at least its own position, so the row is never empty and the seed is never+    // the answer.+    float peak = -65504.0;+    for (uint i = 0u; i < keys; i++) {+        peak = max(peak, float(arena[at + i]));+    }++    float total = 0.0;+    for (uint i = 0u; i < keys; i++) {+        total += exp(float(arena[at + i]) - peak);+    }+    float inverse = 1.0 / total;++    uint out_row = p.out_at + row * stride;+    for (uint i = 0u; i < keys; i++) {+        arena[out_row + i] = float16_t(exp(float(arena[at + i]) - peak) * inverse);+    }+}
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 6fd5f5096a..e783ace068 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -34,7 +34,7 @@ use jni::sys::{jfloatArray, jint, jintArray, jlong, jstring}; use jni::JNIEnv;  use crate::nets::{-    mobilefacenet, nllb, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration,+    maia, mobilefacenet, nllb, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration,     supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, whisper, Plan, }; use crate::post::ctc::Dictionary;@@ -1661,6 +1661,152 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyTi     drop(unsafe { Box::from_raw(handle as *mut TinyclipHandle) }); } +/// Maia3-5M, as `:games:chess` holds it. Handed to Kotlin as an opaque `jlong`.+///+/// # One net, one plan+///+/// A plain [`Net`] rather than a [`Reshaped`]: the board is always 64 squares, so unlike+/// TinyCLIP's two towers or Whisper's growing decode there is nothing to re-record. One+/// forward pass per move, no search, no cache.+///+/// # The weights file stays open+///+/// [`maia::elo_embedding`] blends the two 128-vectors on the host — the blend weight is an+/// input, so it cannot be folded — so the [`Streamed`] is retained the way TinyCLIP's is+/// for its token table.+struct MaiaHandle {+    net: Net,+    weights: Streamed,+}++/// Bring up Maia3 from its one bundled `.maml`. Returns 0 on failure.+///+/// The descriptor is an `AssetFileDescriptor`'s, so it carries an offset and a length: the+/// file is a *range of the APK* rather than a file of its own, which is also why the asset+/// has to be stored uncompressed.+///+/// # Safety+///+/// Called only by the JVM, with a descriptor nothing else holds.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMaia<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    fd: jint,+    offset: jlong,+    length: jlong,+) -> jlong {+    if fd < 0 {+        log(&format!("maia is unavailable: descriptor {fd} is not open"));+        return 0;+    }+    // SAFETY: the caller detached the descriptor, so nothing else owns it, and `File` closes+    // it on drop — including on every failure path below.+    let file = unsafe { File::from_raw_fd(fd) };+    match build_maia(file, offset, length) {+        Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+        Err(e) => {+            log(&format!("maia is unavailable: {e}"));+            0+        }+    }+}++fn build_maia(file: File, offset: jlong, length: jlong) -> Result<MaiaHandle, String> {+    let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {+        (Ok(at), Ok(len)) => (at, len),+        _ => return Err(format!("the graph spans {offset}+{length}")),+    };+    let weights = Streamed::open(file, at, len, graph::MAIA)?;+    if weights.len() != maia::TENSORS {+        return Err(format!("a file of {} tensors, not {}", weights.len(), maia::TENSORS));+    }+    let plan = maia::build(&weights.offsets())?;+    let net = Net::new(context::shared()?, plan, &weights, RESCALE_ONLY)?;+    Ok(MaiaHandle { net, weights })+}++/// The 4352 move logits for a board, or null on failure.+///+/// `planes` is the 12 board planes as `12 * 64` floats, plane-major, square `rank * 8 + file`+/// — **already mirrored and colour-swapped if black is to move**, because the model only ever+/// sees the position from the mover's side and the move vocabulary has no black promotions+/// at all. `:games:chess` does that in `MaiaEngine`, next to the code that un-mirrors the+/// move it picks.+///+/// The logits are raw. Legal masking, temperature and sampling all need the caller's move+/// list, so they stay in Kotlin.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createMaia` that has not been destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maiaLogits<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    planes: JFloatArray<'l>,+    self_elo: jint,+    oppo_elo: jint,+) -> jfloatArray {+    let null = std::ptr::null_mut();+    if handle == 0 {+        return null;+    }+    // SAFETY: the caller guarantees the handle came from `createMaia` and is still live.+    // `&mut` because inference writes the net's staging buffer; Kotlin serialises calls.+    let handle = unsafe { &mut *(handle as *mut MaiaHandle) };+    let logits = match read_float_array(&mut env, &planes) {+        Ok(values) => run_maia(handle, &values, self_elo, oppo_elo),+        Err(e) => Err(e),+    };+    match logits.and_then(|values| new_float_array(&mut env, &values)) {+        Ok(array) => array,+        Err(e) => {+            log(&format!("maia failed: {e}"));+            null+        }+    }+}++fn run_maia(+    handle: &mut MaiaHandle,+    planes: &[f32],+    self_elo: jint,+    oppo_elo: jint,+) -> Result<Vec<f32>, String> {+    let self_vector = maia::elo_embedding(handle.weights.reader(), self_elo as f32)?;+    let oppo_vector = maia::elo_embedding(handle.weights.reader(), oppo_elo as f32)?;+    let tokens = maia::tokens(planes, &self_vector, &oppo_vector)?;+    let outputs = handle.net.infer_raw_many(&[&tokens])?;+    let [scores, promo] = outputs.as_slice() else {+        return Err(format!("{} outputs, expected two", outputs.len()));+    };+    crate::post::maia::logits(scores, promo)+}++/// Free Maia3's net and close its weights file.+///+/// Exactly once per non-zero handle from `createMaia`. When it is the last user of the shared+/// `VkDevice`, the device goes away with it.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createMaia`, and must not be used again.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyMaia<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+) {+    if handle == 0 {+        return;+    }+    // SAFETY: the caller guarantees this handle came from `createMaia` and has not been+    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.+    drop(unsafe { Box::from_raw(handle as *mut MaiaHandle) });+}+ /// whisper-base, as `:speech` holds it. Handed to Kotlin as an opaque `jlong`. /// /// # One net, two plans, and two kinds of cache
library/ml/src/main/rust/src/nets/maia.rs
diff --git a/library/ml/src/main/rust/src/nets/maia.rs b/library/ml/src/main/rust/src/nets/maia.rsnew file mode 100644index 0000000000..c6d103daf5--- /dev/null+++ b/library/ml/src/main/rust/src/nets/maia.rs@@ -0,0 +1,615 @@+//! Maia3-5M: a human-move predictor for `:games:chess`, one forward pass per move.+//!+//! # What it is+//!+//! An encoder-only transformer over 64 tokens, one per square — the "Chessformer" of+//! <https://github.com/CSSLab/maia3>. Width 256, 8 blocks, 8 heads of 32, a 512-wide+//! feed-forward. 5,230,084 parameters, 6.8 MiB as int8 once the shared attention-bias kernel+//! is replicated (see below).+//!+//! It replaces Stockfish, which searched to depth 8 behind an 86 MB NNUE. This searches+//! nothing at all: the board goes in, 4352 move logits come out, and the app masks them to+//! its own legal move list and samples. That is the point of the model — it is trained to+//! predict what a *human of a given rating* plays, so a weak setting blunders the way a+//! beginner does rather than the way a crippled search does.+//!+//! # Strength is an input, not a handicap+//!+//! `SelfElo` and `OppoElo` are 0..5000 and enter as a linear blend of two learned+//! 128-vectors, concatenated onto every square's token. One weights file therefore covers+//! every difficulty; see [`elo_embedding`], and note its inverted naming.+//!+//! # The history is the current position, eight times+//!+//! The model takes 8 plies of history as 96 planes. The shipped `maia3-5m` launcher runs+//! with `use_uci_history=False`, and in that mode upstream seeds its deque with the current+//! position alone and pads by repeating it — so the 96 planes are the current position+//! eight times over. [`tokens`] builds exactly that, which is what makes parity against the+//! preset meaningful and means the app needs no move history.+//!+//! Real 8-ply history is deliberately not implemented: in `use_uci_history` mode each+//! historical position is mirrored by *its own* side to move, so the perspective alternates+//! every ply, and that is easy to get quietly wrong for no gain over what ships.+//!+//! # Post-norm, and RMSNorm inside the block+//!+//! Two things differ from [`super::tinyclip`] and copying that file by reflex gets both+//! wrong. The blocks are **post-norm** — `x = norm(x + sublayer(x))`, not+//! `x = x + sublayer(norm(x))` — and the in-block norm is [`Builder::rms_norm`], which has+//! no mean subtraction and no beta. The two norms outside the stack are ordinary layer+//! norms. Neither mistake changes a single shape.+//!+//! # The attention bias, and why its kernel is replicated eight times+//!+//! Every block generates its own additive `[8, 64, 64]` bias from the board — upstream+//! calls it GAB, and the checkpoint calls it smolgen. The generator pools the squares to+//! `[256]`, runs it through two projections to `[512]`, reads that as `[8, 64]`, and+//! expands it with `einsum("bhi,oi->bho")` against a `[4096, 64]` weight **shared by all+//! eight blocks**.+//!+//! There is no transpose or permute op in this runtime — the layout inventory is+//! `reshaped` / `slice_channels` / `concat` / `concat_positions`, all relabels or copies —+//! so that einsum is expressed as a **grouped 1x1 convolution**: `group = 8`, 512 in,+//! 32768 out, kernel `[32768, 64, 1, 1]`. Group `g` reads input channels+//! `[g*64, (g+1)*64)` and writes `[g*4096, (g+1)*4096)`, which is the einsum with the+//! output already in `[8, 64, 64]` order.+//!+//! The cost is that the converter replicates the `[4096, 64]` weight eight times, +1.84M+//! elements. It is replicated **once, not per block**: the parameter is shared, so all eight+//! blocks pass [`SMOLGEN`] as their `weight_index`. Avoiding the replication would need a new+//! transpose shader, and the memory is the cheaper trade — more so at int8, where the+//! replicated kernel costs 2.1 MB rather than the 4.2 MB it would at fp16.+//!+//! # int8, and why not int4+//!+//! Every `1 x 1` convolution is [`Builder::conv_int8`], quantised per output channel from the+//! fp32 checkpoint. The norms, the biases and the two elo embeddings stay fp16 and together+//! are 1% of the parameters. 13.3 MiB to 6.8 MiB.+//!+//! Measured rather than assumed, by `scripts/ml/maia_quant_eval.py`. The worst per-tensor+//! correlation against fp32 is 0.999941, and over 400 positions at each of the four shipping+//! ratings the quantised model picks a different move 0.5% to 1.0% of the time — always where+//! the top two legal moves are within 0.017 of each other, which is inside the deviation fp16+//! rounding produces on its own.+//!+//! **int4 was measured and rejected.** At 4 bits the same harness agrees on 87% to 91% of+//! moves depending on the group size, and 14 to 29 of the disagreements are on margins wider+//! than fp16 rounding — the model changes its mind rather than losing a coin flip. Sub-row+//! grouping does not rescue it and gives back most of the saving (per-16 is 4.2 MiB against+//! per-channel's 3.5). 5.2M parameters have no redundancy to spare, unlike the large models+//! int4 is usually quoted for.+//!+//! The attention-bias kernel is 30% of the file and is read by every block, so int8 halves+//! this net's weight traffic as well as its size — the part that matters if a move ever feels+//! slow.+//!+//! # The bias is added after the scale+//!+//! [`Builder::attn_scores`] applies `1 / sqrt(head_dim)` itself, and the bias is added to+//! the result. That matches `F.multi_head_attention_forward`, which scales `q` before+//! adding `attn_mask` — so the bias is *not* scaled. Adding it first would divide it by+//! `sqrt(32)`.+//!+//! # What is not emitted+//!+//! The value (win/draw/loss) and ponder heads, and the `last_ln` in front of them. Neither+//! is needed to pick a move, the collector controls the tensor list, so they are simply not+//! in the file. An evaluation bar would want them back.+//!+//! # Move vocabulary+//!+//! [`build`] emits two tensors and `post::maia` assembles the 4352 logits from them:+//!+//! * `0..4095` — `from_square * 64 + to_square`, square `rank * 8 + file`, a1 = 0, h8 = 63+//! * `4096..4351` — `4096 + from_file * 32 + to_file * 4 + piece`, piece in q, r, b, n+//!+//! Promotions are always rank 7 to rank 8 because the board is mirrored for black.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};+use crate::weights::Reader;++/// Channels through the stack: `dim_vit`.+pub const WIDTH: u32 = 256;++/// Attention heads, so `head_dim` is 32 and [`Builder::attn_scores`]'s scale is the model's.+pub const HEADS: u32 = 8;++/// The feed-forward width: `dim_vit * mlp_ratio`, 256 * 2.0.+pub const FFN: u32 = 512;++/// Encoder blocks, `num_blocks`.+pub const BLOCKS: usize = 8;++/// Tokens, one per square of the board. The whole sequence length; there is no class token.+pub const SQUARES: u32 = 64;++/// Board planes per ply: six piece types for each colour.+pub const PLANES: u32 = 12;++/// Plies of history the token projection expects, `history`.+pub const HISTORY: u32 = 8;++/// Each elo embedding's width, `dim_emb`.+pub const ELO_DIM: u32 = 128;++/// The token projection's input width: `12 * history` planes, then both elo embeddings.+pub const INPUT: u32 = PLANES * HISTORY + 2 * ELO_DIM;++/// The highest elo the model interpolates between its two embeddings. See [`elo_embedding`].+pub const ELO_MAX: f32 = 5000.0;++/// The attention bias generator's intermediate width, `gab_intermediate_dim`.+const BIAS_HIDDEN: u32 = 64;++/// Values the bias generator produces per head, `gab_gen_size`.+const BIAS_GEN: u32 = 64;++/// The bias generator's expanded output: one `[64, 64]` map per head.+const BIAS_OUT: u32 = HEADS * SQUARES * SQUARES;++/// The policy head's width, `head_hid_dim`. Equal to [`WIDTH`], which is why+/// `attn_scores(from, to, 1)`'s own `1 / sqrt(head_dim)` is the model's `1 / sqrt(256)`.+pub const HEAD_HIDDEN: u32 = 256;++/// Promotion pieces the head scores, in the vocabulary's order: queen, rook, bishop, knight.+pub const PROMOTIONS: u32 = 4;++/// Logits [`crate::post::maia`] assembles: 64x64 from-to pairs plus 8x8x4 promotions.+pub const MOVES: usize = (SQUARES * SQUARES) as usize + (8 * 8 * PROMOTIONS) as usize;++/// The epsilon in every `nn.LayerNorm`, which is torch's default.+const EPSILON: f32 = 1e-5;++/// The epsilon in every `torch.nn.RMSNorm`.+///+/// Upstream constructs them as `RMSNorm(d_model)` with no `eps`, and torch resolves that to+/// `torch.finfo(x.dtype).eps` at fp32 rather than to a layer norm's 1e-5.+const RMS_EPSILON: f32 = 1.192_092_9e-7;++/// `elo_embedding_low.weight`, `[1, ELO_DIM]`. Read by the host, not by a shader.+const ELO_LOW: usize = 0;++/// `elo_embedding_high.weight`, `[1, ELO_DIM]`.+const ELO_HIGH: usize = ELO_LOW + 1;++/// `token_projection`: int8 kernel `[WIDTH, INPUT, 1, 1]`, per-channel scale, bias.+const TOKEN_PROJECTION: usize = ELO_HIGH + 1;++/// The attention bias kernel, replicated to `[BIAS_OUT, BIAS_GEN, 1, 1]`, its scale, and a+/// synthesised zero bias.+///+/// One tensor for all eight blocks: they share the parameter, so they share the index. See+/// the module docs for why it is a grouped convolution.+const SMOLGEN: usize = TOKEN_PROJECTION + 3;++/// The first encoder block.+const BLOCK: usize = SMOLGEN + 3;++/// Tensors per encoder block, in the order [`encoder_block`] takes them.+///+/// Eight projections of three — the bias generator's two, q, k, v, the output projection and+/// the two feed-forward — two layer norms of two, and the two RMS norms of one.+const BLOCK_TENSORS: usize = 8 * 3 + 2 * 2 + 2 * 1;++/// `transformer.norm`, the layer norm closing the stack.+const FINAL_NORM: usize = BLOCK + BLOCKS * BLOCK_TENSORS;++/// `proj_sq_from`: int8 kernel `[HEAD_HIDDEN, WIDTH, 1, 1]`, scale, synthesised zero bias.+const SQ_FROM: usize = FINAL_NORM + 2;++/// `proj_sq_to`.+const SQ_TO: usize = SQ_FROM + 3;++/// `promo_bias_proj`: int8 kernel `[PROMOTIONS, HEAD_HIDDEN, 1, 1]`, scale, zero bias.+const PROMO: usize = SQ_TO + 3;++/// Tensors the `.maml` must hold, and the count `maml_convert.py` writes.+pub const TENSORS: usize = PROMO + 3;++/// Convolutions read as int8, each carrying a third tensor for its per-channel scale.+///+/// The token projection, the attention bias kernel, eight projections in each of the eight+/// blocks, and the three policy heads. Only the norms, the biases and the two elo embeddings+/// stay fp16, and together they are 1% of the parameters.+///+/// This counts **kernels in the file**, not dispatches: the bias kernel is one tensor that all+/// eight blocks read, so the plan runs seven more int8 convolutions than there are here.+pub const INT8_CONVS: usize = 2 + BLOCKS * 8 + 3;++/// Hands out `.maml` tensor indices in the order the layers appear.+struct Layers {+    next: usize,+}++impl Layers {+    /// A weight and the bias after it, or a layer norm's gamma and beta.+    fn take(&mut self) -> usize {+        let index = self.next;+        self.next += 2;+        index+    }++    /// An int8 kernel, its per-output-channel scale, and the bias after that.+    fn take3(&mut self) -> usize {+        let index = self.next;+        self.next += 3;+        index+    }++    /// A lone tensor: an RMS norm's gain, which has no beta to follow it.+    fn take1(&mut self) -> usize {+        let index = self.next;+        self.next += 1;+        index+    }+}++/// A `1 x 1` convolution with an int8 kernel, which every linear projection here is.+fn point(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id {+    b.conv_int8(x, l.take3(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act)+}++/// The additive `[HEADS, SQUARES, SQUARES]` attention bias this block generates from `x`.+///+/// `mean(squares) -> sm2 -> gelu -> ln1 -> sm3 -> gelu -> ln2 -> einsum`. Note that each+/// GELU is applied *before* its norm, not after: upstream writes `y = ln1(sm_act(sm2(y)))`.+fn attention_bias(b: &mut Builder, l: &mut Layers, x: Id) -> Id {+    // `[WIDTH, 1, SQUARES]` averaged over the width is upstream's `torch.mean(x, dim=1)`.+    let pooled = b.global_avg_pool(x);+    let y = point(b, l, pooled, BIAS_HIDDEN, Act::Gelu);+    let y = b.layer_norm(y, l.take(), EPSILON);+    let y = point(b, l, y, HEADS * BIAS_GEN, Act::Gelu);+    let y = b.layer_norm(y, l.take(), EPSILON);+    // The grouped expansion. `group = HEADS`, so head `h` reads only its own `BIAS_GEN`+    // values — which is what the einsum's `bhi` index does. Grouped, so it lowers to the+    // untiled `Kind::ConvInt8` rather than the pointwise one; that is the same shader the+    // fp16 version would have used, since a grouped 1x1 has no pointwise fast path either.+    let expanded = b.conv_int8(+        y,+        SMOLGEN,+        BIAS_OUT,+        (1, 1),+        (1, 1),+        (1, 1),+        (0, 0, 0, 0),+        HEADS,+        Act::None,+    );+    b.reshaped(expanded, Shape::new(HEADS, SQUARES, SQUARES))+}++/// One `EncoderOnlyBlock`: **post-norm** self-attention with a residual, then post-norm+/// feed-forward with another.+fn encoder_block(b: &mut Builder, l: &mut Layers, x: Id) -> Id {+    let bias = attention_bias(b, l, x);++    let q = point(b, l, x, WIDTH, Act::None);+    let k = point(b, l, x, WIDTH, Act::None);+    let v = point(b, l, x, WIDTH, Act::None);+    // `attn_scores` has already applied `1 / sqrt(head_dim)`, and the bias is added to the+    // scaled scores rather than to `q`. See the module docs.+    let scores = b.attn_scores(q, k, HEADS);+    let scores = b.add(scores, bias);+    let probs = b.softmax(scores);+    let mixed = b.attn_apply(probs, v, HEADS);+    let projected = point(b, l, mixed, WIDTH, Act::None);+    // Post-norm: the norm is outside the residual, not inside it.+    let x = b.add(x, projected);+    let x = b.rms_norm(x, l.take1(), RMS_EPSILON);++    let inner = point(b, l, x, FFN, Act::Gelu);+    let projected = point(b, l, inner, WIDTH, Act::None);+    let x = b.add(x, projected);+    b.rms_norm(x, l.take1(), RMS_EPSILON)+}++/// Build the forward pass: `[INPUT, 1, SQUARES]` in, `[1, 64, 64]` and `[PROMOTIONS, 1, 64]` out.+///+/// The two outputs are `scores_base` and the promotion projection over every square.+/// `post::maia` turns them into the 4352-logit move vector; see [`crate::post::maia`] for+/// why the promotion head runs over all 64 positions rather than the eight it needs.+pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {+    let mut builder = Builder::new(weights);+    let b = &mut builder;+    // The elo tables are read on the host by `elo_embedding`, so nothing in the plan touches+    // them and `finish` would otherwise refuse the file.+    b.host_tensor(ELO_LOW, &[1, ELO_DIM]);+    b.host_tensor(ELO_HIGH, &[1, ELO_DIM]);++    let tokens = b.input(Shape::new(INPUT, 1, SQUARES));+    let head = &mut Layers { next: TOKEN_PROJECTION };+    let mut x = point(b, head, tokens, WIDTH, Act::None);+    if head.next != SMOLGEN {+        return Err(format!("the token projection ends at {}, not {SMOLGEN}", head.next));+    }++    let l = &mut Layers { next: BLOCK };+    for _ in 0..BLOCKS {+        x = encoder_block(b, l, x);+    }+    if l.next != FINAL_NORM {+        return Err(format!("the stack claims {} tensors, not {FINAL_NORM}", l.next));+    }+    let x = b.layer_norm(x, FINAL_NORM, EPSILON);++    let policy = &mut Layers { next: SQ_FROM };+    let sq_from = point(b, policy, x, HEAD_HIDDEN, Act::None);+    let sq_to = point(b, policy, x, HEAD_HIDDEN, Act::None);+    // `einsum("bid,bjd->bij") / sqrt(head_hid_dim)` with one head, whose `head_dim` is+    // `HEAD_HIDDEN` — so the scale this derives is exactly the model's.+    let scores = b.attn_scores(sq_from, sq_to, 1);+    let promo = point(b, policy, sq_to, PROMOTIONS, Act::None);+    if policy.next != TENSORS {+        return Err(format!("the policy head ends at {}, not {TENSORS}", policy.next));+    }+    builder.finish(&[scores, promo])+}++/// The blended elo vector for `elo`, `ELO_DIM` long.+///+/// Upstream's `interpolate_elo`, including its inverted naming: `weight_low` is+/// `elo / 5000` and multiplies `elo_embedding_low`, so at elo 0 the vector is entirely+/// `elo_embedding_high`. Reproduced rather than corrected — the names are backwards, the+/// arithmetic is what the weights were trained against.+pub fn elo_embedding(weights: Reader<'_>, elo: f32) -> Result<Vec<f32>, String> {+    let clamped = elo.clamp(0.0, ELO_MAX);+    let weight_low = clamped / ELO_MAX;+    let weight_high = 1.0 - weight_low;+    let low = weights.fp16(ELO_LOW, &[1, ELO_DIM])?;+    let high = weights.fp16(ELO_HIGH, &[1, ELO_DIM])?;+    Ok(low+        .iter()+        .zip(high.iter())+        .map(|(&l, &h)| weight_low * l + weight_high * h)+        .collect())+}++/// The `[INPUT, 1, SQUARES]` plan input, as f32 for the caller to upload.+///+/// `planes` is the board as `PLANES * SQUARES` in plane-major order — plane `p`, square `s`+/// at `p * 64 + s`, square `rank * 8 + file` — already mirrored and colour-swapped if black+/// is to move. The eight history plies are that same board repeated; see the module docs.+///+/// The two elo vectors are broadcast across all 64 squares, which is upstream's+/// `unsqueeze(1).expand(-1, 64, -1)`.+pub fn tokens(planes: &[f32], self_elo: &[f32], oppo_elo: &[f32]) -> Result<Vec<f32>, String> {+    let squares = SQUARES as usize;+    if planes.len() != PLANES as usize * squares {+        return Err(format!("{} board values, not {}", planes.len(), PLANES as usize * squares));+    }+    if self_elo.len() != ELO_DIM as usize || oppo_elo.len() != ELO_DIM as usize {+        return Err(format!(+            "elo vectors of {} and {}, not {ELO_DIM} each",+            self_elo.len(),+            oppo_elo.len()+        ));+    }++    // Channel-major, like every other input to this runtime: channel `c`, square `s` at+    // `c * 64 + s`.+    let mut out = vec![0.0f32; INPUT as usize * squares];+    for ply in 0..HISTORY as usize {+        let base = ply * PLANES as usize * squares;+        out[base..base + PLANES as usize * squares].copy_from_slice(planes);+    }+    let after_board = (PLANES * HISTORY) as usize * squares;+    for (channel, &value) in self_elo.iter().chain(oppo_elo.iter()).enumerate() {+        let at = after_board + channel * squares;+        out[at..at + squares].fill(value);+    }+    Ok(out)+}++#[cfg(test)]+mod tests {+    use super::super::tests::{assert_no_aliasing, Shapes};+    use super::super::{Kind, Op};+    use super::*;++    fn plan() -> Plan {+        let source = Shapes::new(TENSORS);+        build(&source).unwrap_or_else(|e| panic!("{e}"))+    }++    fn counts(plan: &Plan) -> std::collections::BTreeMap<String, usize> {+        let mut counts = std::collections::BTreeMap::new();+        for op in &plan.ops {+            let name = match op {+                Op::Copy { .. } => "Copy".to_string(),+                Op::Dispatch { kind, .. } => super::super::tests::name_of(*kind),+            };+            *counts.entry(name).or_insert(0) += 1;+        }+        counts+    }++    #[test]+    fn the_layout_constants_walk_the_whole_file() {+        // The cursor arithmetic in `build` is what actually enforces this; the constants+        // are restated here so a mis-sized `BLOCK_TENSORS` fails as a number rather than+        // as a shape mismatch deep in the stack.+        assert_eq!(BLOCK_TENSORS, 30);+        assert_eq!(BLOCK, 8);+        assert_eq!(FINAL_NORM, 8 + 8 * 30);+        assert_eq!(TENSORS, FINAL_NORM + 2 + 3 + 3 + 3);+        assert_eq!(TENSORS, 259);+        // Two globals, eight per block, three in the policy head.+        assert_eq!(INT8_CONVS, 69);+        // `build` returns `Err` rather than panicking if any cursor lands short.+        plan();+    }++    #[test]+    fn the_pass_reads_every_tensor_in_the_file() {+        // `Builder::finish` refuses a tensor that is neither read nor named, so a plan that+        // builds at all has covered the file. The two elo tables are the only host ones.+        let source = Shapes::new(TENSORS);+        assert!(build(&source).is_ok());+        assert!(build(&Shapes::new(TENSORS - 1)).is_err());+    }++    #[test]+    fn the_outputs_are_the_score_map_and_the_promotion_projection() {+        let plan = plan();+        let shapes: Vec<Shape> = plan.outputs.iter().map(|o| o.shape).collect();+        assert_eq!(shapes, vec![Shape::new(1, SQUARES, SQUARES), Shape::new(PROMOTIONS, 1, SQUARES)]);+        assert_eq!(plan.inputs.len(), 1);+        assert_eq!(plan.inputs[0].shape, Shape::new(INPUT, 1, SQUARES));+    }++    #[test]+    fn every_block_normalises_twice_with_an_rms_norm_and_never_with_a_layer_norm() {+        // Post-norm with RMSNorm inside the block: 16 RMS norms for the eight blocks, and+        // layer norms only in the bias generators (2 per block) and closing the stack.+        let counts = counts(&plan());+        assert_eq!(counts.get("RmsNorm"), Some(&(2 * BLOCKS)));+        assert_eq!(counts.get("LayerNorm"), Some(&(2 * BLOCKS + 1)));+    }++    #[test]+    fn the_bias_generator_is_a_grouped_convolution_the_head_split_can_read() {+        // Grouping is what keeps `Node::ConvInt8`'s pointwise fast path from taking this,+        // and is also the whole reason the einsum needs no transpose. It is therefore the+        // one op in the plan that is an untiled `ConvInt8` rather than a `ConvPointInt8`.+        let plan = plan();+        let grouped: Vec<&Op> = plan+            .ops+            .iter()+            .filter(|op| matches!(op, Op::Dispatch { kind: Kind::ConvInt8, .. }))+            .collect();+        assert_eq!(grouped.len(), BLOCKS);+        for op in grouped {+            let Op::Dispatch { push, .. } = op else { unreachable!() };+            assert_eq!(push.group, HEADS);+            assert_eq!(push.in_c, HEADS * BIAS_GEN);+            assert_eq!(push.out_c, BIAS_OUT);+        }+    }++    #[test]+    fn every_projection_is_int8_and_every_norm_is_not() {+        // The norms, the biases and the elo tables are the only fp16 left. A projection that+        // slipped back to `Builder::conv` would still build and still run, just twice the+        // size, and no shape would catch it.+        let counts = counts(&plan());+        let int8 = counts.get("ConvInt8").copied().unwrap_or(0)+            + counts.get("ConvPointInt8").copied().unwrap_or(0)+            + counts.get("ConvVecInt8").copied().unwrap_or(0);+        // Dispatches, not tensors, and the two differ by exactly the sharing: the token+        // projection, eight projections in each of eight blocks, three policy heads, and one+        // attention-bias expansion *per block* — but all eight of those read the one+        // replicated kernel at `SMOLGEN`, so the file holds `INT8_CONVS` kernels and the plan+        // runs seven more convolutions than that.+        assert_eq!(int8, 1 + BLOCKS * 9 + 3);+        assert_eq!(int8, INT8_CONVS + BLOCKS - 1);+        assert_eq!(counts.get("Conv"), None, "an fp16 convolution is left in the plan");+    }++    #[test]+    fn the_attention_bias_is_added_to_the_scaled_scores() {+        // An `Add` of two `[HEADS, SQUARES, SQUARES]` operands, once per block, between the+        // score map and the softmax. Adding the bias to `q` instead would divide it by+        // `sqrt(head_dim)`.+        let plan = plan();+        let mut seen = 0;+        for pair in plan.ops.windows(3) {+            let [Op::Dispatch { kind: Kind::AttnScores, .. }, Op::Dispatch { kind: Kind::Add, push, .. }, Op::Dispatch { kind: Kind::Softmax, .. }] =+                pair+            else {+                continue;+            };+            assert_eq!((push.in_c, push.in_h, push.in_w), (HEADS, SQUARES, SQUARES));+            seen += 1;+        }+        assert_eq!(seen, BLOCKS);+    }++    #[test]+    fn the_policy_score_map_uses_the_models_own_scale() {+        // `attn_scores` derives `1 / sqrt(head_dim)`, and with one head over `HEAD_HIDDEN`+        // channels that is `1 / sqrt(256)` — upstream's `/ math.sqrt(head_hid_dim)`.+        let plan = plan();+        let last = plan+            .ops+            .iter()+            .rev()+            .find_map(|op| match op {+                Op::Dispatch { kind: Kind::AttnScores, push, .. } => Some(*push),+                _ => None,+            })+            .expect("a score map");+        assert_eq!(last.group, 1);+        let scale = f32::from_bits(last.param0_bits);+        assert!(+            (scale - 1.0 / (HEAD_HIDDEN as f32).sqrt()).abs() < 1e-9,+            "scale {scale}"+        );+    }++    #[test]+    fn no_op_reads_what_it_writes() {+        assert_no_aliasing(&plan());+    }++    #[test]+    fn the_elo_blend_is_upstreams_and_so_reads_backwards() {+        // At elo 0 the vector is `elo_embedding_high`, and at 5000 it is `_low`. The names+        // are upstream's and they are the wrong way round; the arithmetic is what matters.+        let blob = crate::weights::write_mixed(+            crate::weights::graph::MAIA,+            &[+                crate::weights::Fixture::F16(vec![1, ELO_DIM], vec![1.0; ELO_DIM as usize]),+                crate::weights::Fixture::F16(vec![1, ELO_DIM], vec![3.0; ELO_DIM as usize]),+            ],+        );+        let weights = crate::weights::Weights::parse(&blob, crate::weights::graph::MAIA)+            .expect("the fixture blob parses");+        let at_zero = elo_embedding(weights.reader(), 0.0).unwrap();+        let at_max = elo_embedding(weights.reader(), ELO_MAX).unwrap();+        let midpoint = elo_embedding(weights.reader(), ELO_MAX / 2.0).unwrap();+        assert!(at_zero.iter().all(|&v| (v - 3.0).abs() < 1e-3), "{:?}", &at_zero[..4]);+        assert!(at_max.iter().all(|&v| (v - 1.0).abs() < 1e-3), "{:?}", &at_max[..4]);+        assert!(midpoint.iter().all(|&v| (v - 2.0).abs() < 1e-3), "{:?}", &midpoint[..4]);+        // Past either end it clamps rather than extrapolating, as `torch.clamp` does.+        let beyond = elo_embedding(weights.reader(), 9000.0).unwrap();+        assert!(beyond.iter().all(|&v| (v - 1.0).abs() < 1e-3));+    }++    #[test]+    fn tokens_repeats_the_board_across_every_ply_and_broadcasts_the_elos() {+        // A board with one distinguishable value per plane-square, so a ply written in the+        // wrong place is visible.+        let planes: Vec<f32> =+            (0..PLANES * SQUARES).map(|i| i as f32).collect();+        let self_elo: Vec<f32> = (0..ELO_DIM).map(|i| 1000.0 + i as f32).collect();+        let oppo_elo: Vec<f32> = (0..ELO_DIM).map(|i| 2000.0 + i as f32).collect();+        let out = tokens(&planes, &self_elo, &oppo_elo).unwrap();+        assert_eq!(out.len(), INPUT as usize * SQUARES as usize);++        let stride = (PLANES * SQUARES) as usize;+        for ply in 0..HISTORY as usize {+            assert_eq!(&out[ply * stride..(ply + 1) * stride], &planes[..], "ply {ply}");+        }+        // Each elo channel is one value repeated across all 64 squares, and self comes+        // before oppo.+        let after = (PLANES * HISTORY * SQUARES) as usize;+        for channel in 0..ELO_DIM as usize {+            let at = after + channel * SQUARES as usize;+            assert!(out[at..at + 64].iter().all(|&v| v == self_elo[channel]));+        }+        let after_self = after + (ELO_DIM * SQUARES) as usize;+        for channel in 0..ELO_DIM as usize {+            let at = after_self + channel * SQUARES as usize;+            assert!(out[at..at + 64].iter().all(|&v| v == oppo_elo[channel]));+        }+    }++    #[test]+    fn tokens_refuses_a_board_or_an_elo_vector_of_the_wrong_length() {+        let planes = vec![0.0; (PLANES * SQUARES) as usize];+        let elo = vec![0.0; ELO_DIM as usize];+        assert!(tokens(&planes[..10], &elo, &elo).is_err());+        assert!(tokens(&planes, &elo[..10], &elo).is_err());+        assert!(tokens(&planes, &elo, &elo[..10]).is_err());+    }+}
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 52e69bf37d..28554fe9d2 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -32,6 +32,7 @@ #[cfg(test)] pub mod reference; pub mod mobilefacenet;+pub mod maia; pub mod nllb; pub mod ppocr_det; pub mod ppocr_rec;@@ -222,6 +223,17 @@ pub enum Kind {     /// `d_model` 120 that is 120 loads a stride apart per position, which is nothing     /// against what a contiguous layout would cost in permutes.     LayerNorm,+    /// Root-mean-square normalisation over the channel axis, with a per-channel gain.+    ///+    /// [`Kind::LayerNorm`] without the mean subtraction and without beta:+    /// `x / sqrt(mean(x^2) + eps) * gamma`. Sixteen uses, all Maia3's `norm1` / `norm2`.+    ///+    /// Separate from [`Kind::LayerNorm`] rather than a flag on it because the difference+    /// is also a difference in *weights read* — one rank-1 tensor rather than two — and+    /// [`Kind::weight_reads`] is what `vulkan::segment` uses to decide which slice of the+    /// `.maml` a pass has to have resident. A flag would make that arm depend on the push+    /// block's contents rather than its kind.+    RmsNorm,     /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`, attention's score map.     ///     /// Contracts over the *middle* axis of `[heads, head_dim, T]`, which is what makes@@ -250,6 +262,24 @@ pub enum Kind {     /// from would break four shipping nets at once if it were ever left unset. See     /// `shaders/softmax_causal.comp`.     SoftmaxCausal,+    /// [`Kind::Softmax`] over only the leading `prefix + 1` entries of each row.+    ///+    /// The decode counterpart. Once a decode plan is built once at a maximum context rather than+    /// rebuilt per token, a score-map row is as wide as that maximum but only its leading span was+    /// written this step; the rest holds whatever the previous step left. Normalising the whole+    /// row would fold that stale data into the maximum and the sum.+    ///+    /// A separate pipeline for the same reason [`Kind::SoftmaxCausal`] is one, and more so: plain+    /// [`Kind::Softmax`] is shared by PP-OCRv5 recognition, both Supertonic encoders, whisper,+    /// maia and NLLB's own encoder. See `shaders/softmax_prefix.comp`.+    SoftmaxPrefix,+    /// Write one position into a KV cache at the row [`crate::vulkan::run::StepParams::prefix`]+    /// names.+    ///+    /// The only op whose *destination* is decided at submit time rather than at record time, and+    /// the reason a decode plan can be recorded once. See `shaders/cache_write.comp` and+    /// [`Builder::cache_write`].+    CacheWrite,     /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.     ///     /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.@@ -420,6 +450,32 @@ pub struct Push {     /// Not always the element count: [`Kind::LayerNorm`] and [`Kind::Softmax`] each run     /// one invocation over a whole reduction, so for them this is the number of those.     pub count: u32,+    /// Non-zero when the attended key count comes from the step-params buffer, not from here.+    ///+    /// A decode step attends over one more position each token. Baking that into the plan is what+    /// made [`crate::vulkan::reshape::Reshaped`] re-record per token. When this is set, the three+    /// cached-attention kinds read `prefix + 1` from+    /// [`crate::vulkan::run::StepParams`] instead, and `in_w` / `out_w` stop being the key *count*+    /// and become only the key *stride* — the maximum the plan was built for.+    ///+    /// Zero for every net that does not decode, which is all of them but NLLB and whisper, so+    /// their recordings and their numbers are untouched.+    pub dyn_keys: u32,+}++/// Which span of a score-map row a [`Node::Softmax`] normalises.+///+/// A dedicated pipeline each, rather than one shader branching on a push field, because+/// [`Kind::Softmax`] is shared by six shipping nets and a field left unset would break all of+/// them at once. See [`Kind::SoftmaxCausal`] and [`Kind::SoftmaxPrefix`].+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum SoftmaxMode {+    /// The whole row.+    Full,+    /// Up to and including the diagonal; the rest is written as zero.+    Causal,+    /// The leading `prefix + 1` entries, the rest left untouched.+    Prefix, }  /// One step of a compiled forward pass.@@ -498,8 +554,12 @@ impl Kind {                 reads.push(WeightRead { at: elems(push.bias), field: "bias" });             }             // One table each: the relative position table, the literal to copy out, the-            // embedding rows.-            Kind::AttnScoresRelative | Kind::AttnApplyRelative | Kind::Constant | Kind::Embed => {+            // embedding rows. RMS norm is here too: gamma with no beta.+            Kind::AttnScoresRelative+            | Kind::AttnApplyRelative+            | Kind::Constant+            | Kind::Embed+            | Kind::RmsNorm => {                 reads.push(WeightRead { at: elems(push.weight), field: "weight" });             }             // Purely elementwise or arena-only. `attn_scores`, `softmax`, `attn_apply` and@@ -519,6 +579,8 @@ impl Kind {             | Kind::AttnScoresCached             | Kind::Softmax             | Kind::SoftmaxCausal+            | Kind::SoftmaxPrefix+            | Kind::CacheWrite             | Kind::AttnApply             | Kind::AttnApplyCached             | Kind::Rotary => {}@@ -704,6 +766,12 @@ enum Node {         beta: u32,         epsilon: f32,     },+    RmsNorm {+        input: Id,+        out: Id,+        gamma: u32,+        epsilon: f32,+    },     AttnScores {         q: Id,         k: Id,@@ -718,6 +786,8 @@ enum Node {         out: Id,         heads: u32,         scale: f32,+        /// Take the key count from the step rather than the cache's shape. See [`Push::dyn_keys`].+        dynamic: bool,     },     /// One query against a position-major V cache. See [`Kind::AttnApplyCached`].     AttnApplyCached {@@ -725,12 +795,19 @@ enum Node {         cache: Id,         out: Id,         heads: u32,+        /// Take the key count from the step rather than the cache's shape. See [`Push::dyn_keys`].+        dynamic: bool,     },     Softmax {         input: Id,         out: Id,-        /// Truncate each row at the diagonal. See [`Kind::SoftmaxCausal`].-        causal: bool,+        /// Which of the three softmax shaders normalises the row.+        mode: SoftmaxMode,+    },+    /// Append `row` to `cache` at the step's prefix. See [`Kind::CacheWrite`].+    CacheWrite {+        row: Id,+        cache: Id,     },     /// Concatenation along the **width** axis, one strided run per channel row. See     /// [`Builder::concat_positions`].@@ -1370,6 +1447,18 @@ impl<'a> Builder<'a> {         out     } +    /// Root-mean-square normalisation over the channel axis, with a per-channel gain.+    ///+    /// [`layer_norm`](Self::layer_norm) without the mean subtraction and without beta, so+    /// `weight_index` is a single tensor rather than the start of a pair.+    pub fn rms_norm(&mut self, input: Id, weight_index: usize, epsilon: f32) -> Id {+        let shape = self.shape_of(input);+        let gamma = self.weight(weight_index, &[shape.c]);+        let out = self.tensor(shape);+        self.nodes.push(Node::RmsNorm { input, out, gamma, epsilon });+        out+    }+     /// Attention scores from `q` and `k`, both `[d_model, 1, T]`, into `[heads, T, T]`.     ///     /// The `1 / sqrt(head_dim)` scale is derived here rather than taken as an argument:@@ -1390,6 +1479,18 @@ impl<'a> Builder<'a> {     /// One query is what makes a causal mask unnecessary — a decode step attends over exactly the     /// positions in the cache, so the prefix bound is the tensor's own length.     pub fn attn_scores_cached(&mut self, q: Id, cache: Id, heads: u32) -> Id {+        self.attn_scores_cached_at(q, cache, heads, false)+    }++    /// [`Builder::attn_scores_cached`] with the key count supplied by the step, not the shape.+    ///+    /// `cache` is then sized to the **maximum** context the plan is built for, and only its+    /// leading `prefix + 1` positions are attended. See [`Push::dyn_keys`].+    pub fn attn_scores_cached_dynamic(&mut self, q: Id, cache: Id, heads: u32) -> Id {+        self.attn_scores_cached_at(q, cache, heads, true)+    }++    fn attn_scores_cached_at(&mut self, q: Id, cache: Id, heads: u32, dynamic: bool) -> Id {         let (sq, sc) = (self.shape_of(q), self.shape_of(cache));         if sq.h != 1 || sq.w != 1 {             self.fail(format!(@@ -1409,7 +1510,7 @@ impl<'a> Builder<'a> {         let head_dim = sq.c.checked_div(heads).unwrap_or(0);         let scale = 1.0 / (head_dim.max(1) as f32).sqrt();         let out = self.tensor(Shape::new(heads, 1, sc.c));-        self.nodes.push(Node::AttnScoresCached { q, cache, out, heads, scale });+        self.nodes.push(Node::AttnScoresCached { q, cache, out, heads, scale, dynamic });         out     } @@ -1419,6 +1520,19 @@ impl<'a> Builder<'a> {     /// `[d_model, 1, 1]` — back in the channel-major layout the next projection reads, so the     /// cache layout is confined to the two operands that are caches.     pub fn attn_apply_cached(&mut self, probs: Id, cache: Id, heads: u32) -> Id {+        self.attn_apply_cached_at(probs, cache, heads, false)+    }++    /// [`Builder::attn_apply_cached`] with the key count supplied by the step, not the shape.+    ///+    /// Must be paired with [`Builder::attn_scores_cached_dynamic`] and+    /// [`Builder::softmax_prefix`]: all three read the same bound, and mixing a dynamic score map+    /// with a full-width sum would fold unattended positions into the result.+    pub fn attn_apply_cached_dynamic(&mut self, probs: Id, cache: Id, heads: u32) -> Id {+        self.attn_apply_cached_at(probs, cache, heads, true)+    }++    fn attn_apply_cached_at(&mut self, probs: Id, cache: Id, heads: u32, dynamic: bool) -> Id {         let (sp, sc) = (self.shape_of(probs), self.shape_of(cache));         if sp.c != heads || sp.h != 1 {             self.fail(format!("cached attention over probs {sp:?} with {heads} heads"));@@ -1432,7 +1546,7 @@ impl<'a> Builder<'a> {             self.fail(format!("{} channels do not split into {heads} heads", sc.w));         }         let out = self.tenso

Diff truncated.