diff --git a/Server/docs/SOR.Ai-Architecture-Plan.md b/Server/docs/SOR.Ai-Architecture-Plan.md index 38e116e..49a1b83 100644 --- a/Server/docs/SOR.Ai-Architecture-Plan.md +++ b/Server/docs/SOR.Ai-Architecture-Plan.md @@ -528,57 +528,121 @@ Global: Total: ~990 floats ``` -### 7.3 Model Architecture (Phase 3) +### 7.3 Model Architecture (implemented) -A lightweight **feedforward neural network**: +A **value network MLP** in `tools/train_neural.py`: ``` -Input layer: 990 units -Dense layer: 512 units, ReLU -Dense layer: 256 units, ReLU -Dense layer: 128 units, ReLU - -Split into two heads: - Policy head: 128 → num_actions (softmax over candidate action types) - Value head: 128 → 1 (sigmoid, win probability) +Input: 1024 floats (FeatureExtractor vector) +Dense: 1024 -> 512 + LayerNorm + ReLU + Dropout(0.2) +Dense: 512 -> 256 + LayerNorm + ReLU + Dropout(0.2) +Dense: 256 -> 128 + LayerNorm + ReLU +Output: 128 -> 1 + Tanh => score in [-1, 1] ``` -Training objective: -- **Policy loss**: cross-entropy between predicted policy and action chosen in replay -- **Value loss**: MSE between predicted win probability and actual game outcome +- **+1.0** = acting player won; **-1.0** = acting player lost +- Loss: MSELoss on outcome. Optimizer: AdamW + cosine LR annealing, gradient clip 1.0 +- Best checkpoint (lowest val loss) restored before ONNX export +- ~920k parameters -Trained in Python using PyTorch, exported to ONNX, deployed to `/Server/models/sor-ai-v{N}.onnx`. -`NeuralDecisionEngine` loads the ONNX model via `Microsoft.ML.OnnxRuntime` at service startup. +**ONNX contract** (must match `NeuralModelRegistry` constants `InputName`/`OutputName`): -### 7.4 Training Pipeline +| Property | Value | +|----------|-------| +| Input tensor name | `features` | +| Input shape | `[1, 1024]` float32 | +| Output tensor name | `score` | +| Output shape | `[1, 1]` float32 | +| Output range | `[-1, 1]` via tanh | + +--- + +### 7.4 How to Train the AI + +See `tools/README.md` for the complete step-by-step workflow. Summary below. + +#### Step 1 - Generate self-play data + +In the admin portal, go to **AI -> Calibration** and click **Run All Pairs**. +This triggers in-process AI vs AI games (no network, no delays) across all difficulty pairs. +The resulting `GameSession` rows are the training data source. + +Alternatively run a specific difficulty pair to generate targeted data faster: +``` +POST /admin/ai/calibration/run-pair { difficultyA: 7, difficultyB: 8, gameCount: 200 } +``` + +#### Step 2 - Export training data + +In the admin portal, go to **AI -> Calibration** and click **Export Training Data**. +Enter an output path on the server, e.g. `/var/sor/training/data.jsonl`. + +`GameReplayExporter` replays each completed session action-by-action and writes one +JSON line per action: + +```json +{ + GameSessionId: 3fa85f64..., + TurnNumber: 5, + ActorAccountId: ..., + Features: [0.0, 1.0, ...], + ActionType: AiPlayCardAction, + ActionJson: {}, + Outcome: 1.0 +} +``` + +`Outcome` is `+1.0` if the acting player won, `-1.0` if they lost. + +#### Step 3 - Train the model + +Install dependencies (Python 3.11+): + +```bash +pip install -r tools/requirements.txt +``` + +Run training: + +```bash +python tools/train_neural.py --data /var/sor/training/data.jsonl --out /var/sor/models/model.onnx --epochs 50 --batch-size 512 --lr 1e-3 +``` + +Key options: + +| Flag | Default | Description | +|------|---------|-------------| +| `--epochs` | 50 | Training epochs | +| `--batch-size` | 512 | Mini-batch size | +| `--lr` | 0.001 | AdamW learning rate | +| `--val-split` | 0.1 | Validation fraction | +| `--dropout` | 0.2 | Dropout probability | +| `--cpu` | off | Force CPU (ignores CUDA) | + +The script prints per-epoch train/val loss, marks best checkpoint with `*`, restores +best weights before export, and runs a quick onnxruntime validation of the exported file. + +#### Step 4 - Deploy ``` -1. Data Collection (continuous) - GameReplayExporter runs as background job nightly: - SELECT * FROM game_action_logs - JOIN game_sessions ON ... - WHERE sessions.status = 'Completed' - AND sessions.ended_at > last_export_timestamp - → Write JSONL to /data/training/raw/{date}.jsonl - -2. Feature Extraction (offline, Python) - python scripts/extract_features.py --input raw/ --output features/ - Reads JSONL, calls FeatureExtractor equivalent in Python, writes Parquet - -3. Model Training (offline, Python) - python scripts/train.py --data features/ --epochs 50 --output models/ - Trains PyTorch model, validates on held-out set - -4. Export & Validate - python scripts/export_onnx.py --model models/best.pt --output sor-ai-v{N}.onnx - Run benchmark: AiVsAiBenchmark plays 1000 games new vs old model; new must win > 55% - -5. Deploy - Copy sor-ai-v{N}.onnx to server/models/ - Admin calls: POST /admin/ai/reload-model { version: N } - NeuralDecisionEngine.ReloadModel() hot-swaps without restart +1. Copy model.onnx to the path configured in appsettings: Ai:NeuralModelPath +2. Admin -> AI -> Neural Model -> Hot-swap Model ``` +No restart required. The old ONNX InferenceSession is disposed atomically. +Tiers 9-10 use the new model for all subsequent decisions. +If no model file exists, tiers 9-10 fall back to heuristic scoring transparently. + +#### Iterative improvement + +1. **Cold start**: run heuristic self-play (D5) to generate initial data; train first model. +2. **Deploy** model and enable D9-D10 in calibration runs. +3. **D9/D10 self-play** generates higher-quality data than heuristic rollouts. +4. **Append** new export to JSONL; retrain with more epochs. +5. **Monitor** admin calibration win-rates after each deployment; adjust difficulty profiles if needed. + +--- + ### 7.5 Difficulty Calibration After each self-play / training cycle, run **calibration games** against human players: @@ -1755,32 +1819,151 @@ causes the AI account selected to have a Water-affinity deck (or the closest ava ## Phase Summary -| Phase | Track | Goal | Key Deliverable | -|---|---|---|---| -| 1.1 | A | Scaffold | `SOR.Ai.csproj` builds, wired into Host | -| 1.2 | A | Transport | `AiAuthenticatedConnection`, `AiClientMessage` | -| 1.3 | A | DB Schema | Migrations for `IsAi`, `AiSlotsJson` | -| 1.4 | A | AI Accounts | 50 seeded AI accounts at startup | -| 1.5 | A | AI Decks | Pre-built decks for every AI account | -| 1.6 | A | Lobby Handlers | Host can add/remove/configure AI in lobby | -| 1.7 | A | Session Manager | AI auto-sends `game.ready`, sessions tracked | -| 2.1 | B | Turn Pipeline | AI takes turns (immediately end-turns) | -| 2.2 | B | Placement | AI places ArchSpirit in Placement phase | -| 2.3 | B | Random Engine | Difficulty 1 plays legal random game end-to-end | -| 2.4 | B | Candidate Gen | All legal moves enumerated, unit tested | -| 2.5 | B | Heuristic Engine | Difficulties 2–5 play purposeful games | -| 3.1 | C | AI ELO | Internal ELO tracked for AI accounts | -| 3.2 | C | Self-Play | In-memory AI-vs-AI runner, admin API | -| 3.3 | C | Data Export | Replay JSONL export for training pipeline | -| 3.4 | C | MCTS Engine | Difficulties 6–8 with lookahead | -| 3.5 | C | Calibration | Automated win-rate calibration across difficulty tiers | -| 4.1 | D | Feature Extractor | Python training scripts, validated feature vector | -| 4.2 | D | Neural Engine | ONNX inference for Difficulties 9–10 | -| 5.1 | E | ELO Guard | AI ELO/OP excluded from human-facing records | -| 5.2 | E | Triggered Targets | AI resolves ability target-selection without stalling | -| 5.3 | E | Adaptive Difficulty | Recommended difficulty API | -| 5.4 | E | Personality | Display metadata, avatars, flavor text | -| 5.5 | E | Counter-Deck | AI selects counter-affinity deck vs human | +| Phase | Track | Status | Goal | Key Deliverable | +|---|---|:---:|---|---| +| 1.1 | A | done | Scaffold | SOR.Ai.csproj builds, wired into Host | +| 1.2 | A | done | Transport | AiAuthenticatedConnection, AiClientMessage | +| 1.3 | A | done | DB Schema | Migrations for IsAi, AiSlotsJson, ai_elo_records, ai_calibration_runs, ai_deck_assignments | +| 1.4 | A | done | AI Accounts | 50 seeded AI accounts at startup (10 tiers x 5 strategies) | +| 1.5 | A | done | AI Decks | Resolved dynamically from prebuilt starter decks; admin deck-per-difficulty config | +| 1.6 | A | done | Lobby Handlers | Host can add/remove/configure AI in lobby (server handlers + client UI) | +| 1.7 | A | done | Session Manager | AI auto-sends game.ready, sessions tracked | +| 2.1 | B | done | Turn Pipeline | AI takes turns end-to-end | +| 2.2 | B | done | Placement | AI places ArchSpirit in Placement phase | +| 2.3 | B | done | Random Engine | Difficulty 1 plays legal random game end-to-end | +| 2.4 | B | done | Candidate Gen | All legal moves enumerated (draw/channel/move/attack/sacrifice/ascend) | +| 2.5 | B | done | Heuristic Engine | Difficulties 2-5 with weighted scoring and mistake injection | +| 3.1 | C | done | AI ELO | Separate ai_elo_records table; FinalizeGameAsync guards with IsAi | +| 3.2 | C | done | Self-Play | In-process SelfPlayOrchestrator, admin calibration page | +| 3.3 | C | done | Data Export | GameReplayExporter writes JSONL; admin export UI | +| 3.4 | C | done | MCTS Engine | UCT tree search for Difficulties 6-8 (2-4s budget) | +| 3.5 | C | done | Calibration | AiCalibrationJob pairwise runs; ai_calibration_runs table | +| 4.1 | D | done | Feature Extractor | FeatureExtractor 1024-float vector; matches Python training contract | +| 4.2 | D | done | Neural Engine | NeuralDecisionEngine MCTS + ONNX leaf eval; hot-swap via admin | +| 4.3 | D | done | Training Pipeline | tools/train_neural.py PyTorch MLP -> ONNX; tools/README.md workflow docs | +| 4.4 | A | done | Client AI UI | Lobby Add AI Opponent button with difficulty (D1-D10) and strategy picker | +| 5.1 | E | TODO | Active Abilities | AI generates AiActivateAbilityAction candidates and executes active abilities | +| 5.2 | E | TODO | Triggered Targets | AI resolves ability target-selection without stalling | +| 5.3 | E | TODO | Adaptive Difficulty | Recommended difficulty API based on human ELO rank | +| 5.4 | E | TODO | Personality | Display metadata, avatars, flavor text per strategy archetype | +| 5.5 | E | TODO | Counter-Deck | AI selects counter-affinity deck vs human opponent | +| 5.6 | E | TODO | Trained Model | Run self-play -> export -> train cycle to produce initial model.onnx for D9-D10 | + +--- + +--- + +## Remaining Work (Phases 5.x) + +The following phases are not yet implemented. They are ordered by recommended priority. + +--- + +### Phase 5.1 — Active Ability Support + +**Gap**: `ActionCandidateGenerator` does not generate `AiActivateAbilityAction` candidates. +The action type is defined in `IAiDecisionEngine.cs` but never produced, so the AI never +uses unit active abilities regardless of difficulty. + +**Files to create/modify**: +- `SOR.Ai/Heuristics/ActionCandidateGenerator.cs` — add `ActiveAbilities(ctx)` method that + iterates `aiPlayer.Field`, checks each unit`s `Abilities` list for `CanActivate == true` + and `CurrentCooldown == 0`, and yields `AiActivateAbilityAction(unitInstanceId, abilityIndex)` +- `SOR.Ai/Heuristics/HeuristicDecisionEngine.cs` — add `AiActivateAbilityAction` case to + `ApplyAction` calling `GameEngine.ActivateAbility` +- `SOR.Ai/Training/SelfPlayRunner.cs` — same `ApplyAction` extension + +**Done when**: a unit with a 0-cooldown active ability uses it during AI turns. + +--- + +### Phase 5.2 — Triggered Target Selection + +**Gap**: Some game effects require target selection mid-turn (triggered abilities, on-play +effects with target prompts). The current AI pipeline submits the initial action but has no +mechanism to respond to a follow-up target-selection request from the server. + +**Files to create/modify**: +- `SOR.Ai/Core/AiPlayerSession.cs` — after submitting each action, check for a + `game.target_required` push and respond with `AiTargetSelectionAction` +- `SOR.Ai/Heuristics/TargetSelector.cs` (new) — given a list of valid target candidates, + pick the best target using heuristic scoring (prefer highest-threat enemy, prefer own + lowest-HP unit for healing, etc.) +- `SOR.Ai/Engine/IAiDecisionEngine.cs` — optionally extend with a `SelectTarget` method + so MCTS/Neural engines can participate in target selection + +**Done when**: an AI playing a card that requires target selection completes the full +play-then-target flow without stalling the game. + +--- + +### Phase 5.3 — Adaptive Difficulty API + +**Goal**: expose an endpoint that recommends a difficulty tier for a new human player based on +their ELO rank, so the client can suggest an appropriate starting difficulty. + +**Files to create/modify**: +- `SOR.Ai/Handlers/GetRecommendedDifficultyHandler.cs` (new) — message type + `game.ai.recommended_difficulty`; returns difficulty 1-10 based on `Account.RankScore` + mapped against calibration win-rate data in `ai_calibration_runs` +- `SOR.Admin/Components/Pages/Ai/AiCalibrationPage.razor` — display recommended-difficulty + mapping table derived from calibration results + +**Done when**: a player with ELO 1400 gets recommended D5-D6; a player with ELO 800 gets D2-D3. + +--- + +### Phase 5.4 — AI Personality & Display + +**Goal**: give each AI strategy archetype a display name, avatar, and flavor text so they feel +like distinct opponents rather than `Balanced AI (Adept)`. + +**Files to create/modify**: +- `SOR.Ai/Seeding/AiPersonality.cs` (new) — static record per (difficulty, strategy): + display name, short bio, avatar asset key +- `SOR.Ai/Handlers/GameAddAiHandler.cs` — include personality fields in + `GameAddAiResponse` and `CustomLobbyAiSlotsChangedPush` +- Client `lobby_room_screen.gd` — render avatar + bio in guest slot when AI is present +- `SOR.Admin/Components/Pages/Ai/AiEloPage.razor` — show avatar next to AI ELO rows + +**Done when**: each of the 50 AI accounts has a distinct portrait visible in the lobby room. + +--- + +### Phase 5.5 — Counter-Deck Selection + +**Goal**: when a host adds an AI opponent, automatically select an AI account whose deck +affinity counters the host`s ArchSpirit affinity, making the AI a more interesting opponent. + +**Files to create/modify**: +- `SOR.Ai/Lobby/CounterAffinityMatrix.cs` (new) — static `Affinity -> Affinity[]` mapping + (preferred counter affinities in priority order for each affinity) +- `SOR.Ai/Lobby/AiSlotAssigner.cs` — add `opponentAffinity` parameter; prefer AI accounts + whose active deck`s ArchSpirit affinity appears in the counter list +- `SOR.Ai/Handlers/GameAddAiHandler.cs` — resolve host`s deck affinity from + `CollectionDb`, pass to `AiSlotAssigner` + +**Done when**: adding an AI to a lobby where the host has a Fire-affinity deck causes the AI +to select a Water-affinity account. + +--- + +### Phase 5.6 — Initial Trained Model + +**Goal**: produce and deploy the first real `model.onnx` so D9-D10 use neural evaluation +instead of the heuristic fallback. + +**Steps** (not a code change — operational work): + +1. Run `AiCalibrationJob.RunAllPairsAsync` with `gameCount = 500` per pair. +2. Export training data from admin portal to `/var/sor/training/data.jsonl`. +3. Train: `python tools/train_neural.py --data data.jsonl --out model-v1.onnx --epochs 100` +4. Copy `model-v1.onnx` to path configured in `Ai:NeuralModelPath`. +5. Admin -> AI -> Neural Model -> Hot-swap Model. +6. Run calibration again; confirm D9 win rate vs D8 > 60%. + +**Done when**: admin neural model page shows `Loaded` and D9/D10 calibration win rates +are measurably higher than D8. ---