using System.Diagnostics; using System.Numerics; namespace EvilEngine.GenerativeMotion; public sealed record BackendTiming(MotionBackend Backend, int Batch, double? MedianMilliseconds, string? Failure); public static class BackendBenchmark { public static readonly int[] Batches = [1, 8, 32]; public static string Graph(string package, int batch) { return Path.Combine(package, $"mmm_v6_soma_fp32_portable_b{batch}.onnx"); } public static IReadOnlyList Run(string package, Action fill, int warmup = 3, int runs = 20, double secondsPerGraph = 2) { ArgumentOutOfRangeException.ThrowIfLessThan(runs, 1); var timings = new List(); foreach (var backend in MotionRuntime.Candidates()) foreach (var batch in Batches) try { using var model = new SomaModel(Graph(package, batch), backend); fill(model.Inputs); for (var i = 0; i < warmup; i++) model.Run(); var samples = new List(); var started = Stopwatch.GetTimestamp(); while (samples.Count < runs && (samples.Count < 3 || Stopwatch.GetElapsedTime(started).TotalSeconds < secondsPerGraph)) { var start = Stopwatch.GetTimestamp(); model.Run(); samples.Add(Stopwatch.GetElapsedTime(start).TotalMilliseconds); } samples.Sort(); var median = samples[samples.Count / 2]; timings.Add(new BackendTiming(backend, batch, median, null)); if (!GenerativeCapacity.Fits(median)) break; } catch (Exception exception) when (exception is not OutOfMemoryException) { timings.Add(new BackendTiming(backend, batch, null, exception.Message)); break; } return timings; } public static void StandingStep(SomaInputs inputs) { var request = new SomaRequest { TargetCount = 1 }; var reference = SomaSkeleton.Reference; for (var pose = 0; pose < SomaContract.PosesPerToken; pose++) { reference.CopyTo(request.ContextPose(pose)); reference.CopyTo(request.TargetPose(pose)); } var hips = request.Target[0]; request.Target[0] = hips with { Position = hips.Position + new Vector3(1f, 0f, 0f) }; inputs.Clear(); var codec = new SomaCodec(Rigid.Identity); for (var row = 0; row < inputs.Batch; row++) codec.Encode(request, inputs.Row(row)); } }