Implement AI Phase 4: Neural MCTS engine for tiers 9-10

- Add NeuralModelRegistry singleton: loads ONNX model from Ai:NeuralModelPath,
  hot-swap via ReloadAsync(), static Instance for engine access
- Add NeuralEvaluator: GameState → ONNX inference with heuristic fallback when
  no model is loaded (tiers 9-10 fully playable without a trained model)
- Add AiNeuralStartupService: loads model at startup, logs if not configured
- Add NeuralDecisionEngine: MCTS with neural leaf evaluation (400 sims/action,
  6-10s budget) replacing random rollouts with direct score estimation
- Set tiers 9-10 EngineType="Neural" in AiDifficultyProfiles
- Add AiModelPage (/ai/model): model status, hot-swap button, ONNX contract docs
- Register NeuralModelRegistry + NeuralDecisionEngine in SOR.Ai and SOR.Admin
- Add Microsoft.ML.OnnxRuntime 1.18.0 to central package versions

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-04-12 19:27:16 -04:00
co-authored by Claude Happy
parent 70df0e0b33
commit 06c61055d4
13 changed files with 554 additions and 3 deletions
+3
View File
@@ -66,5 +66,8 @@
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
<!-- In-process test server for integration tests -->
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0" />
<!-- ── Machine Learning ────────────────────────────────────────────────── -->
<!-- ONNX Runtime: CPU inference for the Phase 4 neural decision engine -->
<PackageVersion Include="Microsoft.ML.OnnxRuntime" Version="1.18.0" />
</ItemGroup>
</Project>
@@ -183,6 +183,11 @@
<i class="bi bi-collection-play me-2"></i>Deck Config
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/ai/model">
<i class="bi bi-cpu me-2"></i>Neural Model
</NavLink>
</li>
</ul>
</li>
<li class="nav-item">
@@ -0,0 +1,123 @@
@page "/ai/model"
@using SOR.Ai.Neural
@inject NeuralModelRegistry ModelRegistry
@inject ILogger<AiModelPage> Logger
<PageTitle>AI Neural Model – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">Neural Model</h1>
</div>
<p class="text-muted mb-4">
Manage the ONNX model used by difficulty tiers 9 (Legend) and 10 (Mythic).
The model path is configured via the <code>Ai:NeuralModelPath</code> environment variable.
</p>
@if (_error is not null)
{
<div class="alert alert-danger">@_error</div>
}
@if (_success is not null)
{
<div class="alert alert-success">@_success</div>
}
<!-- Status card -->
<div class="row g-3 mb-4">
<div class="col-md-4">
<div class="card h-100">
<div class="card-body">
<div class="text-muted small mb-1">Status</div>
@if (ModelRegistry.IsLoaded)
{
<span class="badge bg-success fs-6">Loaded</span>
}
else
{
<span class="badge bg-secondary fs-6">Not Loaded</span>
}
</div>
</div>
</div>
<div class="col-md-4">
<div class="card h-100">
<div class="card-body">
<div class="text-muted small mb-1">Model Path</div>
<code class="small">@(ModelRegistry.ModelPath ?? "— not configured —")</code>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card h-100">
<div class="card-body">
<div class="text-muted small mb-1">Last Loaded</div>
<span>@(ModelRegistry.LoadedAt?.ToString("yyyy-MM-dd HH:mm:ss UTC") ?? "—")</span>
</div>
</div>
</div>
</div>
<!-- Hot-swap -->
<div class="card mb-4">
<div class="card-header">Hot-Swap Model</div>
<div class="card-body">
<p class="text-muted small mb-3">
Reloads the ONNX model from the configured path without restarting the server.
Active AI games will continue with the old model until their next turn.
</p>
<button class="btn btn-warning" @onclick="ReloadAsync" disabled="@_reloading">
@if (_reloading) { <span class="spinner-border spinner-border-sm me-1"></span> }
<i class="bi bi-arrow-repeat me-1"></i>Reload Model from Disk
</button>
</div>
</div>
<!-- ONNX contract reference -->
<div class="card">
<div class="card-header">ONNX Contract</div>
<div class="card-body">
<p class="mb-2 text-muted small">
The model must conform to this interface. Use the Python training script in
<code>tools/train_neural.py</code> to produce a compliant export.
</p>
<table class="table table-sm mb-0">
<thead><tr><th>Field</th><th>Value</th></tr></thead>
<tbody>
<tr><td>Input name</td> <td><code>@NeuralModelRegistry.InputName</code></td></tr>
<tr><td>Input shape</td> <td><code>[1, 1024]</code> — float32</td></tr>
<tr><td>Output name</td> <td><code>@NeuralModelRegistry.OutputName</code></td></tr>
<tr><td>Output shape</td><td><code>[1, 1]</code> — float32 in [-1, 1]</td></tr>
<tr><td>Opset</td> <td>17 (recommended)</td></tr>
</tbody>
</table>
</div>
</div>
@code {
private bool _reloading;
private string? _error;
private string? _success;
private async Task ReloadAsync()
{
_reloading = true; _error = null; _success = null; StateHasChanged();
try
{
bool ok = await ModelRegistry.ReloadAsync();
if (ok)
_success = $"Model reloaded successfully at {ModelRegistry.LoadedAt:yyyy-MM-dd HH:mm:ss} UTC.";
else
_error = "Reload failed — check that the model file exists at the configured path and the server log for details.";
}
catch (Exception ex)
{
_error = ex.Message;
}
finally
{
_reloading = false;
StateHasChanged();
}
}
}
+4
View File
@@ -15,6 +15,7 @@ using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;
using SOR.Admin.Components;
using SOR.Ai.Calibration;
using SOR.Ai.Neural;
using SOR.Ai.Training;
using SOR.Cdn;
using SOR.Database;
@@ -164,6 +165,9 @@ builder.Services.AddScoped<SelfPlayOrchestrator>();
builder.Services.AddScoped<GameReplayExporter>();
builder.Services.AddSingleton<AiCalibrationJob>();
// ── Neural model registry (admin-side: status + hot-swap page) ────────────
builder.Services.AddSingleton<NeuralModelRegistry>();
// ── CDN client ────────────────────────────────────────────────────────────
builder.Services.AddCdnClient(builder.Configuration);
@@ -179,6 +179,7 @@ internal sealed class AiPlayerSession : IAsyncDisposable
{
"Heuristic" => new HeuristicDecisionEngine(profile),
"MCTS" => new MonteCarloEngine(profile),
"Neural" => new NeuralDecisionEngine(profile),
_ => new RandomDecisionEngine(), // "Random" + any future unknown
};
@@ -148,12 +148,15 @@ internal static class AiDifficultyProfiles
PositionalWeight = 1.4f,
ResourceWeight = 1.4f,
},
// ── Tiers 9–10: Neural MCTS ───────────────────────────────────────────
new()
{
Difficulty = 9,
DisplayName = "Legend",
EngineType = "Heuristic", // TODO Phase 4: "Neural"
EngineType = "Neural",
MistakeRate = 0.0f,
MctsTimeBudgetMs = 6000,
MctsMaxDepth = 10,
MinThinkTimeMs = 1500,
MaxThinkTimeMs = 3000,
MinActionDelayMs = 900,
@@ -168,8 +171,10 @@ internal static class AiDifficultyProfiles
{
Difficulty = 10,
DisplayName = "Mythic",
EngineType = "Heuristic", // TODO Phase 4: "Neural"
EngineType = "Neural",
MistakeRate = 0.0f,
MctsTimeBudgetMs = 10000,
MctsMaxDepth = 15,
MinThinkTimeMs = 1500,
MaxThinkTimeMs = 3000,
MinActionDelayMs = 1000,
@@ -0,0 +1,147 @@
namespace SOR.Ai.Engine;
using SOR.Ai.Core;
using SOR.Ai.Heuristics;
using SOR.Ai.MCTS;
using SOR.Ai.Neural;
using SOR.Database.Enums;
using SOR.Game;
/// <summary>
/// Neural MCTS decision engine (Difficulty 9–10).
///
/// Identical tree structure to MonteCarloEngine (Phase 3), but replaces the
/// random playout + heuristic leaf evaluation with a direct neural network call:
///
/// Select → Expand → NeuralEvaluate (no rollout) → Backpropagate
///
/// If no ONNX model is loaded, NeuralEvaluator transparently falls back to the
/// normalised heuristic so the engine degrades gracefully.
/// </summary>
internal sealed class NeuralDecisionEngine : IAiDecisionEngine
{
private readonly AiDifficultyProfile _profile;
public NeuralDecisionEngine(AiDifficultyProfile profile)
{
_profile = profile;
}
public IReadOnlyList<AiAction> ComputeTurn(AiTurnContext ctx)
{
var plan = new List<AiAction>();
// ── 1. Draw phase ─────────────────────────────────────────────────────
GameState workingState;
if (ctx.State.Phase == GamePhase.Draw)
{
plan.Add(new AiDrawAction());
workingState = Clone(ctx.State);
try { (workingState, _) = GameEngine.Draw(workingState, ctx.AiAccountId); }
catch { workingState = Clone(ctx.State); }
}
else
{
workingState = Clone(ctx.State);
}
// ── 2. Neural MCTS main phase ─────────────────────────────────────────
var deadline = DateTime.UtcNow.AddMilliseconds(_profile.MctsTimeBudgetMs);
const int maxActions = 30;
int iterations = 0;
while (iterations++ < maxActions)
{
if (workingState.Phase == GamePhase.GameOver) break;
var workingCtx = new AiTurnContext(workingState, ctx.AiAccountId);
var candidates = ActionCandidateGenerator.All(workingCtx)
.Where(a => a is not AiDrawAction)
.ToList();
if (candidates.Count == 0) break;
var root = new MctsNode(parent: null, actionFromParent: null);
root.Untried = candidates;
int sims = 0;
while (DateTime.UtcNow < deadline && sims < 400)
{
sims++;
RunIteration(root, workingState, ctx.AiAccountId);
}
var best = root.Children.MaxBy(c => c.Visits);
if (best?.ActionFromParent is null) break;
plan.Add(best.ActionFromParent);
try { Apply(workingState, ctx.AiAccountId, best.ActionFromParent); }
catch { break; }
}
plan.Add(new AiEndTurnAction());
return plan;
}
// ── Neural MCTS iteration (no rollout — direct neural evaluation) ─────────
private void RunIteration(MctsNode root, GameState rootState, string aiAccountId)
{
var node = root;
var state = Clone(rootState);
// Selection.
while (node.Untried.Count == 0 && node.Children.Count > 0)
{
node = node.Children.MaxBy(c => c.Ucb1())!;
Apply(state, aiAccountId, node.ActionFromParent!);
}
// Expansion.
if (node.Untried.Count > 0)
{
int idx = Random.Shared.Next(node.Untried.Count);
var action = node.Untried[idx];
node.Untried.RemoveAt(idx);
var simState = Clone(state);
try { Apply(simState, aiAccountId, action); }
catch { return; }
var child = new MctsNode(node, action);
child.Untried = ActionCandidateGenerator.All(
new AiTurnContext(simState, aiAccountId))
.Where(a => a is not AiDrawAction)
.ToList();
node.Children.Add(child);
node = child;
state = simState;
}
// Neural evaluation (replaces random playout).
float value = NeuralEvaluator.Evaluate(state, aiAccountId, _profile);
// Backpropagation.
node.Backpropagate(value);
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static GameState Clone(GameState s)
=> GameEngine.Deserialize(GameEngine.Serialize(s));
private static void Apply(GameState state, string actorId, AiAction action)
{
switch (action)
{
case AiDrawAction: (state, _) = GameEngine.Draw(state, actorId); break;
case AiPlayCardAction p: GameEngine.ChannelCard(state, actorId, p.CardInstanceId, p.TargetTiles); break;
case AiMoveAction m: GameEngine.MoveUnit(state, actorId, m.UnitInstanceId, m.Target); break;
case AiAttackAction a: (state, _) = GameEngine.Attack(state, actorId, a.AttackerInstanceId, a.TargetInstanceId); break;
case AiSacrificeAction s: GameEngine.Sacrifice(state, actorId, s.UnitInstanceId); break;
case AiAscendAction asc: GameEngine.Ascend(state, actorId, asc.IncomingCardInstanceId); break;
case AiEndTurnAction: (state, _) = GameEngine.EndTurn(state, actorId); break;
}
}
}
@@ -0,0 +1,38 @@
namespace SOR.Ai.Neural;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
/// <summary>
/// One-shot IHostedService that loads the ONNX model at startup.
/// Runs after AiSeedStartupService (registration order in ServiceRegistration).
/// Non-blocking: if the model file is absent the server starts normally and
/// tiers 9-10 fall back to heuristic scoring until a model is uploaded.
/// </summary>
internal sealed class AiNeuralStartupService : IHostedService
{
private readonly NeuralModelRegistry _registry;
private readonly ILogger<AiNeuralStartupService> _logger;
public AiNeuralStartupService(
NeuralModelRegistry registry,
ILogger<AiNeuralStartupService> logger)
{
_registry = registry;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("AiNeuralStartupService: initializing neural model…");
await _registry.InitializeAsync(cancellationToken);
if (_registry.IsLoaded)
_logger.LogInformation("AiNeuralStartupService: model ready.");
else
_logger.LogInformation(
"AiNeuralStartupService: no model loaded — tiers 9-10 will use heuristic fallback.");
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -0,0 +1,83 @@
namespace SOR.Ai.Neural;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using SOR.Ai.Engine;
using SOR.Ai.Heuristics;
using SOR.Ai.Training;
using SOR.Game;
/// <summary>
/// Evaluates a game position using the loaded ONNX model.
///
/// Input: float[1024] feature vector produced by FeatureExtractor.
/// Output: float in [-1, 1] — positive = good for the AI player.
///
/// Fallback: if no model is loaded (NeuralModelRegistry.Instance is null or
/// GetSession() returns null), falls back to the heuristic ScoringFunctions
/// normalised to [-1, 1] so the rest of the engine code is unaffected.
/// </summary>
internal static class NeuralEvaluator
{
/// <summary>
/// Evaluate the position. Returns a score in [-1, 1].
/// </summary>
public static float Evaluate(
GameState state,
string aiAccountId,
AiDifficultyProfile profile)
{
var session = NeuralModelRegistry.Instance?.GetSession();
if (session is null)
return FallbackHeuristic(state, aiAccountId, profile);
try
{
return RunInference(session, state, aiAccountId);
}
catch
{
// Model inference failure — fall back silently.
return FallbackHeuristic(state, aiAccountId, profile);
}
}
// ── Inference ─────────────────────────────────────────────────────────────
private static float RunInference(
InferenceSession session,
GameState state,
string aiAccountId)
{
var features = FeatureExtractor.Extract(state, aiAccountId);
// Build input tensor: shape [1, 1024].
var tensor = new DenseTensor<float>(features, [1, FeatureExtractor.FeatureCount]);
using var inputOrtValue = OrtValue.CreateTensorValueFromMemory(
OrtMemoryInfo.DefaultInstance,
tensor.Buffer,
[1L, (long)FeatureExtractor.FeatureCount]);
using var outputs = session.Run(
new RunOptions(),
[NeuralModelRegistry.InputName],
[inputOrtValue],
[NeuralModelRegistry.OutputName]);
var result = outputs[0].GetTensorDataAsSpan<float>();
return Math.Clamp(result[0], -1f, 1f);
}
// ── Heuristic fallback ─────────────────────────────────────────────────────
private static float FallbackHeuristic(
GameState state,
string aiAccountId,
AiDifficultyProfile profile)
{
float h = ScoringFunctions.Evaluate(state, aiAccountId, profile);
return Math.Clamp(h / 500f, -1f, 1f);
}
}
@@ -0,0 +1,129 @@
namespace SOR.Ai.Neural;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.ML.OnnxRuntime;
/// <summary>
/// Singleton that owns the loaded ONNX InferenceSession for the neural decision engine.
///
/// Model path is read from configuration key "Ai:NeuralModelPath".
/// If the path is not set or the file does not exist at startup, the registry starts
/// with no model loaded — NeuralEvaluator falls back to heuristic scoring transparently.
///
/// Hot-swap: call ReloadAsync() from the admin page to reload the model from disk
/// without restarting the server. The old session is disposed after the swap.
///
/// ONNX contract (must match the Python training export):
/// Input tensor name: "features" shape [1, 1024] dtype float32
/// Output tensor name: "score" shape [1, 1] dtype float32
/// </summary>
public sealed class NeuralModelRegistry : IDisposable
{
public static NeuralModelRegistry? Instance { get; private set; }
private readonly string? _modelPath;
private readonly ILogger<NeuralModelRegistry> _logger;
private volatile InferenceSession? _session;
private DateTimeOffset? _loadedAt;
// ── Status (for admin page) ───────────────────────────────────────────────
public bool IsLoaded => _session is not null;
public string? ModelPath => _modelPath;
public DateTimeOffset? LoadedAt => _loadedAt;
// ONNX tensor names — must match the Python export.
public const string InputName = "features";
public const string OutputName = "score";
public NeuralModelRegistry(
IConfiguration config,
ILogger<NeuralModelRegistry> logger)
{
_modelPath = config["Ai:NeuralModelPath"];
_logger = logger;
Instance = this;
}
/// <summary>
/// Called at startup by AiNeuralStartupService.
/// Loads the model if the path is configured and the file exists.
/// Never throws — logs and continues without a model on any failure.
/// </summary>
public async Task InitializeAsync(CancellationToken ct = default)
{
if (string.IsNullOrEmpty(_modelPath))
{
_logger.LogInformation(
"NeuralModelRegistry: Ai:NeuralModelPath not configured — neural engine disabled.");
return;
}
await LoadFromPathAsync(_modelPath);
}
/// <summary>
/// Hot-swap: reloads the model from the configured path.
/// Called from the admin page. Returns true if load succeeded.
/// </summary>
public async Task<bool> ReloadAsync()
{
if (string.IsNullOrEmpty(_modelPath))
{
_logger.LogWarning("NeuralModelRegistry: cannot reload — Ai:NeuralModelPath not set.");
return false;
}
return await LoadFromPathAsync(_modelPath);
}
/// <summary>
/// Returns the current InferenceSession, or null if no model is loaded.
/// Callers must handle null and fall back to heuristic evaluation.
/// </summary>
public InferenceSession? GetSession() => _session;
// ── Private ───────────────────────────────────────────────────────────────
private Task<bool> LoadFromPathAsync(string path)
{
return Task.Run(() =>
{
try
{
if (!File.Exists(path))
{
_logger.LogWarning(
"NeuralModelRegistry: model file not found at '{Path}'. " +
"Neural engine will be disabled until a model is provided.", path);
return false;
}
var opts = new SessionOptions();
opts.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL;
var newSession = new InferenceSession(path, opts);
var old = Interlocked.Exchange(ref _session, newSession);
old?.Dispose();
_loadedAt = DateTimeOffset.UtcNow;
_logger.LogInformation(
"NeuralModelRegistry: model loaded from '{Path}' at {When}.", path, _loadedAt);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex,
"NeuralModelRegistry: failed to load model from '{Path}'.", path);
return false;
}
});
}
public void Dispose()
{
_session?.Dispose();
_session = null;
if (Instance == this) Instance = null;
}
}
+4
View File
@@ -9,6 +9,10 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ML.OnnxRuntime" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
<ProjectReference Include="..\SOR.Game\SOR.Game.csproj" />
+9 -1
View File
@@ -8,6 +8,7 @@ using SOR.Ai.Engine;
using SOR.Ai.Handlers;
using SOR.Ai.Heuristics;
using SOR.Ai.Lobby;
using SOR.Ai.Neural;
using SOR.Ai.Seeding;
using SOR.Ai.Training;
using SOR.Networking.Abstractions.Messaging;
@@ -26,9 +27,15 @@ public static class ServiceRegistration
IConfiguration configuration)
{
// ── Startup seed (one-shot IHostedService) ────────────────────────────
// Ensures AI accounts and decks exist in the DB before traffic is accepted.
// Ensures AI accounts exist in the DB before traffic is accepted.
services.AddHostedService<AiSeedStartupService>();
// ── Neural model registry (singleton) + startup loader ────────────────
// Loads the ONNX model at startup if Ai:NeuralModelPath is configured.
// If not configured, neural tiers fall back to heuristic scoring.
services.AddSingleton<NeuralModelRegistry>();
services.AddHostedService<AiNeuralStartupService>();
// ── Account registry (singleton, loaded at seed time) ─────────────────
// In-memory set of AI account IDs for O(1) "is this account an AI?" checks.
// Used by GameEndTurnHandler to decide whether to publish AiTurnStartedEvent.
@@ -54,6 +61,7 @@ public static class ServiceRegistration
services.AddTransient<RandomDecisionEngine>();
services.AddTransient<HeuristicDecisionEngine>();
services.AddTransient<MonteCarloEngine>();
services.AddTransient<NeuralDecisionEngine>();
// ── Training / calibration (scoped — used per admin request) ─────────
services.AddScoped<SelfPlayOrchestrator>();
@@ -112,6 +112,7 @@ internal sealed class SelfPlayRunner
{
"Heuristic" => new HeuristicDecisionEngine(profile),
"MCTS" => new MonteCarloEngine(profile),
"Neural" => new NeuralDecisionEngine(profile),
_ => new RandomDecisionEngine(),
};