ONNX & Engine Inference (Unreal & Godot)

⚡ ONNX & In-Engine Neural Network Inference (Unreal & Godot)

Training machine learning models in Python (via PyTorch or TensorFlow) is great for experimentation, but running a Python interpreter inside a compiled C++ game engine or custom Odin executable is slow, bloated, and impractical for real-time 60fps games.

The industry standard bridge is ONNX (Open Neural Network Exchange) and ONNX Runtime (C/C++ / C#).


🏛️ The Offline Training to Real-Time Runtime Pipeline

+-------------------------------------------------------------+
| 1. Offline Training (Python + PyTorch / TensorFlow)         |
|    - Train Game AI / Market Model on GPU cluster            |
+-------------------------------------------------------------+
                              │
                     (torch.onnx.export)
                              ▼
+-------------------------------------------------------------+
| 2. Standardized Binary (.onnx File)                         |
|    - Serialized static computation graph & optimized weights|
+-------------------------------------------------------------+
                              │
                     (Embedded in Game Project)
                              ▼
+-------------------------------------------------------------+
| 3. In-Engine Inference (ONNX Runtime / NNE / GDExtension)   |
|    - Pure C/C++ native execution (DirectX, Vulkan, DirectML)|
|    - Sub-millisecond execution per frame without Python!    |
+-------------------------------------------------------------+

📤 1. Exporting PyTorch Models to ONNX Format

To convert a PyTorch model into an optimized .onnx binary:

import torch

# Instantiate trained model
model = SimpleNet(input_dim=10, hidden_dim=64, output_dim=3)
model.eval()

# Create dummy input matching expected tensor shape
dummy_input = torch.randn(1, 10, dtype=torch.float32)

# Export model graph to disk
torch.onnx.export(
    model,
    dummy_input,
    "game_ai_model.onnx",
    export_params=True,                 # Store trained weights inside model file
    opset_version=17,                   # Modern ONNX operator set
    do_constant_folding=True,           # Optimize constant expressions upfront
    input_names=['observation_input'],  # Named input tensor
    output_names=['action_output'],     # Named output tensor
    dynamic_axes={
        'observation_input': {0: 'batch_size'}, # Allow variable batch size at runtime
        'action_output': {0: 'batch_size'}
    }
)
print("Successfully exported game_ai_model.onnx!")

🎮 2. Running Inference in Unreal Engine 5 (NNE Subsystem)

Unreal Engine 5 includes the native Neural Network Engine (NNE) subsystem, allowing direct evaluation of ONNX models in C++ and Blueprints without third-party plugins:

  1. Enable the NNE (Neural Network Engine) plugin in Project Settings -> Plugins.
  2. Drag and drop your .onnx file directly into the Unreal Content Browser to create a UNNEModelData asset.
  3. Use the C++ NNE runtime to evaluate predictions inside your Tick() or character controller:
#include "NNE.h"
#include "NNERuntimeCPU.h"
#include "NNERuntimeGPU.h"

void AAIController::EvaluateModel(const TArray<float>& Observations)
{
    // 1. Get NNE Runtime instance
    TWeakInterfacePtr<INNERuntimeCPU> Runtime = UE::NNE::GetRuntime<INNERuntimeCPU>(TEXT("NNERuntimeORTCpu"));
    
    // 2. Create Model Instance from imported asset
    TSharedPtr<UE::NNE::IModelInstanceCPU> ModelInstance = Runtime->CreateModelInstanceCPU(MyModelAsset);
    
    // 3. Set input tensor bindings and evaluate synchronously
    // ModelInstance->RunSync(InputBindings, OutputBindings);
}

🤖 3. Running Inference in Godot 4 via GDExtension

In Godot 4, you can execute ONNX models using the C++ ONNX Runtime compiled inside a GDExtension Native Plugin or via lightweight community bindings (godot-onnx):

# GDScript ONNX Inference Example
extends Node3D

var onnx_session: ONNXSession
var observations: PackedFloat32Array

func _ready() -> void:
    # Load serialized ONNX binary
    onnx_session = ONNXSession.new()
    onnx_session.load_model("res://ai/game_ai_model.onnx")

func _physics_process(delta: float) -> void:
    # 1. Gather sensory observations (e.g. raycast distances, speed)
    observations = _gather_raycast_sensors()
    
    # 2. Run instant native inference (0.1ms execution)
    var action_probabilities: PackedFloat32Array = onnx_session.run([observations])[0]
    
    # 3. Apply best action to character movement
    var chosen_action: int = _argmax(action_probabilities)
    _execute_ai_action(chosen_action)

⚖️ Performance Comparison: Python vs Native ONNX

Metric Python Runtime (torch.eval()) Native C++ / ONNX Runtime
Latency per Step ≈2.5ms−8.0ms (GIL & interpreter overhead) ≈0.08ms−0.3ms (Direct SIMD / AVX2 / Tensor cores)
Memory Footprint 250MB−1.2GB (Python + torch DLLs) 15MB−45MB (Standalone .onnx + runtime static lib)
Thread Safety Subject to Python Global Interpreter Lock (GIL) Fully multi-threaded across engine worker tasks
Engine Packaging Heavy, complex bundling required Drop .onnx directly into standard game build