ScalphaGoZero is an independent implementation of DeepMind's AlphaGo Zero in Scala.
The neural net is a Dual ResNet policy/value model on Storch (LibTorch),
behind a small PolicyValueModel interface.
ScalphaGoZero is mainly an engineering effort to demonstrate how complex and successful systems in machine learning are not bound to Python anymore. With LibTorch via Storch and the mature infrastructure of the JVM, languages like Scala can offer a viable alternative for data scientists.
This project is a Scala port of the AlphaGo Zero module found in Deep Learning and the Game of Go.
To run after cloning, do
cd ScalphaGoZero
sbt runThis application will set up two opponents, simulate some specified number of games between them using the AlphaGo Zero methodology and train one of the opponents with the experience data gained from the games. You can also accumulate training experience in a saved model and use that model later.
Regenerate checked-in Dual-ResNet checkpoints (5×5 and 9×9) with:
sbt "runMain org.deeplearning4j.scalphagozero.app.GenerateStorchCheckpoints"Build a fat jar that speaks GTP for Go GUIs such as Sabaki:
sbt assemblyPrefer the platform wrappers (gtpClient.sh / gtpClient.bat): they pass JVM flags required for LibTorch/JavaCPP. A bare java -jar … gtp without those flags often dies with SIGSEGV in libjnitorch during Dual-ResNet construction.
GTP mode reads commands from stdin (Sabaki does this for you). A quick smoke test from the project root:
chmod +x gtpClient.sh # once, on macOS/Linux
printf 'protocol_version\nname\nboardsize 5\nclear_board\ngenmove b\nquit\n' | ./gtpClient.shYou should see GTP replies such as = 2, = ScalphaGoZero, and a move like = a3.
For Sabaki, point the engine at the wrapper script for your OS (not a raw java -jar command). The wrappers live in the repo root and launch the fat jar in GTP mode.
- From the project root, make the shell wrapper executable (once):
chmod +x gtpClient.sh
- In Sabaki, open Engines → Manage Engines and add an engine:
- Path: absolute path to
gtpClient.sh
(e.g./Users/<user>/projects/ScalphaGoZero/gtpClient.sh) - Initial directory / working directory: the project root
(e.g./Users/<user>/projects/ScalphaGoZero) so relativemodels/paths resolve. - Arguments (optional):
--layers 3for 9×9,--rounds 50for faster moves.
- Path: absolute path to
- Ensure
javais on your PATH (Temurin / OpenJDK 21 recommended). - Prefer one engine vs human on 9×9 first (two engine instances each load a Dual-ResNet).
- To use overnight-trained weights:
cp models/model_size_9_layers_3_trained.storch models/model_size_9_layers_3.storch
- In Sabaki, open Engines → Manage Engines and add an engine:
- Path: absolute path to
gtpClient.bat
(e.g.C:\Users\you\projects\ScalphaGoZero\gtpClient.bat) - Initial directory / working directory: the project root
(e.g.C:\Users\you\projects\ScalphaGoZero).
- Path: absolute path to
- Ensure
javais on your PATH.
Then File → New. For Black, White, or both, select the ScalphaGoZero engine you added. The engine loads a checkpoint from models/ for the chosen board size (5×5: models/model_size_5_layers_2.storch; 9×9: models/model_size_9_layers_3.storch).
While the engine runs, information and errors go to output.log in the working directory.
Use the non-interactive benchmark harness to measure training throughput and a small-board strength proxy against the frozen 5×5 checkpoint in models/.
# Tiny harness check (seconds–minutes)
sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero benchmark --config smoke"
# Official modernization baselines (can take a long time on CPU)
sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero benchmark --config A"
sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero benchmark --config B"Results append to performance/benchmark-results.csv. Side-by-side interpretation: performance/COMPARISON.md. Historical 2020 GPU timings remain in performance/performance-results.csv for reference only (different hardware/stack).
| Config | Board | Blocks | MCTS rounds | Episodes | Eval games |
|---|---|---|---|---|---|
| smoke | 5 | 2 | 5 | 2 | 2 |
| A | 5 | 2 | 50 | 20 | 10 |
| B | 5 | 2 | 100 | 50 | 10 |
Optional overrides: --backend storch, --rounds, --episodes, --batch, --eval-games, --eval-rounds, --seed, --model.
Env: SCALPHAGO_ML_BACKEND (default storch).
Smoke snapshot (same Mac aarch64 CPU): Phase 0 DL4J baseline ~26 s/episode → 1.2.0 Storch ~0.2–1.3 s/episode (~20–100×). Strength on smoke (n=2) is noisy; use config A for a 10-game proxy. See COMPARISON.md.
Self-play runs in small chunks, each in a fresh JVM, so LibTorch/JavaCPP native memory (nopointergc) cannot grow into a SIGKILL that wipes the whole night. The shipped 9×9 checkpoint is left alone; training writes models/model_size_9_layers_3_trained.storch. Within a chunk, weights are checkpointed after every training batch.
Do not use interactive sbt run Demo or a single huge benchmark job for this — those keep one JVM forever and often die with exit 137 (SIGKILL) or a LibTorch SIGSEGV.
cd /path/to/ScalphaGoZero
sbt assembly # fat jar makes each chunk much faster to start
chmod +x trainOvernight.shRun from Terminal.app / iTerm (not an IDE run console), so the job is not tied to an editor session:
# ~1 hour wall clock, smaller chunks (safer)
DURATION_HOURS=1 EPISODES=5 ROUNDS=25 BATCH=5 ./trainOvernight.shWatch progress in another terminal:
tail -f logs/train-overnight-$(date +%Y%m%d).logYou should see episode N/5, then checkpoint saved after episode …, then Attempt K OK. If you only see the banner and then silence for a long time with no episode lines, something is wrong (or an old jar without progress logging is being used — re-run sbt assembly).
# Script auto-wraps with macOS caffeinate to reduce sleep kills.
./trainOvernight.sh
# Or explicitly:
# caffeinate -dims ./trainOvernight.shEnv overrides: DURATION_HOURS (or DURATION_SECS for short tests), EPISODES, ROUNDS, BATCH, MODEL, SEED_MODEL, MAX_CONSECUTIVE_FAILURES.
Logs: logs/train-overnight-YYYYMMDD.log. PID file: logs/train-overnight.pid.
One-shot chunk without the loop (useful for debugging):
sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero train --episodes 2 --rounds 10 --batch 2"
# or, after assembly:
java -Xmx16G -Dorg.bytedeco.javacpp.nopointergc=true \
-Dorg.bytedeco.javacpp.maxbytes=8G -Dorg.bytedeco.javacpp.maxphysicalbytes=24G \
--enable-native-access=ALL-UNNAMED \
-jar target/scala-3.6.4/ScalphaGoZero-assembly-1.2.0.jar \
train --episodes 5 --rounds 25 --batch 5GTP loads model_size_<size>_layers_<n>.storch. Copy the trained file over (backup first):
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| Symptom | Meaning | What to do |
|---|---|---|
exit 137 |
SIGKILL (often native memory) | Lower EPISODES / ROUNDS; close other JVMs; keep chunked restarts |
SIGSEGV / exit 134 / Abort trap 6 |
Known flaky LibTorch crash (often at JVM startup) | Script quiet-retries up to STARTUP_RETRIES (default 8) before counting a hard failure |
Log stops after banner, no Attempt … OK/FAILED |
Job/sleep killed the shell before it could log | Use Terminal + caffeinate; check logs/train-overnight.pid |
No episode N/M lines |
Old fat jar or hung process | sbt assembly then restart script |
Agents/GTP talk to PolicyValueModel.
The default (and only) runtime backend is Storch (*.storch checkpoints under models/).
DL4J was removed from the classpath after a Storch-first spike; see docs/ml-backend-decision.md.
MCTS uses network-value leaves by default, Dirichlet noise + temperature on self-play, and a tanh value head in [-1, 1].
Legacy MC leaf eval remains behind useMcPlayout=true. See docs/agz-fidelity.md.
| Component | Version | Notes |
|---|---|---|
| Scala | 3.6.4 | Required to read storch_core TASTy (3.3 LTS cannot) |
| Storch | 0.7.6-1.5.12 | io.github.mullerhai:storch_core on Maven Central |
| LibTorch / OpenBLAS | 2.7.1-1.5.12 / 0.3.30-1.5.12 | JavaCPP natives; classifier matches host OS/arch |
| sbt | 1.11.7 | |
| Logback | 1.2.13 |
Quite a few concepts are needed to build an AlphaGoZero system, ScalphaGoZero is intended as a software developer friendly approach with clean abstractions to help users get started. Many of the concepts used here can be reused for other games, only the basics are really designed for the game of Go.
- Basics: To let a computer play a game you need to code the basics of the game, including what a Go board, a player, a move or the current game state is. Notably, the Zobrist hashing technique is implemented in the Go board class to speed up computation.
- Encoders:
Game states and moves need to be translated into something a neural network can
use for training and predictions, namely float tensors (
Array[Float]NCHW). AlphaGo Zero needs a specific ZeroEncoder, but many other encoders are feasible and can be implemented by the user. - Agents: A Go-playing agent knows how to play a game, by selecting the next move, and handles game state information internally. For AlphaGo Zero you need a ZeroAgent, but other agents with simpler methodology can also lead to decent results.
- Models:
To select a move, agents need machine learning models to predict the value of the current position (value function)
and how well a next move would probably work (policy function). In AlphaGo Zero both of these
components are integrated into one deep neural network, with a so called policy and value head.
The Dual ResNet lives in
DualResNetNetand is exposed throughStorchPolicyValueModel. - Scoring: To play actual games, agents need the ability to estimate scores at the end of a game to decide who won and reinforce the signals leading to victory (and weaken those leading to defeat). This includes territory estimation and reporting game results.
- Experience: When opponents play many games against each other, they generate game play data, or experience, that can be used for training the agents. We use experience collectors to store this information.
- Simulation:
The last piece needed to run your own AlphaGo Zero is to create a simulation between two
ZeroAgentinstances. The simulation stores experience data and lets your agents learn from it, so they become better players over time.
ScalphaGoZero can be improved in many ways, here are a few examples:
- Experience collectors still assemble full-episode batches in memory, which won't work for large experiments. This should be refactored into an iterator that only provides you with the next batch needed for training.
- Test coverage can be vastly improved. The basics are covered, but there are potentially many edge cases still missing.
- Running a larger experiment and storing the weights somewhere freely accessible to users would be beneficial to get started and see reasonable results from the start.
- Building a demo with a user interface would be nice. Agents could be wrapped in an HTTP server, for instance, and connect against a web interface so humans can play their bots.