Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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).
26 changes: 26 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down
9 changes: 9 additions & 0 deletions docs/overnight-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
95 changes: 95 additions & 0 deletions docs/superpowers/plans/2026-12-02-eval-win-rate-cli.md
Original file line number Diff line number Diff line change
@@ -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.
73 changes: 73 additions & 0 deletions docs/superpowers/specs/2026-12-02-eval-win-rate-cli-design.md
Original file line number Diff line number Diff line change
@@ -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.
53 changes: 53 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
@@ -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.
Binary file modified models/model_size_9_layers_3_trained.storch
Binary file not shown.
1 change: 1 addition & 0 deletions project/plugins.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Original file line number Diff line number Diff line change
Expand Up @@ -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 =>
Expand Down
Loading
Loading