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
2 changes: 1 addition & 1 deletion .bsp/sbt.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"name":"sbt","version":"1.11.7","bspVersion":"2.1.0-M1","languages":["scala"],"argv":["/Library/Java/JavaVirtualMachines/temurin-21.jdk/Contents/Home/bin/java","-Xms100m","-Xmx100m","-classpath","/Users/barry/Library/Application Support/JetBrains/IntelliJIdea2026.3/plugins/Scala/launcher/sbt-launch.jar","-Dsbt.script=/opt/homebrew/bin/sbt","xsbt.boot.Boot","-bsp"]}
{"name":"sbt","version":"1.11.7","bspVersion":"2.1.0-M1","languages":["scala"],"argv":["E:\\apps\\Java\\java-21\\jdk-21.0.10.7-hotspot/bin/java","-Xms100m","-Xmx100m","-classpath","C:\\Users\\barry\\AppData\\Local\\Coursier\\cache\\arc\\https\\github.com\\sbt\\sbt\\releases\\download\\v1.10.10\\sbt-1.10.10.zip\\sbt\\bin\\sbt-launch.jar","-Dsbt.script=C:\\Users\\barry\\AppData\\Local\\Coursier\\cache\\arc\\https\\github.com\\sbt\\sbt\\releases\\download\\v1.10.10\\sbt-1.10.10.zip\\sbt\\bin\\sbt.bat","xsbt.boot.Boot","-bsp"]}
19 changes: 18 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,18 @@ lazy val cudaLoaderFlags: Seq[String] =
"-Dorg.bytedeco.javacpp.cachedir=target/javacpp-cuda"
)

// Temurin 21.0.10's C1 compiler access-violates in jvm.dll while compiling
// storch / JavaCPP methods (Tensor.fromNative, ClassProperties.addAll, …).
// Oracle JDK 17.0.6 is installed on this Windows box; fork the app onto it.
// Override with SCALPHAGO_JAVA_HOME. Missing directory keeps sbt's own JVM.
lazy val forkJavaHome: Option[File] = {
val candidate = sys.env.get("SCALPHAGO_JAVA_HOME") match {
case Some(path) => file(path)
case None => file("E:/apps/Java/jdk-17")
}
if (candidate.exists) Some(candidate) else None
}

lazy val jvmOpenFlags = Seq(
"--add-opens=java.base/java.util=ALL-UNNAMED",
"--add-opens=java.base/java.lang=ALL-UNNAMED",
Expand All @@ -106,18 +118,23 @@ lazy val jvmOpenFlags = Seq(
)

Compile / run / fork := true
Compile / run / javaHome := forkJavaHome
Compile / run / javaOptions ++= Seq(
// Overnight / 9x9 self-play: generous heap + native budget on 48G hosts.
"-Xms4G",
"-Xmx16G",
"-Dorg.bytedeco.javacpp.nopointergc=true",
"-Dorg.bytedeco.javacpp.maxbytes=8G",
"-Dorg.bytedeco.javacpp.maxphysicalbytes=24G"
) ++ jvmOpenFlags ++ cudaLoaderFlags
) ++ jvmOpenFlags ++ cudaLoaderFlags ++ (
// Temurin 21.0.10 access-violates in jvm.dll while compiling the checkpoint load.
if (sys.env.get("SCALPHAGO_XINT").contains("1")) Seq("-Xint") else Nil
)

// Soft coverage only — no coverageMinimum / failOnMinimum (see docs/testing.md).

