diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a89ceb..c3dd586 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,22 +7,52 @@ on: jobs: test: - runs-on: ubuntu-latest + # Pin away from ubuntu-latest (26.04); keep a known GHA image. + runs-on: ubuntu-24.04 + # Forked LibTorch aborts can leave sbt wedged on "Unable to read from client". + timeout-minutes: 20 steps: - uses: actions/checkout@v4 - - name: Set up JDK 25 + - name: Set up JDK 21 uses: actions/setup-java@v4 with: distribution: temurin - java-version: "25" + java-version: "21" cache: sbt - name: Set up sbt uses: sbt/setup-sbt@v1 - - name: Run tests - run: sbt -batch test + # Cold CI runners often get Maven Central 403/429 while bootstrapping sbt itself; + # coursier reports that as "not found". Prefer Google's Central mirror for boot. + - name: Prefer Maven Central mirror for sbt bootstrap + run: | + mkdir -p "$HOME/.sbt" + cat > "$HOME/.sbt/repositories" <<'EOF' + [repositories] + local + google-maven-central: https://maven-central.storage-download.googleapis.com/maven2/ + maven-central + sbt-maven-releases: https://repo.scala-sbt.org/scalasbt/maven-releases/, bootOnly + sbt-maven-snapshots: https://repo.scala-sbt.org/scalasbt/maven-snapshots/, bootOnly + typesafe-ivy-releases: https://repo.typesafe.com/typesafe/ivy-releases/, [organization]/[module]/[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly + sbt-ivy-snapshots: https://repo.scala-sbt.org/scalasbt/ivy-snapshots/, [organization]/[module]/[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly + EOF + + # build.sbt skips LibTorch-loading suites when CI=true (DualResNet init aborts on + # GHA Linux with glibc "malloc(): unaligned tcache chunk detected"). Set + # SCALPHAGO_NATIVE_TESTS=true to force them back on. + - name: Run tests with coverage + run: sbt -batch coverage test coverageReport env: # LibTorch / OpenBLAS natives resolve via build.sbt classifier (linux-x86_64 here) SBT_OPTS: "-Xmx2G" + + - name: Upload scoverage report + if: always() + uses: actions/upload-artifact@v4 + with: + name: scoverage-report + path: target/scala-*/scoverage-report/ + if-no-files-found: ignore diff --git a/README.md b/README.md index f05c7e5..426ce82 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,12 @@ Chunked self-play via `trainOvernight.sh` (fresh JVM per chunk) writes `models/model_size_9_layers_3_trained.storch`. Setup, clean restart, env overrides, and failure cheat-sheet: [`docs/overnight-training.md`](docs/overnight-training.md). +Measure `_trained` vs the seed checkpoint (default 20 games @ 50 MCTS, stdout win rate): + +```bash +sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero eval" +``` + ### ML backends Agents/GTP talk to [`PolicyValueModel`](src/main/scala/org/deeplearning4j/scalphagozero/ml/PolicyValueModel.scala). @@ -174,3 +180,5 @@ ScalphaGoZero aims for clean abstractions that developers can reuse beyond Go; o Ideas and planned improvements live in [GitHub Issues](https://github.com/maxpumperla/ScalphaGoZero/issues). Pull requests that fix bugs or advance an open issue are welcome. + +How to run unit and integration tests locally: [`docs/testing.md`](docs/testing.md). diff --git a/build.sbt b/build.sbt index c2e8333..0483700 100644 --- a/build.sbt +++ b/build.sbt @@ -115,6 +115,8 @@ Compile / run / javaOptions ++= Seq( "-Dorg.bytedeco.javacpp.maxphysicalbytes=24G" ) ++ jvmOpenFlags ++ cudaLoaderFlags +// Soft coverage only — no coverageMinimum / failOnMinimum (see docs/testing.md). + Test / fork := true Test / parallelExecution := false Global / concurrentRestrictions += Tags.limit(Tags.Test, 1) @@ -129,6 +131,30 @@ Test / javaOptions ++= Seq( "-Dorg.bytedeco.javacpp.nopointergc=true" ) ++ jvmOpenFlags ++ cudaLoaderFlags +// GitHub Actions Linux aborts in DualResNet/LibTorch init with +// "malloc(): unaligned tcache chunk detected", then sbt hangs on the dead fork. +// Skip suites that construct/load Storch models unless SCALPHAGO_NATIVE_TESTS=true. +lazy val ciSkipNativeTests: Boolean = + sys.env.contains("CI") && !sys.env.get("SCALPHAGO_NATIVE_TESTS").contains("true") +lazy val nativeTestNameHints: Seq[String] = Seq( + ".integration.", + "Storch", + "PolicyValueModelsTest", + "ScalphaGoEngineTest", + "ZeroAgentTest", + "ZeroTreeNodeCreatorTest", + "ZeroSimulationTest", + "MonteCarloPlayerTest", + "AgzFidelityTest" +) +Test / testOptions ++= { + if (!ciSkipNativeTests) Seq.empty + else + Seq(Tests.Filter { name => + !nativeTestNameHints.exists(h => name.contains(h)) + }) +} + import org.typelevel.scalacoptions.ScalacOptions Test / tpolecatExcludeOptions += ScalacOptions.warnNonUnitStatement diff --git a/docs/overnight-training.md b/docs/overnight-training.md index 3a7d086..6a5c2c5 100644 --- a/docs/overnight-training.md +++ b/docs/overnight-training.md @@ -91,6 +91,15 @@ cp models/model_size_9_layers_3.storch models/model_size_9_layers_3.storch.bak cp models/model_size_9_layers_3_trained.storch models/model_size_9_layers_3.storch ``` +## Morning: measure strength + +Compare frozen `_trained` to the Nov 28 seed without guessing from Sabaki. Defaults: 20 games, 50 MCTS; ~50% win rate ≈ same strength as the seed. + +```bash +sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero eval" +# optional: --games 40 --rounds 100 --challenger PATH --opponent PATH +``` + ## Failure cheat-sheet | Symptom | Meaning | What to do | diff --git a/docs/superpowers/plans/2026-12-02-eval-win-rate-cli.md b/docs/superpowers/plans/2026-12-02-eval-win-rate-cli.md new file mode 100644 index 0000000..0923b4f --- /dev/null +++ b/docs/superpowers/plans/2026-12-02-eval-win-rate-cli.md @@ -0,0 +1,95 @@ +--- +name: Eval win-rate CLI +overview: Add an `eval` CLI mode that loads frozen `_trained` vs seed checkpoints, runs StrengthProxy (20 games @ 50 MCTS by default), and prints win rate to stdout — with parser unit tests and short docs. +todos: + - id: task-1-parser + content: TDD EvalConfig + EvalConfigParser + unit tests + status: pending + - id: task-2-runner + content: EvalRunner + ScalphaGoZero eval dispatch + status: pending + - id: task-3-docs + content: README + overnight-training.md usage + status: pending + - id: task-4-verify + content: Run parser tests; optional 2-game smoke + status: pending +isProject: false +--- + +# Eval Win-Rate CLI Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Spec: [docs/superpowers/specs/2026-12-02-eval-win-rate-cli-design.md](docs/superpowers/specs/2026-12-02-eval-win-rate-cli-design.md). Also save a copy of this plan to `docs/superpowers/plans/2026-12-02-eval-win-rate-cli.md` when implementing. + +**Goal:** Add `ScalphaGoZero eval` so `_trained` can be measured against the Nov 28 seed via printed win rate. + +**Architecture:** Mirror the `train` stack: `EvalConfig` + `EvalConfigParser` + `EvalRunner`, dispatch from `ScalphaGoZero`. Reuse `StrengthProxy.evaluate` unchanged; no CSV, no training. + +**Tech Stack:** Scala 3.6.4, existing Storch `PolicyValueModels`, Scalatest FunSpec for parser tests. + +## Global Constraints + +- Defaults: challenger=`models/model_size_9_layers_3_trained.storch`, opponent=`models/model_size_9_layers_3.storch`, games=20, rounds=50, board-size=9, blocks=3, seed=1 +- Stdout only; exit 1 on missing paths / bad flags; win rate does not affect exit code +- No SlowTest / full-game CI; no CSV; no GTP changes + +```mermaid +flowchart LR + CLI["ScalphaGoZero eval"] --> Parser[EvalConfigParser] + Parser --> Runner[EvalRunner] + Runner --> LoadA["load challenger"] + Runner --> LoadB["load opponent"] + LoadA --> SP[StrengthProxy.evaluate] + LoadB --> SP + SP --> Out["stdout win rate"] +``` + +## File map + +| File | Role | +|------|------| +| Create [EvalConfig.scala](src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfig.scala) | Defaults case class | +| Create [EvalConfigParser.scala](src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParser.scala) | Flag parse (train style) | +| Create [EvalConfigParserTest.scala](src/test/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParserTest.scala) | Parser unit tests | +| Create [EvalRunner.scala](src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala) | Load both models + StrengthProxy + summary | +| Modify [ScalphaGoZero.scala](src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala) | `case "eval" => EvalRunner.run(...)` | +| Modify [README.md](README.md), [overnight-training.md](docs/overnight-training.md) | Usage | + +Reuse: [StrengthProxy.scala](src/main/scala/org/deeplearning4j/scalphagozero/benchmark/StrengthProxy.scala), [StrengthProxyResult](src/main/scala/org/deeplearning4j/scalphagozero/benchmark/BenchmarkResult.scala), [PolicyValueModels.load](src/main/scala/org/deeplearning4j/scalphagozero/ml/PolicyValueModels.scala), [TrainConfigParser](src/main/scala/org/deeplearning4j/scalphagozero/app/config/TrainConfigParser.scala) as the parse pattern. + +--- + +### Task 1: EvalConfig + parser (TDD) + +**Files:** Create the three config/test files above. + +- [ ] Write `EvalConfigParserTest` mirroring [TrainConfigParserTest.scala](src/test/scala/org/deeplearning4j/scalphagozero/app/config/TrainConfigParserTest.scala): defaults; all overrides (`--challenger`, `--opponent`, `--games`, `--rounds`, `--board-size`, `--blocks`, `--seed`); unknown flag; flag without value. +- [ ] Run `sbt "testOnly org.deeplearning4j.scalphagozero.app.config.EvalConfigParserTest"` — expect compile/fail (types missing). +- [ ] Implement `EvalConfig` and `EvalConfigParser` (same while-loop/`require`/`IllegalArgumentException` style as train). Field names: `challengerPath`, `opponentPath`, `games`, `roundsPerMove`, `boardSize`, `blocks`, `seed`. +- [ ] Re-run test — PASS. +- [ ] Commit: `Add EvalConfig parser and unit tests.` + +### Task 2: EvalRunner + ScalphaGoZero dispatch + +**Files:** Create `EvalRunner.scala`; modify `ScalphaGoZero.scala`. + +- [ ] Implement `EvalRunner.run(args)`: + - Parse config; `MlBackend.fromEnvOrDefault`; `ZeroEncoder(boardSize)`. + - If either path missing: `println`/`System.err` clear message, `sys.exit(1)`. + - `PolicyValueModels.load` both paths; call `StrengthProxy.evaluate(challenger, opponent, encoder, games, roundsPerMove, seed)`. + - Print banner (paths, games, rounds) and final line like `eval done: challengerWins=W/G (R%)`. +- [ ] In `ScalphaGoZero.main`, add `case "eval" => EvalRunner.run(argv.drop(1))` and update the unknown-mode help string to include `eval`. +- [ ] Commit: `Add eval mode using StrengthProxy.` + +### Task 3: Docs + +**Files:** [README.md](README.md) overnight section; [docs/overnight-training.md](docs/overnight-training.md) after “Morning: use the trained weights”. + +- [ ] README: one short paragraph + default `sbt "runMain … ScalphaGoZero eval"` command under Overnight 9×9. +- [ ] overnight-training: “Morning: measure strength” subsection with the same command and note that ~50% ≈ same strength as seed. +- [ ] Commit: `Document eval win-rate CLI.` + +### Task 4: Verify + +- [ ] `sbt "testOnly org.deeplearning4j.scalphagozero.app.config.EvalConfigParserTest"` +- [ ] Manual smoke (optional, not CI): `sbt "runMain … ScalphaGoZero eval --games 2 --rounds 5"` against existing model files — expect 2 strength lines + summary. Skip if native/JVM flaky; parser tests are the gate. diff --git a/docs/superpowers/specs/2026-12-02-eval-win-rate-cli-design.md b/docs/superpowers/specs/2026-12-02-eval-win-rate-cli-design.md new file mode 100644 index 0000000..6577990 --- /dev/null +++ b/docs/superpowers/specs/2026-12-02-eval-win-rate-cli-design.md @@ -0,0 +1,73 @@ +# Eval win-rate CLI + +**Date:** 2026-12-02 +**Status:** Approved for implementation after user review of this spec + +## Goal + +Add a small non-interactive `eval` command that plays a frozen challenger checkpoint against a frozen opponent and prints win rate — so overnight `_trained` weights can be compared to the Nov 28 seed without guessing from Sabaki. + +## Non-goals + +- No CSV / performance history append +- No training, checkpoint writes, or model mutation +- No Sabaki/GTP changes +- No full-game integration test in CI (too slow / native-heavy) + +## Defaults (option B) + +| Flag | Default | +|------|---------| +| `--challenger` | `models/model_size_9_layers_3_trained.storch` | +| `--opponent` | `models/model_size_9_layers_3.storch` | +| `--games` | `20` | +| `--rounds` | `50` (MCTS sims per move) | +| `--board-size` | `9` | +| `--blocks` | `3` (informational / future create; both paths must exist) | +| `--seed` | `1` | + +## CLI + +```bash +sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero eval" +# optional overrides: +# --challenger PATH --opponent PATH --games N --rounds N +# --board-size N --blocks N --seed N +``` + +Unknown flags or missing required values → fail fast with a clear message (same style as `TrainConfigParser`). + +## Behavior + +1. `ScalphaGoZero` gains an `eval` mode alongside `gtp` / `benchmark` / `train`. +2. `EvalConfig` + `EvalConfigParser` under `app/config/` mirror the `train` config pattern. +3. `EvalRunner`: + - Requires both challenger and opponent paths to exist; otherwise print error and `sys.exit(1)`. + - Loads both via `PolicyValueModels.load` (Storch). + - Calls existing `StrengthProxy.evaluate` (eval agents, alternating colors, recommended komi). + - Prints per-game progress lines (StrengthProxy already does) plus a final summary: + `challengerWins/games` and win rate percent. +4. Stdout only. Exit `0` after a completed match series; exit `1` on config/load errors. Win rate does not affect exit code. + +## Testing + +- Unit tests for `EvalConfigParser` (defaults, overrides, unknown flag, missing value) — parallel to `TrainConfigParserTest`. +- Do not add a SlowTest that runs 20 real 9×9 games in CI. + +## Docs + +- Short mention in `README.md` (near overnight / benchmarks). +- Short “Morning: measure strength” note in `docs/overnight-training.md` with the default command. + +## Files (expected) + +| Path | Change | +|------|--------| +| `app/ScalphaGoZero.scala` | Dispatch `eval` | +| `app/config/EvalConfig.scala` | Case class defaults | +| `app/config/EvalConfigParser.scala` | Flag parsing | +| `app/EvalRunner.scala` | Load + StrengthProxy + summary | +| `test/.../EvalConfigParserTest.scala` | Parser tests | +| `README.md`, `docs/overnight-training.md` | Usage | + +Reuse `StrengthProxy` / `StrengthProxyResult` as-is; do not duplicate match logic. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..b3941e1 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,53 @@ +# Testing + +## Quick start + +```bash +sbt test +``` + +Runs the full ScalaTest suite: unit tests under `src/test/scala/...` plus heavier cases in the `integration/` package. Tests are **forked** and **serial** (`Test / parallelExecution := false`) so LibTorch / JavaCPP natives stay stable. + +Prefer **Temurin / OpenJDK 21** locally and in CI. JDK 25+ has been seen to SIGSEGV mid-`genmove` with LibTorch in longer GTP sessions. + +**GitHub Actions (Linux):** Dual-ResNet / LibTorch construction currently aborts on GHA runners with glibc `malloc(): unaligned tcache chunk detected`, after which forked `sbt test` hangs. CI therefore skips suites that construct or load Storch models (`CI=true` unless `SCALPHAGO_NATIVE_TESTS=true`). Run the full suite locally on macOS / a known-good Linux host. + +## Single suites + +```bash +# Fast board / rules +sbt "testOnly org.deeplearning4j.scalphagozero.board.*" + +# Agents / MCTS (mostly stubs; a few create tiny Dual-ResNets) +sbt "testOnly org.deeplearning4j.scalphagozero.agents.*" + +# One integration suite +sbt "testOnly org.deeplearning4j.scalphagozero.integration.GtpIntegrationTest" +sbt "testOnly org.deeplearning4j.scalphagozero.integration.SelfPlayIntegrationTest" +``` + +## Slow / native-heavy tests + +These load Dual-ResNet checkpoints or run self-play and are slower than pure board/encoder tests: + +- `integration/GtpIntegrationTest`, `ScalphaGoEngineTest` +- `integration/SelfPlayIntegrationTest`, `TrainIntegrationTest`, `ModelSaveLoadIntegrationTest` +- `ml/PolicyValueModelsTest`, `AgzFidelityTest` (tiny net create), CUDA parity (`StorchCudaParityTest`) + +There is no separate sbt `IntegrationTest` config; everything runs under `sbt test`. + +## Optional GPU + +```bash +sbt -Dscalphago.cuda=true test +``` + +See [gpu.md](gpu.md). GPU tests use `assume(torch.cuda.isAvailable)` where needed. + +## Coverage (soft) + +```bash +sbt coverage test coverageReport +``` + +HTML report: `target/scala-*/scoverage-report/index.html`. CI uploads this as an artifact; there is **no** coverage floor yet. diff --git a/models/model_size_9_layers_3_trained.storch b/models/model_size_9_layers_3_trained.storch index 5d12bb3..4efc9b8 100644 Binary files a/models/model_size_9_layers_3_trained.storch and b/models/model_size_9_layers_3_trained.storch differ diff --git a/project/plugins.sbt b/project/plugins.sbt index add1908..f4b4f0b 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -2,3 +2,4 @@ addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.4") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.5") addSbtPlugin("org.typelevel" % "sbt-tpolecat" % "0.5.2") addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.1") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.3.1") diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala b/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala index ed3942e..45f91a0 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala @@ -242,7 +242,7 @@ class ZeroAgent( collector.recordDecision(rootStateTensor, visitCounts) } - private def selectValidNextMove(validMoves: Seq[Move], root: ZeroTreeNode, ply: Int): Move = + private[agents] def selectValidNextMove(validMoves: Seq[Move], root: ZeroTreeNode, ply: Int): Move = if (validMoves.isEmpty) Move.Pass else if (ply < temperatureMoves && temperature > 1e-12) { val weights = validMoves.map { m => diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala new file mode 100644 index 0000000..c085df8 --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala @@ -0,0 +1,58 @@ +package org.deeplearning4j.scalphagozero.app + +import java.nio.file.{Files, Path} + +import org.deeplearning4j.scalphagozero.app.config.EvalConfigParser +import org.deeplearning4j.scalphagozero.benchmark.StrengthProxy +import org.deeplearning4j.scalphagozero.encoders.ZeroEncoder +import org.deeplearning4j.scalphagozero.ml.{MlBackend, PolicyValueModels} + +/** + * Non-interactive frozen-model strength eval: challenger vs opponent via [[StrengthProxy]]. + * No training and no checkpoint writes. + */ +object EvalRunner { + + def run(args: Array[String]): Unit = { + val config = EvalConfigParser.parse(args) + val challengerPath = Path.of(config.challengerPath) + val opponentPath = Path.of(config.opponentPath) + + if (!Files.exists(challengerPath)) { + System.err.println(s"Challenger model not found: $challengerPath") + sys.exit(1) + } + if (!Files.exists(opponentPath)) { + System.err.println(s"Opponent model not found: $opponentPath") + sys.exit(1) + } + + val backend = MlBackend.fromEnvOrDefault + val encoder = ZeroEncoder(config.boardSize) + + println( + s"=== ScalphaGoZero eval board=${config.boardSize} blocks=${config.blocks} " + + s"rounds=${config.roundsPerMove} games=${config.games} ===" + ) + println(s"challenger=$challengerPath") + println(s"opponent=$opponentPath") + System.out.flush() + + val challenger = PolicyValueModels.load(backend, challengerPath) + val opponent = PolicyValueModels.load(backend, opponentPath) + + val result = StrengthProxy.evaluate( + challengerModel = challenger, + opponentModel = opponent, + encoder = encoder, + games = config.games, + roundsPerMove = config.roundsPerMove, + seed = config.seed + ) + + println( + f"eval done: challengerWins=${result.challengerWins}/${result.games} " + + f"(${result.winRate * 100}%.1f%%)" + ) + } +} diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala index 81cddbd..ae8c841 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala @@ -8,6 +8,7 @@ import org.deeplearning4j.scalphagozero.benchmark.BenchmarkRunner * - gtp → GTP client for Sabaki / GUIs * - benchmark … → non-interactive baseline harness * - train … → one self-play chunk with checkpoint save (overnight scripts) + * - eval … → frozen challenger vs opponent win-rate (StrengthProxy) * * @author Max Pumperla * @author Barry Becker @@ -46,8 +47,10 @@ object ScalphaGoZero { val _ = new BenchmarkRunner(config).run() case "train" => TrainRunner.run(argv.drop(1)) + case "eval" => + EvalRunner.run(argv.drop(1)) case other => - System.err.println(s"Unknown mode '$other'. Use no args (demo), 'gtp', 'benchmark', or 'train'.") + System.err.println(s"Unknown mode '$other'. Use no args (demo), 'gtp', 'benchmark', 'train', or 'eval'.") sys.exit(1) } } diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfig.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfig.scala new file mode 100644 index 0000000..e684200 --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfig.scala @@ -0,0 +1,12 @@ +package org.deeplearning4j.scalphagozero.app.config + +/** CLI settings for frozen challenger-vs-opponent strength eval. */ +final case class EvalConfig( + boardSize: Int = 9, + blocks: Int = 3, + roundsPerMove: Int = 50, + games: Int = 20, + challengerPath: String = "models/model_size_9_layers_3_trained.storch", + opponentPath: String = "models/model_size_9_layers_3.storch", + seed: Long = 1L +) diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParser.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParser.scala new file mode 100644 index 0000000..c40b323 --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParser.scala @@ -0,0 +1,38 @@ +package org.deeplearning4j.scalphagozero.app.config + +/** Parses `eval` CLI flags into an [[EvalConfig]]. */ +object EvalConfigParser { + + def parse(args: Array[String]): EvalConfig = { + var config = EvalConfig() + var i = 0 + while (i < args.length) { + args(i) match { + case "--board-size" => + require(i + 1 < args.length, "--board-size requires a value") + config = config.copy(boardSize = args(i + 1).toInt); i += 2 + case "--blocks" => + require(i + 1 < args.length, "--blocks requires a value") + config = config.copy(blocks = args(i + 1).toInt); i += 2 + case "--rounds" => + require(i + 1 < args.length, "--rounds requires a value") + config = config.copy(roundsPerMove = args(i + 1).toInt); i += 2 + case "--games" => + require(i + 1 < args.length, "--games requires a value") + config = config.copy(games = args(i + 1).toInt); i += 2 + case "--challenger" => + require(i + 1 < args.length, "--challenger requires a path") + config = config.copy(challengerPath = args(i + 1)); i += 2 + case "--opponent" => + require(i + 1 < args.length, "--opponent requires a path") + config = config.copy(opponentPath = args(i + 1)); i += 2 + case "--seed" => + require(i + 1 < args.length, "--seed requires a value") + config = config.copy(seed = args(i + 1).toLong); i += 2 + case other => + throw new IllegalArgumentException(s"Unknown eval argument: $other") + } + } + config + } +} diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoder.scala b/src/main/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoder.scala index 63f01ec..91e9c66 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoder.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoder.scala @@ -62,7 +62,8 @@ final class ZeroEncoder(boardSize: Int) extends Encoder(boardSize, 11) { case _ => throw new IllegalArgumentException("Cannot encode resign move") } - override def decodeMoveIndex(index: Int): Move = + override def decodeMoveIndex(index: Int): Move = { + require(index >= 0 && index <= numberOfPoints, s"move index $index out of range [0, $numberOfPoints]") if (index == numberOfPoints) { Move.Pass } else { @@ -70,6 +71,7 @@ final class ZeroEncoder(boardSize: Int) extends Encoder(boardSize, 11) { val col = index % boardSize Move.Play(Point(row + 1, col + 1)) } + } } object ZeroEncoder { diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/StorchPolicyValueModel.scala b/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/StorchPolicyValueModel.scala index a70c2e4..1d2dd71 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/StorchPolicyValueModel.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/StorchPolicyValueModel.scala @@ -44,6 +44,15 @@ final class StorchPolicyValueModel private ( try { val n = shape(0) require(n > 0, "predictBatch needs at least one row") + require(shape.length == 4, s"expected NCHW rank 4, got ${shape.toSeq}") + require( + shape(1) == net.planes && shape(2) == net.boardSize && shape(3) == net.boardSize, + s"shape ${shape.toSeq} incompatible with planes=${net.planes} boardSize=${net.boardSize}" + ) + require( + states.length == shape.product, + s"states length ${states.length} != shape product ${shape.product}" + ) net.eval() val x = toTensor(states, shape) val (policyLogits, valueLogits) = net.forward(x) @@ -61,9 +70,15 @@ final class StorchPolicyValueModel private ( StorchPolicyValueModel.NativeLock.synchronized { val scope = new PointerScope() try { - net.train(true) val n = batch.stateShape(0) - val numMoves = batch.policyTarget.length / n + val expectedMoves = net.boardSize * net.boardSize + 1 + require( + batch.policyTarget.length == n * expectedMoves, + s"policyTarget length ${batch.policyTarget.length} != $n * $expectedMoves" + ) + require(batch.valueTarget.length == n, s"valueTarget length ${batch.valueTarget.length} != $n") + net.train(true) + val numMoves = expectedMoves val x = toTensor(batch.states, batch.stateShape) val policyTarget = toTensor(batch.policyTarget, Array(n, numMoves)) val valueTarget = toTensor(batch.valueTarget, Array(n, 1)) diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/agents/AgzFidelityTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/agents/AgzFidelityTest.scala index 9f24242..a4f2fb3 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/agents/AgzFidelityTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/agents/AgzFidelityTest.scala @@ -26,6 +26,24 @@ class AgzFidelityTest extends AnyFunSpec { assert(node.moves.forall(m => node.prior(m) > 0.0)) } + it("same seed yields identical mixed priors") { + val priors = Map(Play(1, 1) -> 0.7, Play(2, 2) -> 0.2, Play(3, 3) -> 0.1, Move.Pass -> 0.0) + val a = new ZeroTreeNode(GameState.newGame(5), 0.0, priors, None, None) + val b = new ZeroTreeNode(GameState.newGame(5), 0.0, priors, None, None) + a.applyDirichletNoise(0.25, 0.3, new Random(42)) + b.applyDirichletNoise(0.25, 0.3, new Random(42)) + assert(a.moves == b.moves) + a.moves.foreach(m => assert(math.abs(a.prior(m) - b.prior(m)) < 1e-12, s"prior mismatch at $m")) + } + + it("epsilon 0 leaves priors unchanged") { + val priors = Map(Play(1, 1) -> 0.7, Play(2, 2) -> 0.2, Play(3, 3) -> 0.1, Move.Pass -> 0.0) + val node = new ZeroTreeNode(GameState.newGame(5), 0.0, priors, None, None) + val before = node.moves.map(m => m -> node.prior(m)).toMap + node.applyDirichletNoise(0.0, 0.3, new Random(42)) + node.moves.foreach(m => assert(node.prior(m) == before(m))) + } + it("sample produces a valid probability vector") { val d = Dirichlet.sample(0.3, 8, new Random(7)) assert(d.length == 8) diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/agents/PassCollapseGuardTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/agents/PassCollapseGuardTest.scala index 2586575..d8354dd 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/agents/PassCollapseGuardTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/agents/PassCollapseGuardTest.scala @@ -64,6 +64,22 @@ class PassCollapseGuardTest extends AnyFunSpec { assert(move != Move.Pass, s"must play a stone while legal plays exist, got $move") assert(move.isInstanceOf[Move.Play]) } + + it("forEval still refuses Pass deep into a longer mid-game") { + val agent = ZeroAgent.forEval(passHungryModel, encoder, roundsPerMove = 25, rand = new Random(3)) + var game = GameState.newGame(5) + val longer = Seq( + Play(1, 1), Play(1, 5), Play(5, 1), Play(5, 5), Play(3, 3), + Play(3, 2), Play(2, 3), Play(4, 3), Play(3, 4), Play(2, 2), + Play(4, 4), Play(2, 4) + ) + longer.foreach(m => if (!game.isOver && game.isValidMove(m)) game = game.applyMove(m)) + assert(ZeroAgent.plyCount(game) >= 10, s"expected a deep mid-game, ply=${ZeroAgent.plyCount(game)}") + assert(!game.isOver) + val move = agent.selectMove(game) + assert(move != Move.Pass, s"must play a stone while legal plays exist at ply ${ZeroAgent.plyCount(game)}, got $move") + assert(move.isInstanceOf[Move.Play]) + } } describe("self-play ply gate") { diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgentTemperatureTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgentTemperatureTest.scala new file mode 100644 index 0000000..83b7066 --- /dev/null +++ b/src/test/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgentTemperatureTest.scala @@ -0,0 +1,86 @@ +package org.deeplearning4j.scalphagozero.agents + +import java.nio.file.Path + +import org.deeplearning4j.scalphagozero.board.Move.Play +import org.deeplearning4j.scalphagozero.board.{ GameState, Move } +import org.deeplearning4j.scalphagozero.encoders.ZeroEncoder +import org.deeplearning4j.scalphagozero.ml.{ PolicyValueModel, Prediction, TrainingBatch } +import org.scalatest.funspec.AnyFunSpec + +import scala.util.Random + +/** + * Temperature cut-off and fresh-root-per-move (no tree reuse) for ZeroAgent. + */ +class ZeroAgentTemperatureTest extends AnyFunSpec { + + private val encoder = ZeroEncoder(5) + + private val stubModel: PolicyValueModel = new PolicyValueModel { + override def predict(state: Array[Float], shape: Array[Int]): Prediction = { + val policy = Array.fill(encoder.numMoves)(1.0 / encoder.numMoves) + Prediction(policy, 0.0) + } + override def fit(batch: TrainingBatch): Unit = () + override def save(path: Path): Unit = () + } + + private def nodeWithVisits(visits: Map[Move, Int]): ZeroTreeNode = { + val priors = visits.keys.map(m => m -> 0.5).toMap + val n = new ZeroTreeNode(GameState.newGame(5), 0.0, priors, None, None) + visits.foreach { case (m, count) => + for (_ <- 0 until count) n.recordVisit(m, 0.1) + } + n + } + + describe("temperature cut-off") { + it("samples from visit weights when ply is below temperatureMoves") { + val a = new ZeroAgent( + stubModel, + encoder, + roundsPerMove = 1, + rand = new Random(0), + temperatureMoves = 2, + temperature = 1.0 + ) + val root = nodeWithVisits(Map(Play(1, 1) -> 1, Play(5, 5) -> 100)) + val moves = Seq(Play(1, 1), Play(5, 5)) + // Fixed seed 0 with weights [1,100] picks the rare branch for the first draw. + val weights = Array(1.0, 100.0) + val expectedIdx = ProbabilityDistribution(weights, new Random(0)).selectRandomIdx() + val got = a.selectValidNextMove(moves, root, ply = 0) + assert(got == moves(expectedIdx)) + } + + it("returns argmax visits once ply reaches temperatureMoves") { + val a = new ZeroAgent( + stubModel, + encoder, + roundsPerMove = 1, + rand = new Random(0), + temperatureMoves = 2, + temperature = 1.0 + ) + val root = nodeWithVisits(Map(Play(1, 1) -> 1, Play(5, 5) -> 100)) + val moves = Seq(Play(1, 1), Play(5, 5)) + assert(a.selectValidNextMove(moves, root, ply = 2) == Play(5, 5)) + assert(a.selectValidNextMove(moves, root, ply = 10) == Play(5, 5)) + } + } + + describe("fresh root per move (no tree reuse)") { + it("searchRoot matches the state passed into the latest selectMove") { + val agent = new ZeroAgent(stubModel, encoder, roundsPerMove = 3, rand = new Random(1), useMcPlayout = false) + val g0 = GameState.newGame(5) + val _ = agent.selectMove(g0) + assert(agent.searchRoot.gameState == g0) + + val g1 = g0.applyMove(Play(3, 3)) + val _ = agent.selectMove(g1) + assert(agent.searchRoot.gameState == g1) + assert(agent.searchRoot.parent.isEmpty) + } + } +} diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/app/TrainerWaveTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/app/TrainerWaveTest.scala index 60ab976..465c7cf 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/app/TrainerWaveTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/app/TrainerWaveTest.scala @@ -27,4 +27,31 @@ class TrainerWaveTest extends AnyFunSpec { assert(next == 15) } } + + describe("Trainer leftover flush") { + it("fits the mid-batch threshold then flushes remaining episodes at the end") { + // Mirrors Trainer.runSimulationsAndTrain with episodes=7, batchSize=5, wave=1: + // fit when finished hits 5; leftover pending after episode 7 forces a second fit. + val batchSize = 5 + val episodes = 7 + var finished = 0 + var nextFitAt = batchSize + var pending = 0 + val fits = ArrayBuffer.empty[Int] + var nextGame = 0 + while (nextGame < episodes) { + val wave = 1 + pending += wave + finished += wave + nextGame += wave + if (finished >= nextFitAt) { + fits += finished + pending = 0 + nextFitAt = Trainer.nextFitThreshold(finished, batchSize) + } + } + if (pending > 0) fits += finished + assert(fits.toList == List(5, 7)) + } + } } diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParserTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParserTest.scala new file mode 100644 index 0000000..2a6dea9 --- /dev/null +++ b/src/test/scala/org/deeplearning4j/scalphagozero/app/config/EvalConfigParserTest.scala @@ -0,0 +1,53 @@ +package org.deeplearning4j.scalphagozero.app.config + +import org.scalatest.funspec.AnyFunSpec + +class EvalConfigParserTest extends AnyFunSpec { + + describe("EvalConfigParser.parse") { + it("returns defaults when no args") { + val cfg = EvalConfigParser.parse(Array.empty) + assert(cfg == EvalConfig()) + } + + it("applies each override flag") { + val cfg = EvalConfigParser.parse( + Array( + "--challenger", + "models/challenger.storch", + "--opponent", + "models/opponent.storch", + "--games", + "8", + "--rounds", + "25", + "--board-size", + "5", + "--blocks", + "2", + "--seed", + "42" + ) + ) + assert(cfg.challengerPath == "models/challenger.storch") + assert(cfg.opponentPath == "models/opponent.storch") + assert(cfg.games == 8) + assert(cfg.roundsPerMove == 25) + assert(cfg.boardSize == 5) + assert(cfg.blocks == 2) + assert(cfg.seed == 42L) + } + + it("rejects unknown flags") { + intercept[IllegalArgumentException] { + EvalConfigParser.parse(Array("--unknown")) + } + } + + it("rejects a flag without a value") { + intercept[IllegalArgumentException] { + EvalConfigParser.parse(Array("--games")) + } + } + } +} diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/benchmark/BenchmarkConfigTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/benchmark/BenchmarkConfigTest.scala index 773ea03..29312c7 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/benchmark/BenchmarkConfigTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/benchmark/BenchmarkConfigTest.scala @@ -30,5 +30,12 @@ class BenchmarkConfigTest extends AnyFunSpec { assert(cfg.evalGames == 0) assert(cfg.roundsPerMove == 50) } + + it("rejects unknown flags") { + val ex = intercept[IllegalArgumentException] { + BenchmarkRunner.parseArgs(Array("--not-a-real-flag", "1")) + } + assert(ex.getMessage.contains("Unknown benchmark argument")) + } } } diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/board/GoBoardSerializerTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/board/GoBoardSerializerTest.scala index 61136a1..84f3111 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/board/GoBoardSerializerTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/board/GoBoardSerializerTest.scala @@ -51,4 +51,41 @@ class GoBoardSerializerTest extends AnyFunSpec { } } + + describe("empty and multi-string boards") { + it("serializes an empty 5x5 board") { + val board = GoBoard(5) + assertResult(strip("""-------- + | 5 ..... + | 4 ..... + | 3 ..... + | 2 ..... + | 1 ..... + | ABCDE + |--------""")) { board.toString } + } + + it("serializes multiple GoStrings after a capture") { + // Two disjoint black stones, white surrounds and captures one black stone, + // leaving black (top-left) + white string(s) and an empty capture point. + var board = GoBoard(5) + board = GoRules.placeStone(board, BlackPlayer, Point(1, 1)) // stays + board = GoRules.placeStone(board, BlackPlayer, Point(3, 3)) // will be captured + board = GoRules.placeStone(board, WhitePlayer, Point(2, 3)) + board = GoRules.placeStone(board, WhitePlayer, Point(3, 2)) + board = GoRules.placeStone(board, WhitePlayer, Point(3, 4)) + board = GoRules.placeStone(board, WhitePlayer, Point(4, 3)) // captures black at 3,3 + + assert(board.getPlayer(Point(3, 3)).isEmpty) + assert(board.getPlayer(Point(1, 1)).contains(BlackPlayer)) + assertResult(strip("""-------- + | 5 X.... + | 4 ..O.. + | 3 .O.O. + | 2 ..O.. + | 1 ..... + | ABCDE + |--------""")) { board.toString } + } + } } diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoderTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoderTest.scala index a9a091d..ce3fcd6 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoderTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/encoders/ZeroEncoderTest.scala @@ -253,6 +253,31 @@ class ZeroEncoderTest extends AnyFunSpec { assert(encoder.decodeMoveIndex(0) == Play(1, 1)) assert(encoder.decodeMoveIndex(80) == Play(9, 9)) } + + it("encodes empty 13x13 with correct shape and pass index") { + val encoder = ZeroEncoder(13) + val tensor = encoder.encode(GameState.newGame(13)) + assert(encoder.numMoves == 170) + assert(encoder.encodeShape.sameElements(Array(1, 11, 13, 13))) + assert(tensor.length == 1 * 11 * 13 * 13) + assert(encoder.encodeMove(Move.Pass) == 169) + assert(encoder.decodeMoveIndex(169) == Move.Pass) + assert(encoder.decodeMoveIndex(0) == Play(1, 1)) + assert(encoder.decodeMoveIndex(12) == Play(1, 13)) + assert(encoder.decodeMoveIndex(168) == Play(13, 13)) + assert(encoder.encodeMove(Play(1, 1)) == 0) + assert(encoder.encodeMove(Play(13, 13)) == 168) + } + + it("rejects out-of-range move indices") { + val encoder = ZeroEncoder(5) + intercept[IllegalArgumentException] { + encoder.decodeMoveIndex(-1) + } + intercept[IllegalArgumentException] { + encoder.decodeMoveIndex(encoder.numMoves) + } + } } describe("Ko plane") { diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/integration/GtpIntegrationTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/integration/GtpIntegrationTest.scala index 4553d93..083cba0 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/integration/GtpIntegrationTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/integration/GtpIntegrationTest.scala @@ -91,5 +91,34 @@ class GtpIntegrationTest extends AnyFunSpec { assert(shared.getVersion.nonEmpty) assert(!shared.canScore) } + + it("boardsize mid-session resets to a fresh empty board") { + shared.resizeBoard(5) + shared.newGame() + assert(shared.addMove(new Move(2, 2), Player.BLACK)) + assert(shared.getGameState.board.getPlayer( + org.deeplearning4j.scalphagozero.board.Point(3, 3) + ).isDefined) + assert(shared.resizeBoard(5)) + val after = shared.getGameState + assert(!after.isOver) + assert(after.nextPlayer == BlackPlayer) + assert(after.board.getPlayer(org.deeplearning4j.scalphagozero.board.Point(3, 3)).isEmpty) + val mv = shared.nextMove(Player.BLACK) + assert(mv != null) + assert(mv != Move.RESIGN) + } + + it("genmove after double Pass returns RESIGN") { + shared.resizeBoard(5) + shared.newGame() + assert(shared.addMove(Move.PASS, Player.BLACK)) + assert(shared.addMove(Move.PASS, Player.WHITE)) + assert(shared.getGameState.isOver) + val before = shared.getGameState + val mv = shared.nextMove(Player.BLACK) + assert(mv == Move.RESIGN) + assert(shared.getGameState eq before) + } } } diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/ml/PolicyValueModelsTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/ml/PolicyValueModelsTest.scala index b555438..6d25cf6 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/ml/PolicyValueModelsTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/ml/PolicyValueModelsTest.scala @@ -6,6 +6,10 @@ import org.scalatest.funspec.AnyFunSpec class PolicyValueModelsTest extends AnyFunSpec { + // One tiny Dual-ResNet for the suite — repeated creates/loads exhaust JavaCPP native memory. + private lazy val tiny: PolicyValueModel = + PolicyValueModels.create(MlBackend.Storch, blocks = 1, planes = 11, boardSize = 5) + describe("MlBackend") { it("parses dl4j and storch") { assert(MlBackend.fromString("dl4j") == MlBackend.Dl4j) @@ -23,26 +27,30 @@ class PolicyValueModelsTest extends AnyFunSpec { describe("PolicyValueModels") { it("creates a Storch model for tiny 5x5 and runs predict") { - val m = PolicyValueModels.create(MlBackend.Storch, blocks = 1, planes = 11, boardSize = 5) val state = Array.fill(1 * 11 * 5 * 5)(0f) - val pred = m.predict(state, Array(1, 11, 5, 5)) + val pred = tiny.predict(state, Array(1, 11, 5, 5)) assert(pred.policy.length == 26) assert(!pred.value.isNaN) assert(pred.value >= -1.0 && pred.value <= 1.0) assert(pred.policy.forall(p => !p.isNaN)) } - it("round-trips save/load") { - val m = PolicyValueModels.create(MlBackend.Storch, blocks = 1, planes = 11, boardSize = 5) + it("round-trips save/load and rejects mismatched board shape on loaded model") { val tmp = Files.createTempFile("scalphago-storch-", ".storch") tmp.toFile.deleteOnExit() - m.save(tmp) + tiny.save(tmp) val loaded = PolicyValueModels.load(MlBackend.Storch, tmp) val state = Array.fill(1 * 11 * 5 * 5)(0.1f) - val a = m.predict(state, Array(1, 11, 5, 5)) + val a = tiny.predict(state, Array(1, 11, 5, 5)) val b = loaded.predict(state, Array(1, 11, 5, 5)) assert(math.abs(a.value - b.value) < 1e-4) assert(a.policy.zip(b.policy).map { case (x, y) => math.abs(x - y) }.sum < 1e-3) + + val wrong = Array.fill(1 * 11 * 9 * 9)(0f) + val ex = intercept[IllegalArgumentException] { + loaded.predict(wrong, Array(1, 11, 9, 9)) + } + assert(ex.getMessage.contains("boardSize")) } it("rejects DL4J backend (removed from classpath)") { @@ -50,5 +58,40 @@ class PolicyValueModelsTest extends AnyFunSpec { PolicyValueModels.create(MlBackend.Dl4j, blocks = 1, planes = 11, boardSize = 5) } } + + it("rejects predict with mismatched board size in shape") { + val state = Array.fill(1 * 11 * 9 * 9)(0f) + val ex = intercept[IllegalArgumentException] { + tiny.predict(state, Array(1, 11, 9, 9)) + } + assert(ex.getMessage.contains("boardSize")) + } + + it("rejects fit with wrong policyTarget length") { + val n = 1 + val states = Array.fill(n * 11 * 5 * 5)(0f) + val batch = TrainingBatch( + states = states, + stateShape = Array(n, 11, 5, 5), + policyTarget = Array.fill(10)(0f), // wrong length (expect 26) + valueTarget = Array(0f) + ) + val ex = intercept[IllegalArgumentException] { + tiny.fit(batch) + } + assert(ex.getMessage.contains("policyTarget")) + } + + it("rejects load of checkpoint with bad magic") { + val tmp = Files.createTempFile("scalphago-bad-magic-", ".storch") + tmp.toFile.deleteOnExit() + val out = new java.io.DataOutputStream(new java.io.FileOutputStream(tmp.toFile)) + try out.writeUTF("not-a-valid-magic") + finally out.close() + val ex = intercept[IllegalArgumentException] { + PolicyValueModels.load(MlBackend.Storch, tmp) + } + assert(ex.getMessage.toLowerCase.contains("magic")) + } } }