# Train a Color Lines neural player in Google Colab This kit includes the original deterministic C game engine, not a Python rules approximation. It requires Python 3.10+, a C compiler, NumPy and PyTorch. The browser and evaluator use the SAME C inference and move-selection code. No original game artwork is needed for training/testing. ## What is being trained? A small 704 → 64 ReLU → 1 sigmoid neural network estimates discounted remaining legal moves (gamma 0.99; output multiplied by 100). Inputs are the 9×9 board, ordered upcoming colors/count, and board-derived space/mobility/line features. It never sees the actual random seed, score, elapsed time or hidden engine data. The first 512 games use the regular V3 player as a teacher. Monte Carlo targets are computed from COMPLETE games: one reward per successful move until death. Then approximate policy iteration alternates epsilon-greedy self-play and value regression on a recent-state replay buffer. Every 32 games, 128 gradient batches update the model by default. This is value learning with search, NOT AlphaZero, an LLM, or a guarantee of better play. Off-policy replay, limited exploration and approximate chance sampling can cause plateauing or regression. For each decision, search shortlists the best 16 legal tactical moves and samples four possible original-engine transitions per move. It maximizes mean learned successor value (terminal value zero). All moves have the same immediate reward and discount, so these constants do not affect the argmax. Sampled seeds depend only on visible input, not the real RNG; this is not an exact conditional distribution over hidden seeds. Only shortlisted actions are explored. A strong move outside that shortlist can be missed. Original placement/line/score rules are unchanged. The model has 45,185 parameters; export size is 180,760 bytes. The bundled starter is experimental and **weaker than V3**. It completed 2,048 training games (512 teacher games, then self-play), with the default settings. On 1,000 separate evaluation seeds per player (3000000000–3000000999): | Player | Mean moves | Median | Longest | | --- | ---: | ---: | ---: | | Neural starter | 65.498 | 63 | 149 | | Regular V3 | 145.196 | 136 | 494 | The neural mean's approximate 95% interval is 64.31–66.69 moves. This is a working training/inference baseline, not evidence that AI has improved play. More games may help, but do not guarantee improvement; architecture, training objectives, exploration and search may need further work. Regular remains the default. See `models/starter.metadata.json`, `models/starter.evaluation.csv`, and `models/starter.evaluation.summary.json` for provenance and complete results. ## 1. Download and upload the kit On the game startup page click **Download Colab training kit**. Create a new notebook at https://colab.research.google.com/ . A CPU runtime works; optionally choose Runtime → Change runtime type → GPU. The native game/search uses CPU; only PyTorch gradient batches use the GPU. A small network may not benefit much from a GPU; simulator throughput may dominate. Run this cell, then select `ai-training.zip` downloaded from the game: ```python from google.colab import files uploaded = files.upload() ``` Unpack the trusted kit and install dependencies with uv: ```python !unzip -q -o /content/ai-training.zip -d /content !pip -q install uv !uv pip install --system numpy %cd /content/color-lines-ai !cc --version ``` ### T4 GPU setup (recommended for your GPU runtime) Select **Runtime → Change runtime type → T4 GPU**, then reconnect. Do not replace Colab's working CUDA PyTorch with an unqualified `uv ... torch` install. Use: ```python !python ai/setup_colab.py !python ai/train.py --device cuda --check-device ``` The setup script targets the exact Python interpreter used to run it. It keeps a working CUDA installation; if broken or CPU-only, it installs the official `torch==2.8.0` CUDA 12.6 wheel, then runs a real GPU matrix-multiply/backward test. Use a dedicated runtime: replacing torch can conflict with unrelated installed torchvision/torchaudio versions. If you imported torch in the notebook before repair, restart the notebook session before using that imported module again. Fresh `!python` subprocesses see the repaired installation immediately. You should see `CUDA preflight passed: Tesla T4` (the device name can vary), then `Training on cuda:0`. Update logs include `updates_device=cuda:0` and GPU memory. `--device cuda` refuses to start if CUDA is unusable; `--check-device` makes no output files. Auto mode also refuses silent CPU fallback in Colab or when an NVIDIA GPU is detected. For intentional CPU use, install torch as appropriate and pass `--device cpu` instead of `--device cuda` in the commands below. The original C simulator, move search and browser-compatible inference still run on CPU. GPU training occurs in bursts every 32 complete games by default, so low GPU utilization during game collection is normal. This change does not move the simulator onto GPU or promise an end-to-end speedup for this small network. If preflight fails, share its Python executable, torch version, CUDA runtime and `nvidia-smi` output. Merely selecting T4 in the UI does not establish that this Python process has a usable CUDA installation. `python ai/setup_colab.py --check-only` diagnoses without installing packages. Colab normally includes a C compiler. If `cc` is missing: ```python !apt-get -qq update !apt-get -qq install -y build-essential ``` ## 2. Save checkpoints to Drive, then train Colab runtime storage is temporary. Mount Drive and put the output directory there so checkpoint/export files survive runtime resets: ```python from google.colab import drive drive.mount('/content/drive') ``` Train a fresh model (10,000 COMPLETE games, not 10,000 moves): ```python !python ai/train.py --device cuda --episodes 10000 --out /content/drive/MyDrive/color-lines/run1 ``` Start with `--episodes 128` as a smoke test if desired. Runtime depends strongly on the machine and policy survival; no completion-time promise. The script prints progress each 32 games. Checkpoints contain the model, Adam optimizer, episode counter, replay data, settings and random states. They are replaced using a temporary file at each update and normal exit. An abrupt runtime kill can lose work since the last checkpoint; keep periodic copies for long runs. Ctrl-C requests a checkpoint after the current full game/update finishes. Training batches consistently permute color names across board, preview and line features to encourage color-invariant decisions. Spatial rotations are not used because the original placement algorithm scans cells in a fixed order. The output directory contains: * `checkpoint.pt`: full resumable training state (can be tens of MB). * `model.lnai`: latest browser/evaluator export, NOT necessarily the best model. * `metadata.json`: training settings and completed episode count. * `training.jsonl`: per-game seed, survival, score and update loss. ## 3. Resume After reconnecting, upload/unzip the kit, reinstall dependencies if needed, and mount Drive again. Train 10,000 ADDITIONAL games: ```python !python ai/train.py --device cuda --resume /content/drive/MyDrive/color-lines/run1/checkpoint.pt --episodes 10000 --out /content/drive/MyDrive/color-lines/run1 ``` Saved training hyperparameters are restored on full resume (CLI overrides for those settings are ignored); device, thread count, output and additional episode count remain configurable. Exact numerical repeatability across different GPU, PyTorch or hardware versions is not guaranteed. Checkpoints load with PyTorch's restricted `weights_only=True`; still use files from sources you trust. You can also start from the bundled starter or any compatible `.lnai` export: ```python !python ai/train.py --device cuda --resume models/starter.lnai --episodes 10000 --out /content/drive/MyDrive/color-lines/from-starter ``` That restores weights only: optimizer, replay buffer, RNG and episode counter start fresh, and teacher warmup is skipped. To reproduce/continue an exact run, keep its `.pt`, not just its `.lnai`. ## 4. Test in memory before choosing a model Evaluate 1,000 complete games plus the regular V3 player on matching initial seeds. This needs only NumPy, a compiler and the export, not PyTorch or artwork: ```python !python ai/evaluate.py --model /content/drive/MyDrive/color-lines/run1/model.lnai --games 1000 --compare --out /content/drive/MyDrive/color-lines/eval-run1.csv ``` Use `--games 10000` for a larger comparison. It writes per-game CSV and a `.summary.json` with means, approximate 95% intervals, medians, tails, maximum, paired differences, and a model SHA-256. Every game must reach actual game over; the safety limit raises an error rather than counting truncated games as wins. Both players receive only visible board/preview data. Scores use zero think-time timestamps for consistency; survival in moves is the primary metric. Training samples seeds 1–999,999,999. Evaluation defaults to seeds starting at 3,000,000,000. Treat that range as validation if you repeatedly select models against it; reserve an untouched range, e.g. `--seed-start 3500000000`, for a final test. Don't tune on the final test. Compare lower-tail failures and latency too, not just the single best game. Frozen model inference is deterministic on the same hardware/input; float rounding can cause tie differences across platforms. Keep separate named exports for models you wish to compare. The trainer does not automatically pick a 'best' model using the test set. Larger training budgets do not necessarily improve performance; evaluate periodically. ## 5. Play with your model Download the small export from Colab: ```python from google.colab import files files.download('/content/drive/MyDrive/color-lines/run1/model.lnai') ``` Reload the hosted game. Before starting, select the `.lnai` using **Load a trained model**. The page validates its format, selects **Neural — my model file**, and stores the bytes locally in that browser. Click Play (or complete the original artwork download flow), start the game, then press F5 or click its native button. It reads **F5 Model** when the neural model is active. Nothing is sent to a model API. The `.pt` checkpoint cannot be loaded in the browser. **Regular** ignores all stored models. **Neural — bundled experimental model** uses the included starter. After a page reload your custom model remains available, but regular mode is the safe default; explicitly select custom again. **Forget saved model** removes only that model, not artwork or high scores. Model selection is locked at startup; reload to change players. Manual play, F5 pause, scoring and game rules remain the same. ## Local commands and verification ```sh uv run --with torch --with numpy python ai/train.py --episodes 128 --out runs/demo uv run --with numpy python ai/evaluate.py --model runs/demo/model.lnai --games 100 --compare --out runs/eval.csv uv run --with torch --with numpy python ai/test_pipeline.py ``` The C loader targets little-endian IEEE-754 float32 systems (Colab x86/ARM and WebAssembly). Export format: `LNAI0001`, three little-endian uint32 dimensions 704/64/1, then row-major float32 first-layer weights, first-layer biases, output-layer weights, output bias. Wrong sizes, nonfinite and extreme weights are rejected. Exported files contain only numeric data, no executable code. References: https://docs.pytorch.org/tutorials/beginner/saving_loading_models https://research.google.com/colaboratory/faq.html https://pytorch.org/get-started/previous-versions/