Test / fork := true
Test / javaHome := forkJavaHome
Test / parallelExecution := false
Global / concurrentRestrictions += Tags.limit(Tags.Test, 1)
Test / javaOptions ++= Seq(
Expand Down
22 changes: 22 additions & 0 deletions docs/overnight-training.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,25 @@ sbt "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero eval"
| 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 |
| Activity Monitor shows Physical Memory **0 bytes** / huge Swap | UI glitch after thrash; not ground truth | Quit/reopen Activity Monitor; trust `vm_stat` / `sysctl vm.swapusage` |

## Gated generation (Windows, Git Bash)

This is the run that can show a strength gain in one sitting. It does not use `trainOvernight.bat`. The seed and `model_size_9_layers_3_trained.storch` are not overwritten.

Smoke (a few minutes). Confirms the forked JVM is 17.0.6 and that a loss line appears. `SKIP_EVAL=1` skips the 40-game match.

```bash
cd /e/projects/scala_projects/ScalphaGoZero
export MSYS_NO_PATHCONV=1
GAMES=8 STEPS=2 MINIBATCH=32 SKIP_EVAL=1 bash generate-generation.sh
```

Full generation (about 15 minutes of self-play plus about one hour of CPU eval):

```bash
cd /e/projects/scala_projects/ScalphaGoZero
export MSYS_NO_PATHCONV=1
bash generate-generation.sh
```

Read `logs/generation-eval.log` for `eval done: challengerWins=W/40`. At 26 or more, the script copies the candidate to `models/promoted/gen-<timestamp>.storch` and prints the next `PARENT=...` command. Below 26 it deletes the candidate. A second rejection prints `Two generations were already rejected` and exits. Reset with `echo 0 > logs/generation-rejects` only after changing the learning rule.
68 changes: 68 additions & 0 deletions generate-generation.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# One gated generation. Git Bash on Windows. Does not call trainOvernight.
set -u
cd "$(dirname "$0")"
export MSYS_NO_PATHCONV=1

PARENT="${PARENT:-models/model_size_9_layers_3.storch}"
CANDIDATE="${CANDIDATE:-models/model_size_9_layers_3_candidate.storch}"
GAMES="${GAMES:-256}"
STEPS="${STEPS:-100}"
MINIBATCH="${MINIBATCH:-512}"
ROUNDS="${ROUNDS:-100}"
EVAL_GAMES="${EVAL_GAMES:-40}"
PROMOTE_WINS="${PROMOTE_WINS:-26}"
REJECTS_FILE=logs/generation-rejects

mkdir -p logs models/promoted
if [[ -f "$REJECTS_FILE" ]]; then
REJECTS="$(tr -d '[:space:]' < "$REJECTS_FILE")"
else
REJECTS=0
fi
if [[ "${REJECTS}" -ge 2 ]]; then
echo "Two generations were already rejected. Stopping."
exit 3
fi

echo "parent=$PARENT"
echo "candidate=$CANDIDATE"
echo "games=$GAMES steps=$STEPS minibatch=$MINIBATCH rounds=$ROUNDS"

sbt -Dscalphago.cuda=true "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero generate --parent ${PARENT} --candidate ${CANDIDATE} --games ${GAMES} --steps ${STEPS} --minibatch ${MINIBATCH} --rounds ${ROUNDS} --parallel-games 8 --eval-batch 16 --seed 1" \
| tee logs/generation-train.log
if ! grep -q "generate result=loss-dropped" logs/generation-train.log; then
echo "Loss did not fall, or generate did not finish. No eval."
exit 2
fi
if ! grep -q "java=17.0.6" logs/generation-train.log; then
echo "Expected the forked JVM to be 17.0.6. See logs/generation-train.log."
exit 4
fi
if [[ "${SKIP_EVAL:-0}" == "1" ]]; then
echo "SKIP_EVAL=1, not playing the 40 games."
exit 0
fi

sbt -Dscalphago.cuda=true "runMain org.deeplearning4j.scalphagozero.app.ScalphaGoZero eval --challenger ${CANDIDATE} --opponent ${PARENT} --games ${EVAL_GAMES} --rounds ${ROUNDS} --seed 1" \
| tee logs/generation-eval.log
WINS="$(sed -n 's/.*challengerWins=\([0-9][0-9]*\)\/.*/\1/p' logs/generation-eval.log | tail -n 1)"
if [[ -z "${WINS}" ]]; then
echo "Eval did not print challengerWins. See logs/generation-eval.log."
exit 1
fi
echo "challengerWins=${WINS}/${EVAL_GAMES}"

if [[ "${WINS}" -ge "${PROMOTE_WINS}" ]]; then
STAMP="$(date -u +%Y%m%d-%H%M%S)"
DEST="models/promoted/gen-${STAMP}.storch"
cp "${CANDIDATE}" "${DEST}"
echo 0 > "${REJECTS_FILE}"
echo "Promoted to ${DEST}"
echo "Next parent: PARENT=${DEST} bash generate-generation.sh"
else
REJECTS="$((REJECTS + 1))"
echo "${REJECTS}" > "${REJECTS_FILE}"
rm -f "${CANDIDATE}"
echo "Rejected ${WINS}/${EVAL_GAMES}. Consecutive rejects=${REJECTS}."
fi
Binary file modified models/model_size_9_layers_3_trained.storch
Binary file not shown.
1 change: 1 addition & 0 deletions performance/benchmark-results.csv
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ date,configName,ScalphaGoVersion,gitSha,scalaVersion,nd4jVersion,OS,CPU,GPU,numC
2026-11-26,"A","1.2.0","e4dc9cc","3.6.4","0.7.6-1.5.12","Mac OS X aarch64","aarch64","none/cpu",14,8192,5,2,5,50,20,23.35,0.58,1.17,0.15,23.93,513,10,5,5,0.5000,"phase10-finale-1.2.0;backend=Storch;quiet-selfplay"
2026-12-01,"smoke","1.2.0","9de3b03","3.6.4","0.7.6-1.5.12","Windows 10 amd64","Intel64 Family 6 Model 94 Stepping 3, GenuineIntel","none/cpu",8,16384,5,2,2,20,4,114.01,0.27,28.50,0.14,114.28,114,2,2,0,1.0000,"phase10-finale-1.2.0;backend=Storch;quiet-selfplay",1,1,"cpu"
2026-12-01,"smoke","1.2.0","9de3b03","3.6.4","0.7.6-1.5.12","Windows 10 amd64","Intel64 Family 6 Model 94 Stepping 3, GenuineIntel","none/cpu",8,16384,5,2,2,20,4,2.73,0.43,0.68,0.21,3.16,138,2,2,0,1.0000,"phase10-finale-1.2.0;backend=Storch;quiet-selfplay",8,4,"cuda"
2026-12-02,"smoke","1.2.0","99fd262","3.6.4","0.7.6-1.5.12","Windows 10 amd64","Intel64 Family 6 Model 94 Stepping 3, GenuineIntel","none/cpu",8,16384,9,3,8,50,8,18.86,0.54,2.36,0.54,19.40,2296,0,0,0,0.0000,"phase10-finale-1.2.0;backend=Storch;quiet-selfplay",8,4,"cuda"
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package org.deeplearning4j.scalphagozero.agents

import org.deeplearning4j.scalphagozero.board.{ GameState, Move }
import org.deeplearning4j.scalphagozero.encoders.ZeroEncoder
import org.deeplearning4j.scalphagozero.experience.{ ZeroExperienceBuffer, ZeroExperienceCollector }
import org.deeplearning4j.scalphagozero.ml.{ InferenceService, PolicyValueModel, Prediction, TrainingBatch }
import org.deeplearning4j.scalphagozero.experience.{ ExperienceTargets, ZeroExperienceBuffer, ZeroExperienceCollector }
import org.deeplearning4j.scalphagozero.ml.{ InferenceService, PolicyValueModel, Prediction }
import org.deeplearning4j.scalphagozero.util.ObjectSizer

import scala.compiletime.uninitialized
Expand Down Expand Up @@ -291,41 +291,12 @@ class ZeroAgent(
}

def train(experience: ZeroExperienceBuffer): Unit = {
val numExamples = experience.numExamples
val numMoves = experience.visitShape(1)
val policyTarget = new Array[Float](numExamples * numMoves)

for (i <- 0 until numExamples) {
var sum = 0f
val base = i * numMoves
var j = 0
while (j < numMoves) {
sum += experience.visitCounts(base + j)
j += 1
}
val denom = if (sum == 0f) 1f else sum
j = 0
while (j < numMoves) {
policyTarget(base + j) = experience.visitCounts(base + j) / denom
j += 1
}
}

if (DEBUG) {
println("numExamples: " + numExamples)
println("numExamples: " + experience.numExamples)
println("The size of the modelInput (experience) is: " + ObjectSizer.getSizeKB(experience.states))
println("model size before fit: " + ObjectSizer.getSizeKB(model))
}

model.fit(
TrainingBatch(
states = experience.states,
stateShape = experience.stateShape,
policyTarget = policyTarget,
valueTarget = experience.rewards
)
)

model.fit(ExperienceTargets.toBatch(experience))
if (DEBUG) {
println("model size after fit: " + ObjectSizer.getSizeKB(model))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ 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}
import org.deeplearning4j.scalphagozero.ml.MlBackend
import org.deeplearning4j.scalphagozero.ml.storch.StorchPolicyValueModel

/**
* Non-interactive frozen-model strength eval: challenger vs opponent via [[StrengthProxy]].
Expand Down Expand Up @@ -38,8 +39,16 @@ object EvalRunner {
println(s"opponent=$opponentPath")
System.out.flush()

val challenger = PolicyValueModels.load(backend, challengerPath)
val opponent = PolicyValueModels.load(backend, opponentPath)
val (challenger, opponent) = backend match {
case MlBackend.Storch =>
// Weights are copied on the module before either net is moved.
// One GPU then holds both, which is the fast match.
StorchPolicyValueModel.loadPair(challengerPath, opponentPath, None)
case MlBackend.Dl4j =>
throw new UnsupportedOperationException(
"DL4J backend removed from the main classpath. Use the Storch checkpoints."
)
}

val result = StrengthProxy.evaluate(
challengerModel = challenger,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.deeplearning4j.scalphagozero.app

/** Decisions the generation script can make without loading a network. */
object GenerationGate {

def lossDropped(first: Double, last: Double): Boolean =
java.lang.Double.isFinite(first) && java.lang.Double.isFinite(last) && last < first

def promote(wins: Int, games: Int, requiredWins: Int): Boolean = {
require(games > 0, "games must be positive")
require(requiredWins >= 0 && requiredWins <= games, s"requiredWins $requiredWins not in 0..$games")
wins >= requiredWins
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package org.deeplearning4j.scalphagozero.app

import java.nio.file.{Files, Path, StandardCopyOption}

import org.deeplearning4j.scalphagozero.agents.ZeroAgent
import org.deeplearning4j.scalphagozero.app.config.GenerationConfigParser
import org.deeplearning4j.scalphagozero.encoders.ZeroEncoder
import org.deeplearning4j.scalphagozero.experience.{ExperienceTargets, ZeroExperienceBuffer}
import org.deeplearning4j.scalphagozero.ml.{BatchSlicer, InferenceService, MlBackend}
import org.deeplearning4j.scalphagozero.ml.storch.StorchPolicyValueModel

import scala.util.Random

object GenerationRunner {

def run(args: Array[String]): Unit = {
val config = GenerationConfigParser.parse(args)
val parent = Path.of(config.parentPath)
val candidate = Path.of(config.candidatePath)
if (!Files.exists(parent)) {
System.err.println(s"Parent model not found: $parent")
Runtime.getRuntime.halt(1)
}
val backend = MlBackend.fromEnvOrDefault
if (backend != MlBackend.Storch) {
System.err.println("generate requires the Storch backend")
Runtime.getRuntime.halt(1)
}
val encoder = ZeroEncoder(config.boardSize)
val model = StorchPolicyValueModel
.load(parent, None, config.learningRate)
.asInstanceOf[StorchPolicyValueModel]
println(
s"=== ScalphaGoZero generate parent=$parent candidate=$candidate " +
s"games=${config.games} rounds=${config.roundsPerMove} steps=${config.steps} " +
s"minibatch=${config.minibatch} lr=${config.learningRate} ==="
)
System.out.flush()

val service =
if (config.evalBatchSize > 1 || config.parallelGames > 1)
Some(new InferenceService(model, config.evalBatchSize, config.parallelGames))
else None

val collectors = Trainer(batchSize = config.games).collectEpisodes(
episodes = config.games,
makeAgents = { i =>
val black = ZeroAgent.forSelfPlay(
model, encoder, config.roundsPerMove,
rand = new Random(config.seed + 2L * i),
evalBatchSize = config.evalBatchSize,
inference = service
)
val white = ZeroAgent.forSelfPlay(
model, encoder, config.roundsPerMove,
rand = new Random(config.seed + 2L * i + 1),
evalBatchSize = config.evalBatchSize,
inference = service
)
(black, white)
},
parallelGames = config.parallelGames,
inference = service,
progress = true
)
val experience = ZeroExperienceBuffer.combineExperience(
collectors,
stateCHWShape = Array(encoder.numPlanes, encoder.boardSize, encoder.boardSize)
)
val batch = ExperienceTargets.toBatch(experience)
val rng = new Random(config.seed)
val n = batch.stateShape(0)
var first = Double.NaN
var last = Double.NaN
var step = 0
while (step < config.steps) {
val take = math.min(config.minibatch, n)
val offset = if (n <= take) 0 else rng.nextInt(n - take + 1)
val loss = model.fitLoss(BatchSlicer.slice(batch, offset, take))
if (step == 0) first = loss
last = loss
println(f"step ${step + 1}/${config.steps} loss=$loss%.6f examples=$n")
System.out.flush()
step += 1
}
println(f"loss first=$first%.6f last=$last%.6f")
if (!GenerationGate.lossDropped(first, last)) {
println("generate result=loss-flat")
System.out.flush()
Runtime.getRuntime.halt(2)
}
val parentDir = candidate.getParent
if (parentDir != null) {
val _ = Files.createDirectories(parentDir)
}
val tmp = Path.of(candidate.toString + ".tmp")
model.save(tmp)
val _ = Files.move(tmp, candidate, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
println(s"candidate saved: $candidate")
println("generate result=loss-dropped")
System.out.flush()
Runtime.getRuntime.halt(0)
}
}
Loading
Loading