diff --git a/.bsp/sbt.json b/.bsp/sbt.json index 9596587..b291d2f 100644 --- a/.bsp/sbt.json +++ b/.bsp/sbt.json @@ -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"]} \ No newline at end of file +{"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"]} \ No newline at end of file diff --git a/build.sbt b/build.sbt index 0483700..b11b354 100644 --- a/build.sbt +++ b/build.sbt @@ -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", @@ -106,6 +118,7 @@ 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", @@ -113,11 +126,15 @@ Compile / run / javaOptions ++= Seq( "-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( diff --git a/docs/overnight-training.md b/docs/overnight-training.md index 6a5c2c5..f921ad7 100644 --- a/docs/overnight-training.md +++ b/docs/overnight-training.md @@ -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-.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. diff --git a/generate-generation.sh b/generate-generation.sh new file mode 100644 index 0000000..ada526d --- /dev/null +++ b/generate-generation.sh @@ -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 \ No newline at end of file diff --git a/models/model_size_9_layers_3_trained.storch b/models/model_size_9_layers_3_trained.storch index 4efc9b8..5ffe038 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/performance/benchmark-results.csv b/performance/benchmark-results.csv index a981aab..828cbbc 100644 --- a/performance/benchmark-results.csv +++ b/performance/benchmark-results.csv @@ -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" diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala b/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala index 45f91a0..a229e0e 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/agents/ZeroAgent.scala @@ -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 @@ -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)) } diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala index c085df8..094eeb3 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/EvalRunner.scala @@ -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]]. @@ -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, diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/GenerationGate.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/GenerationGate.scala new file mode 100644 index 0000000..6e8a82a --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/GenerationGate.scala @@ -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 + } +} \ No newline at end of file diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/GenerationRunner.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/GenerationRunner.scala new file mode 100644 index 0000000..6a3d834 --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/GenerationRunner.scala @@ -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) + } +} \ No newline at end of file diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala index ae8c841..2727d79 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/ScalphaGoZero.scala @@ -1,6 +1,7 @@ package org.deeplearning4j.scalphagozero.app import org.deeplearning4j.scalphagozero.benchmark.BenchmarkRunner +import org.deeplearning4j.scalphagozero.ml.storch.CudaBootstrap /** * Entry point: @@ -22,20 +23,62 @@ object ScalphaGoZero { () } - private def configureJavaCpp(): Unit = { + private def configureJavaCpp(preloadCuda: Boolean): Unit = { setDefaultProperty("org.bytedeco.javacpp.nopointergc", "true") setDefaultProperty("org.bytedeco.javacpp.maxbytes", "2G") setDefaultProperty("org.bytedeco.javacpp.maxphysicalbytes", "6G") // Fat-jar assembly may drop Log4j plugin metadata; silence StatusLogger when using Logback. setDefaultProperty("log4j2.statusLoggerLevel", "OFF") + // Eval compares frozen weights and must not call cudaSetDevice. Doing that before + // the state dict is applied crashes this JDK inside the C2 compiler. + if (preloadCuda) CudaBootstrap.preload() + } + + private val interpreterModes: Set[String] = Set("eval", "generate", "train") + + /** + * Temurin 21.0.10 access-violates in jvm.dll while compiling the checkpoint load. + * Restart eval, generate, and train in the interpreter before any LibTorch class initializes. + * The GPU matmul still runs; only the Java compiler is off. + */ + private def restartEvalInInterpreter(argv: Array[String]): Unit = { + if (!argv.headOption.exists(interpreterModes.contains)) return + if (!System.getProperty("java.version", "").startsWith("21.")) return + val vmArgs = java.lang.management.ManagementFactory.getRuntimeMXBean.getInputArguments + if (vmArgs.contains("-Xint")) { + println("runtime=interpreter") + return + } + val exeName = if (System.getProperty("os.name", "").toLowerCase.contains("win")) "java.exe" else "java" + val javaBin = java.nio.file.Path.of(System.getProperty("java.home"), "bin", exeName).toString + val cmd = new java.util.ArrayList[String]() + cmd.add(javaBin) + val vmIt = vmArgs.iterator() + while (vmIt.hasNext) { + val _ = cmd.add(vmIt.next()) + } + cmd.add("-Xint") + cmd.add("-cp") + cmd.add(System.getProperty("java.class.path")) + cmd.add("org.deeplearning4j.scalphagozero.app.ScalphaGoZero") + argv.foreach(cmd.add) + val child = new ProcessBuilder(cmd).inheritIO().start() + sys.exit(child.waitFor()) } def main(args: Array[String]): Unit = { - configureJavaCpp() val argv = Option(args).getOrElse(Array.empty[String]) + restartEvalInInterpreter(argv) + configureJavaCpp(preloadCuda = !argv.headOption.contains("eval")) // Never print to stdout in gtp mode — Sabaki parses stdout as GTP and warning-icons any junk. - if (argv.headOption.contains("gtp")) System.err.println("args = " + argv.mkString(", ")) - else println("args = " + argv.mkString(", ")) + val javaDesc = s"java=${System.getProperty("java.version")} ${System.getProperty("java.vm.name")}" + if (argv.headOption.contains("gtp")) { + System.err.println("args = " + argv.mkString(", ")) + System.err.println(javaDesc) + } else { + println("args = " + argv.mkString(", ")) + println(javaDesc) + } if (argv.isEmpty) { new Demo().run() } else @@ -49,8 +92,10 @@ object ScalphaGoZero { TrainRunner.run(argv.drop(1)) case "eval" => EvalRunner.run(argv.drop(1)) + case "generate" => + GenerationRunner.run(argv.drop(1)) case other => - System.err.println(s"Unknown mode '$other'. Use no args (demo), 'gtp', 'benchmark', 'train', or 'eval'.") + System.err.println(s"Unknown mode '$other'. Use no args (demo), 'gtp', 'benchmark', 'train', 'eval', or 'generate'.") sys.exit(1) } } diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/Trainer.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/Trainer.scala index fc9ec17..9827e4e 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/app/Trainer.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/Trainer.scala @@ -3,7 +3,7 @@ package org.deeplearning4j.scalphagozero.app import java.util.concurrent.ConcurrentLinkedQueue import org.deeplearning4j.scalphagozero.agents.ZeroAgent -import org.deeplearning4j.scalphagozero.experience.ZeroExperienceBuffer +import org.deeplearning4j.scalphagozero.experience.{ZeroExperienceBuffer, ZeroExperienceCollector} import org.deeplearning4j.scalphagozero.ml.InferenceService import org.deeplearning4j.scalphagozero.simulation.ZeroSimulator /** @@ -68,6 +68,40 @@ case class Trainer(batchSize: Int = Trainer.DEFAULT_BATCH_SIZE) { stats } + def collectEpisodes( + episodes: Int, + makeAgents: Int => (ZeroAgent, ZeroAgent), + parallelGames: Int, + inference: Option[InferenceService], + progress: Boolean + ): List[ZeroExperienceCollector] = { + require(parallelGames > 0, "parallelGames must be positive") + val collectors = scala.collection.mutable.ListBuffer.empty[ZeroExperienceCollector] + try { + var nextGame = 0 + while (nextGame < episodes) { + val wave = math.min(parallelGames, episodes - nextGame) + val agents = (0 until wave).map { j => + val index = nextGame + j + if (progress) { + println(s"episode ${index + 1}/$episodes") + System.out.flush() + } + makeAgents(index) + } + playWave(agents, verbose = false) + agents.foreach { case (black, white) => + val bc = black.retrieveAndClearCollector() + val wc = white.retrieveAndClearCollector() + if (bc.states.nonEmpty) collectors += bc + if (wc.states.nonEmpty) collectors += wc + } + nextGame += wave + } + } finally inference.foreach(_.close()) + collectors.toList + } + private def playWave(agents: Seq[(ZeroAgent, ZeroAgent)], verbose: Boolean): Unit = { val errors = new ConcurrentLinkedQueue[Throwable]() val threads = agents.map { case (black, white) => diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfig.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfig.scala new file mode 100644 index 0000000..5a5c9da --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfig.scala @@ -0,0 +1,16 @@ +package org.deeplearning4j.scalphagozero.app.config + +final case class GenerationConfig( + parentPath: String = "models/model_size_9_layers_3.storch", + candidatePath: String = "models/model_size_9_layers_3_candidate.storch", + boardSize: Int = 9, + blocks: Int = 3, + roundsPerMove: Int = 100, + games: Int = 256, + parallelGames: Int = 8, + evalBatchSize: Int = 16, + minibatch: Int = 512, + steps: Int = 100, + learningRate: Double = 0.001, + seed: Long = 1L +) \ No newline at end of file diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfigParser.scala b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfigParser.scala new file mode 100644 index 0000000..407857b --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfigParser.scala @@ -0,0 +1,61 @@ +package org.deeplearning4j.scalphagozero.app.config + +/** Parses `generate` CLI flags into a [[GenerationConfig]]. */ +object GenerationConfigParser { + + def parse(args: Array[String]): GenerationConfig = { + var config = GenerationConfig() + var i = 0 + while (i < args.length) { + args(i) match { + case "--parent" => + require(i + 1 < args.length, "--parent requires a path") + config = config.copy(parentPath = args(i + 1)); i += 2 + case "--candidate" => + require(i + 1 < args.length, "--candidate requires a path") + config = config.copy(candidatePath = args(i + 1)); i += 2 + 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 "--parallel-games" => + require(i + 1 < args.length, "--parallel-games requires a value") + config = config.copy(parallelGames = args(i + 1).toInt); i += 2 + case "--eval-batch" => + require(i + 1 < args.length, "--eval-batch requires a value") + config = config.copy(evalBatchSize = args(i + 1).toInt); i += 2 + case "--minibatch" => + require(i + 1 < args.length, "--minibatch requires a value") + config = config.copy(minibatch = args(i + 1).toInt); i += 2 + case "--steps" => + require(i + 1 < args.length, "--steps requires a value") + config = config.copy(steps = args(i + 1).toInt); i += 2 + case "--lr" => + require(i + 1 < args.length, "--lr requires a value") + config = config.copy(learningRate = args(i + 1).toDouble); 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 => + require(false, s"unknown flag $other") + } + } + require(config.games > 0, "games must be positive") + require(config.steps > 0, "steps must be positive") + require(config.minibatch > 0, "minibatch must be positive") + require(config.learningRate > 0, "lr must be positive") + require( + config.parentPath != config.candidatePath, + s"candidate must not overwrite parent (${config.parentPath})" + ) + config + } +} \ No newline at end of file diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/experience/ExperienceTargets.scala b/src/main/scala/org/deeplearning4j/scalphagozero/experience/ExperienceTargets.scala new file mode 100644 index 0000000..7e34e20 --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/experience/ExperienceTargets.scala @@ -0,0 +1,36 @@ +package org.deeplearning4j.scalphagozero.experience + +import org.deeplearning4j.scalphagozero.ml.TrainingBatch + +/** Visit counts become a probability target. No LibTorch. */ +object ExperienceTargets { + + def toBatch(experience: ZeroExperienceBuffer): TrainingBatch = { + val numExamples = experience.numExamples + val numMoves = experience.visitShape(1) + val policyTarget = new Array[Float](numExamples * numMoves) + var i = 0 + while (i < 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 + } + i += 1 + } + TrainingBatch( + states = experience.states, + stateShape = experience.stateShape, + policyTarget = policyTarget, + valueTarget = experience.rewards + ) + } +} \ No newline at end of file diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/ml/BatchSlicer.scala b/src/main/scala/org/deeplearning4j/scalphagozero/ml/BatchSlicer.scala new file mode 100644 index 0000000..4d9c00b --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/ml/BatchSlicer.scala @@ -0,0 +1,21 @@ +package org.deeplearning4j.scalphagozero.ml + +import java.util.Arrays + +/** Row slice of a packed NCHW [[TrainingBatch]]. Does not touch LibTorch. */ +object BatchSlicer { + + def slice(batch: TrainingBatch, offset: Int, count: Int): TrainingBatch = { + val n = batch.stateShape(0) + require(offset >= 0 && offset < n, s"offset $offset out of range for n=$n") + require(count > 0, "count must be positive") + val take = math.min(count, n - offset) + require(take > 0, "empty slice") + val chw = batch.states.length / n + val moves = batch.policyTarget.length / n + val states = Arrays.copyOfRange(batch.states, offset * chw, (offset + take) * chw) + val policy = Arrays.copyOfRange(batch.policyTarget, offset * moves, (offset + take) * moves) + val value = Arrays.copyOfRange(batch.valueTarget, offset, offset + take) + TrainingBatch(states, batch.stateShape.updated(0, take), policy, value) + } +} \ No newline at end of file diff --git a/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/CudaBootstrap.scala b/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/CudaBootstrap.scala new file mode 100644 index 0000000..fb6c923 --- /dev/null +++ b/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/CudaBootstrap.scala @@ -0,0 +1,53 @@ +package org.deeplearning4j.scalphagozero.ml.storch + +import java.util.concurrent.atomic.AtomicBoolean + +import org.bytedeco.javacpp.Loader + +/** + * Map the CUDA runtime and `torch_cuda` before any `torch.*` class initializes. + * + * On Windows the GPU LibTorch jar also contains `torch_cpu`. The first touch of + * `org.bytedeco.pytorch.global.torch` loads that CPU entry point, caches + * `cuda_is_available` as false, and later `LoadLibrary` of `c10_cuda.dll` does + * not change the answer. Preloading the CUDA DLLs, then `torch_cuda`, makes + * the same process report the device. A JVM without + * `org.bytedeco.javacpp.platform.extension=-gpu` skips this and stays on CPU. + */ +object CudaBootstrap { + + private val loaded = new AtomicBoolean(false) + + private val classes: Array[String] = Array( + "org.bytedeco.cuda.global.cudart", + "org.bytedeco.cuda.global.cublas", + "org.bytedeco.cuda.global.cudnn", + "org.bytedeco.pytorch.global.torch_cuda" + ) + + def preload(): Unit = { + if (!loaded.compareAndSet(false, true)) return + val extension = System.getProperty("org.bytedeco.javacpp.platform.extension", "") + if (!extension.contains("gpu")) return + classes.foreach { name => + try { + val _ = Loader.load(Class.forName(name)) + } catch { + case t: Throwable => + System.err.println( + s"CUDA preload failed for $name: ${t.getClass.getSimpleName}: ${t.getMessage}" + ) + } + } + // Make device 0 current before any Module.to. A cold context plus device index -1 + // crashes inside LibTorch's Module.to on this Windows build. + try { + val rc = org.bytedeco.cuda.global.cudart.cudaSetDevice(0) + if (rc != 0) + System.err.println(s"cudaSetDevice(0) returned $rc") + } catch { + case t: Throwable => + System.err.println(s"cudaSetDevice(0) failed: ${t.getClass.getSimpleName}: ${t.getMessage}") + } + } +} 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 1d2dd71..62f06e0 100644 --- a/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/StorchPolicyValueModel.scala +++ b/src/main/scala/org/deeplearning4j/scalphagozero/ml/storch/StorchPolicyValueModel.scala @@ -5,8 +5,12 @@ import java.nio.file.Path import org.bytedeco.javacpp.PointerScope import org.deeplearning4j.scalphagozero.ml.{ ComputeDevice, PolicyValueModel, Prediction, TrainingBatch } -import torch.{Default, Device, Float32, Tensor} +import torch.{Default, Device, DeviceType, Float32, Tensor} import torch.nn.functional as F +import torch.nn.modules.Module +import torch.nn.modules.batchnorm.BatchNorm2d +import torch.nn.modules.conv.Conv2d +import torch.nn.modules.linear.Linear import torch.optim.Adam /** @@ -25,10 +29,12 @@ final class StorchPolicyValueModel private ( private val torchDevice: Device = computeDevice match { case ComputeDevice.Cpu => Device.CPU - case ComputeDevice.Cuda => Device.CUDA + case ComputeDevice.Cuda => StorchPolicyValueModel.CudaDevice } - private val optimizer = Adam(net.parameters(true), lr = learningRate) + // Built on the first fit. Constructing it during load walks every CUDA parameter through + // JavaCPP and has been corrupting the heap before eval reaches its first game. + private lazy val optimizer = Adam(net.parameters(true), lr = learningRate) override def deviceName: String = computeDevice match { case ComputeDevice.Cpu => "cpu" @@ -66,8 +72,12 @@ final class StorchPolicyValueModel private ( } finally scope.close() } - override def fit(batch: TrainingBatch): Unit = + def fitLoss(batch: TrainingBatch): Double = StorchPolicyValueModel.NativeLock.synchronized { + // Create Adam before any PointerScope. The first touch inside a scope + // retains the optimizer, and close() then frees it, so later steps in + // the same generation run on a deallocated Adam. + val opt = optimizer val scope = new PointerScope() try { val n = batch.stateShape(0) @@ -78,27 +88,28 @@ final class StorchPolicyValueModel private ( ) 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 policyTarget = toTensor(batch.policyTarget, Array(n, expectedMoves)) val valueTarget = toTensor(batch.valueTarget, Array(n, 1)) - - optimizer.zeroGrad() + opt.zeroGrad() val (policyLogits, valueLogits) = net.forward(x) val logProbs = F.log_softmax(policyLogits, dim = 1) - // Soft cross-entropy: -sum(π * log p) / N val policyLoss = -(policyTarget * logProbs).sum() / n.toDouble val valuePred = torch.tanh(valueLogits) val valueLoss = F.mse_loss(valuePred, valueTarget) val loss = policyLoss + valueLoss loss.backward() - optimizer.step() - () + opt.step() + doubles(loss.cpu().flatten()).head } finally scope.close() } + override def fit(batch: TrainingBatch): Unit = { + val _ = fitLoss(batch) + } + override def save(path: Path): Unit = StorchPolicyValueModel.NativeLock.synchronized { - val dict = net.state_dict() + val dict = StorchPolicyValueModel.snapshotState(net) val out = new DataOutputStream(new FileOutputStream(path.toFile)) try { out.writeUTF("scalphago-storch-v1") @@ -123,7 +134,7 @@ final class StorchPolicyValueModel private ( /** Expose parameter snapshot for tests. */ def paramFingerprint(limit: Int = 64): Array[Double] = { - val params = net.parameters(true).flatMap { t => + val params = StorchPolicyValueModel.snapshotState(net).values.flatMap { t => doubles(t.cpu().flatten()) } params.take(limit).toArray @@ -146,17 +157,85 @@ final class StorchPolicyValueModel private ( object StorchPolicyValueModel { + /** + * Index 0, not [[Device.CUDA]]. That constant uses index -1 ("current device"). + * `Module.to` on this JavaCPP build reads that -1 as a pointer and access-violates + * at 0xffffffffffffffff when the CUDA context is not already current. + * Lazy: constructing it initializes CUDA, which eval must not do. + */ + private[storch] lazy val CudaDevice: Device = Device(DeviceType.CUDA, 0.toByte) + private val DefaultLr = 0.01 /** LibTorch / JavaCPP is not safe for concurrent Module construction in one JVM. */ private[storch] val NativeLock = new Object + /** + * Parameters by layer type. `named_parameters` access-violates on this LibTorch + * once CUDA is initialized, including the non-recursive call. + */ + private def directTensors(module: Module): Seq[(String, Tensor[?])] = module match { + case conv: Conv2d[?] => + Seq("weight" -> conv.weight) + case linear: Linear[?] => + Seq("weight" -> linear.weight, "bias" -> linear.bias) + case bn: BatchNorm2d[?] => + Seq( + "weight" -> bn.weight, + "bias" -> bn.bias, + "running_mean" -> bn.running_mean(), + "running_var" -> bn.running_var(), + "num_batches_tracked" -> bn.num_batches_tracked() + ) + case _ => Nil + } + + private[storch] def snapshotState(root: Module): Map[String, Tensor[?]] = { + val acc = scala.collection.mutable.LinkedHashMap.empty[String, Tensor[?]] + def walk(module: Module, prefix: String): Unit = { + directTensors(module).foreach { case (name, tensor) => + val key = if (prefix.isEmpty) name else s"$prefix.$name" + acc(key) = tensor + } + module.namedChildren.foreach { case (child, sub) => + val next = if (prefix.isEmpty) child else s"$prefix.$child" + walk(sub, next) + } + } + walk(root, "") + acc.toMap + } + + private[storch] def copyStateDict(root: Module, state: Map[String, Tensor[?]]): Unit = { + val copied = scala.collection.mutable.Set.empty[String] + def walk(module: Module, prefix: String): Unit = { + directTensors(module).foreach { case (name, param) => + val key = if (prefix.isEmpty) name else s"$prefix.$name" + state.get(key).foreach { value => + torch.noGrad { val _ = param.copy_(value) } + val _ = copied.add(key) + } + } + module.namedChildren.foreach { case (child, sub) => + val next = if (prefix.isEmpty) child else s"$prefix.$child" + walk(sub, next) + } + } + walk(root, "") + val missing = state.keySet -- copied + require( + missing.isEmpty, + s"checkpoint keys not found on the module: ${missing.toSeq.sorted.take(12).mkString(", ")}" + ) + } + def create( blocks: Int, planes: Int, boardSize: Int, device: Option[ComputeDevice] = None ): PolicyValueModel = NativeLock.synchronized { + prepareNative(device) given Default[Float32] = Default.float32 // Resolve the device before the first module walk so CUDA is initialized. val resolved = resolveDevice(device) @@ -165,9 +244,43 @@ object StorchPolicyValueModel { new StorchPolicyValueModel(net, DefaultLr, resolved) } - def load(path: Path, device: Option[ComputeDevice] = None): PolicyValueModel = NativeLock.synchronized { + def load( + path: Path, + device: Option[ComputeDevice] = None, + learningRate: Double = DefaultLr + ): PolicyValueModel = NativeLock.synchronized { + prepareNative(device) + given Default[Float32] = Default.float32 + val resolved = resolveDevice(device) + val net = readNet(path) + place(net, resolved) + new StorchPolicyValueModel(net, learningRate, resolved) + } + + /** + * Load two checkpoints on CPU, then move both. A recursive `named_parameters` calls + * `shared_from_this` on the root module, which JavaCPP did not allocate with + * `shared_ptr`, and that read access-violates at 0xffffffffffffffff. + */ + def loadPair( + first: Path, + second: Path, + device: Option[ComputeDevice] = None + ): (PolicyValueModel, PolicyValueModel) = NativeLock.synchronized { + prepareNative(device) given Default[Float32] = Default.float32 val resolved = resolveDevice(device) + val net1 = readNet(first) + val net2 = readNet(second) + place(net1, resolved) + place(net2, resolved) + ( + new StorchPolicyValueModel(net1, DefaultLr, resolved), + new StorchPolicyValueModel(net2, DefaultLr, resolved) + ) + } + + private def readNet(path: Path)(using Default[Float32]): DualResNetNet = { val in = new DataInputStream(new FileInputStream(path.toFile)) try { val magic = in.readUTF() @@ -189,9 +302,8 @@ object StorchPolicyValueModel { loaded(name) = t i += 1 } - net.load_state_dict(loaded.toMap.asInstanceOf[Map[String, Tensor[torch.DType]]]) - place(net, resolved) - new StorchPolicyValueModel(net, DefaultLr, resolved) + StorchPolicyValueModel.copyStateDict(net, loaded.toMap) + net } finally in.close() } @@ -203,14 +315,23 @@ object StorchPolicyValueModel { None } + /** GPU builds must map torch_cuda before the first torch class init, except CPU eval. */ + private def prepareNative(device: Option[ComputeDevice]): Unit = + if (!device.contains(ComputeDevice.Cpu)) CudaBootstrap.preload() + private def resolveDevice(requested: Option[ComputeDevice]): ComputeDevice = { - val cudaOk = - try torch.cuda.isAvailable - catch { case _: Throwable => false } + // Do not touch torch.cuda when the caller asked for CPU. isAvailable initializes + // CUDA, and the following state-dict load then crashes inside named_parameters. val resolved = requested match { - case Some(ComputeDevice.Cuda) => ComputeDevice.resolve("cuda", cudaOk) - case Some(ComputeDevice.Cpu) => ComputeDevice.Cpu - case None => ComputeDevice.fromEnvOrDefault(cudaOk) + case Some(ComputeDevice.Cpu) => ComputeDevice.Cpu + case other => + val cudaOk = + try torch.cuda.isAvailable + catch { case _: Throwable => false } + other match { + case Some(ComputeDevice.Cuda) => ComputeDevice.resolve("cuda", cudaOk) + case _ => ComputeDevice.fromEnvOrDefault(cudaOk) + } } val name = resolved match { case ComputeDevice.Cpu => "cpu" @@ -225,6 +346,6 @@ object StorchPolicyValueModel { // Already on CPU. Module.to(CPU) access-violates in torch_cpu.dll on a later load. case ComputeDevice.Cpu => () case ComputeDevice.Cuda => - val _ = net.to(Device.CUDA) + val _ = net.to(CudaDevice) } } diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/app/GenerationGateTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/app/GenerationGateTest.scala new file mode 100644 index 0000000..4a3d84c --- /dev/null +++ b/src/test/scala/org/deeplearning4j/scalphagozero/app/GenerationGateTest.scala @@ -0,0 +1,18 @@ +package org.deeplearning4j.scalphagozero.app + +import org.scalatest.funspec.AnyFunSpec + +class GenerationGateTest extends AnyFunSpec { + describe("GenerationGate") { + it("accepts a strictly lower finite loss") { + assert(GenerationGate.lossDropped(1.5, 1.4)) + assert(!GenerationGate.lossDropped(1.5, 1.5)) + assert(!GenerationGate.lossDropped(1.5, Double.NaN)) + } + + it("promotes only at the required win count") { + assert(GenerationGate.promote(wins = 26, games = 40, requiredWins = 26)) + assert(!GenerationGate.promote(wins = 25, games = 40, requiredWins = 26)) + } + } +} \ No newline at end of file diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfigParserTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfigParserTest.scala new file mode 100644 index 0000000..2f7e9ff --- /dev/null +++ b/src/test/scala/org/deeplearning4j/scalphagozero/app/config/GenerationConfigParserTest.scala @@ -0,0 +1,37 @@ +package org.deeplearning4j.scalphagozero.app.config + +import org.scalatest.funspec.AnyFunSpec + +class GenerationConfigParserTest extends AnyFunSpec { + describe("GenerationConfigParser.parse") { + it("returns the gated-generation defaults") { + val cfg = GenerationConfigParser.parse(Array.empty) + assert(cfg.parentPath == "models/model_size_9_layers_3.storch") + assert(cfg.candidatePath == "models/model_size_9_layers_3_candidate.storch") + assert(cfg.games == 256) + assert(cfg.steps == 100) + assert(cfg.minibatch == 512) + assert(cfg.learningRate == 0.001) + assert(cfg.roundsPerMove == 100) + assert(cfg.parallelGames == 8) + assert(cfg.evalBatchSize == 16) + } + + it("applies overrides") { + val cfg = GenerationConfigParser.parse( + Array("--parent", "models/promoted/gen.storch", "--games", "8", "--steps", "2", "--lr", "0.001") + ) + assert(cfg.parentPath == "models/promoted/gen.storch") + assert(cfg.games == 8) + assert(cfg.steps == 2) + } + + it("rejects a candidate path equal to the parent path") { + intercept[IllegalArgumentException] { + GenerationConfigParser.parse( + Array("--parent", "models/same.storch", "--candidate", "models/same.storch") + ) + } + } + } +} \ No newline at end of file diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/experience/ExperienceTargetsTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/experience/ExperienceTargetsTest.scala new file mode 100644 index 0000000..e5258e9 --- /dev/null +++ b/src/test/scala/org/deeplearning4j/scalphagozero/experience/ExperienceTargetsTest.scala @@ -0,0 +1,21 @@ +package org.deeplearning4j.scalphagozero.experience + +import org.scalatest.funspec.AnyFunSpec + +class ExperienceTargetsTest extends AnyFunSpec { + describe("ExperienceTargets.toBatch") { + it("normalizes each visit row and keeps rewards") { + val buffer = ZeroExperienceBuffer( + states = Array(1f, 2f, 3f, 4f), + stateShape = Array(2, 1, 2, 1), + visitCounts = Array(1f, 1f, 0f, 3f), + visitShape = Array(2, 2), + rewards = Array(1f, -1f) + ) + val batch = ExperienceTargets.toBatch(buffer) + assert(batch.policyTarget.toSeq == Seq(0.5f, 0.5f, 0f, 1f)) + assert(batch.valueTarget.toSeq == Seq(1f, -1f)) + assert(batch.stateShape.toSeq == Seq(2, 1, 2, 1)) + } + } +} \ No newline at end of file diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/ml/BatchSlicerTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/ml/BatchSlicerTest.scala new file mode 100644 index 0000000..b1b6e70 --- /dev/null +++ b/src/test/scala/org/deeplearning4j/scalphagozero/ml/BatchSlicerTest.scala @@ -0,0 +1,28 @@ +package org.deeplearning4j.scalphagozero.ml + +import org.scalatest.funspec.AnyFunSpec + +class BatchSlicerTest extends AnyFunSpec { + describe("BatchSlicer.slice") { + it("copies a row range of states, policy, and value") { + val batch = TrainingBatch( + states = Array(1f, 2f, 3f, 4f, 5f, 6f), + stateShape = Array(3, 2, 1, 1), + policyTarget = Array(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f), + valueTarget = Array(-1f, 0f, 1f) + ) + val sliced = BatchSlicer.slice(batch, offset = 1, count = 2) + assert(sliced.stateShape.toSeq == Seq(2, 2, 1, 1)) + assert(sliced.states.toSeq == Seq(3f, 4f, 5f, 6f)) + assert(sliced.policyTarget.toSeq == Seq(0.3f, 0.4f, 0.5f, 0.6f)) + assert(sliced.valueTarget.toSeq == Seq(0f, 1f)) + } + + it("rejects an empty slice") { + val batch = TrainingBatch(Array(1f), Array(1, 1, 1, 1), Array(1f), Array(1f)) + intercept[IllegalArgumentException] { + BatchSlicer.slice(batch, offset = 0, count = 0) + } + } + } +} \ No newline at end of file diff --git a/src/test/scala/org/deeplearning4j/scalphagozero/ml/StorchCudaParityTest.scala b/src/test/scala/org/deeplearning4j/scalphagozero/ml/StorchCudaParityTest.scala index 747f6f2..4f896cb 100644 --- a/src/test/scala/org/deeplearning4j/scalphagozero/ml/StorchCudaParityTest.scala +++ b/src/test/scala/org/deeplearning4j/scalphagozero/ml/StorchCudaParityTest.scala @@ -2,8 +2,9 @@ package org.deeplearning4j.scalphagozero.ml import java.nio.file.Files -import org.deeplearning4j.scalphagozero.ml.storch.StorchPolicyValueModel +import org.deeplearning4j.scalphagozero.ml.storch.{ CudaBootstrap, StorchPolicyValueModel } import org.scalatest.funspec.AnyFunSpec +import torch.cuda.isAvailable class StorchCudaParityTest extends AnyFunSpec { @@ -18,7 +19,8 @@ class StorchCudaParityTest extends AnyFunSpec { describe("CUDA parity") { it("matches a CPU forward and reloads through the current checkpoint reader") { - assume(torch.cuda.isAvailable, "CUDA not available") + CudaBootstrap.preload() + assume(isAvailable, "CUDA not available") val state = Array.fill(11 * 5 * 5)(0.15f) val cpu = StorchPolicyValueModel.create(1, 11, 5, Some(ComputeDevice.Cpu)) val saved = Files.createTempFile("scalphago-cuda-", ".storch")