|
using Godot; |
|
using Microsoft.ML.OnnxRuntime; |
|
using Microsoft.ML.OnnxRuntime.Tensors; |
|
using System.Collections.Generic; |
|
using System.Linq; |
|
|
|
namespace GodotONNX |
|
{ |
|
|
|
public partial class ONNXInference : GodotObject |
|
{ |
|
|
|
private InferenceSession session; |
|
|
|
|
|
|
|
private string modelPath; |
|
private int batchSize; |
|
|
|
private SessionOptions SessionOpt; |
|
|
|
|
|
|
|
public void Initialize(string Path, int BatchSize) |
|
{ |
|
modelPath = Path; |
|
batchSize = BatchSize; |
|
SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions(); |
|
session = LoadModel(modelPath); |
|
|
|
} |
|
|
|
public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins) |
|
{ |
|
|
|
|
|
|
|
|
|
|
|
var span = new float[obs.Count]; |
|
for (int i = 0; i < obs.Count; i++) |
|
{ |
|
span[i] = obs[i]; |
|
} |
|
|
|
IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue> |
|
{ |
|
NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })), |
|
NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize })) |
|
}; |
|
IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; |
|
|
|
IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results; |
|
|
|
try |
|
{ |
|
results = session.Run(inputs, outputNames); |
|
} |
|
catch (OnnxRuntimeException e) |
|
{ |
|
|
|
GD.Print("Error at inference: ", e); |
|
return null; |
|
} |
|
|
|
Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>(); |
|
DisposableNamedOnnxValue output1 = results.First(); |
|
DisposableNamedOnnxValue output2 = results.Last(); |
|
Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>(); |
|
Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>(); |
|
|
|
foreach (float f in output1.AsEnumerable<float>()) |
|
{ |
|
output1Array.Add(f); |
|
} |
|
|
|
foreach (float f in output2.AsEnumerable<float>()) |
|
{ |
|
output2Array.Add(f); |
|
} |
|
|
|
output.Add(output1.Name, output1Array); |
|
output.Add(output2.Name, output2Array); |
|
|
|
|
|
results.Dispose(); |
|
return output; |
|
} |
|
|
|
public InferenceSession LoadModel(string Path) |
|
{ |
|
using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read); |
|
byte[] model = file.GetBuffer((int)file.GetLength()); |
|
|
|
return new InferenceSession(model, SessionOpt); |
|
} |
|
public void FreeDisposables() |
|
{ |
|
session.Dispose(); |
|
SessionOpt.Dispose(); |
|
} |
|
} |
|
} |
|
|