aisop/tests/AmdGpu.Smoke/Program.cs

95 lines
5.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Diagnostics;
using System.Security.Cryptography;
using System.Text.Json;
using OpenCvSharp;
using SopHelper.Engine.Common;
using SopHelper.Engine.Inference;
if (args.Length < 1) throw new ArgumentException("用法:AmdGpu.Smoke 模型目录 双手视频路径 [--cuda] [--expect-unavailable]");
var cuda = args.Contains("--cuda");
var expectedBackend = cuda ? "CUDA" : "AMD";
var expectedProvider = cuda ? "CUDAExecutionProvider" : "WebGpuExecutionProvider";
var models = Path.GetFullPath(args[0]);
var palmPath = Path.Combine(models, "palm_detection_full_Nx3x192x192_post.onnx");
var landmarkPath = Path.Combine(models, "hand_landmark_sparse_Nx3x224x224.onnx");
if (args.Contains("--expect-unavailable"))
{
using var unavailable = new MediaPipeHandDetector();
try { unavailable.Load(palmPath, landmarkPath, requireGpu: true); }
catch (InvalidOperationException)
{
if (unavailable.IsReady || unavailable.UsingGpu) throw new Exception("GPU 失败后仍保留推理会话");
Console.WriteLine("PASS: GPU 不可用时拒绝运行,没有静默回退 CPU");
return;
}
throw new Exception("测试要求 GPU 不可用,但初始化成功");
}
if (args.Length < 2) throw new ArgumentException("请提供含双手的视频");
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS", "4");
var profiles = Path.GetFullPath(Path.Combine("artifacts", "amd-gpu-smoke", Guid.NewGuid().ToString("N")));
Environment.SetEnvironmentVariable("SOPHELPER_INFERENCE_PROFILE", profiles);
var hashes = new[] { palmPath, landmarkPath }.ToDictionary(p => p, p => SHA256.HashData(File.ReadAllBytes(p)));
using (var gpuHand = new MediaPipeHandDetector())
using (var cpuHand = new MediaPipeHandDetector())
{
gpuHand.Load(palmPath, landmarkPath, requireGpu: true);
cpuHand.Load(palmPath, landmarkPath, preferGpu: false);
if (!gpuHand.UsingGpu || !gpuHand.Backend.Contains(expectedBackend))
throw new Exception($"手部模型必须实际使用 {expectedBackend} GPU");
Console.WriteLine($"BACKEND: hand={gpuHand.Backend}");
using var video = new VideoCapture(args[1]);
if (!video.IsOpened()) throw new Exception("测试视频无法读取");
using var frame = new Mat();
var found = false;
for (var index = 0; index < 300 && video.Read(frame); index++)
{
if (index % 5 != 0) continue;
var expected = cpuHand.Detect(frame).OrderBy(h => h.Rect.X).ToArray();
var actual = gpuHand.Detect(frame).OrderBy(h => h.Rect.X).ToArray();
if (expected.Length != 2) continue;
if (actual.Length != 2) throw new Exception("GPU 未检出 CPU 基准中的双手");
var maxError = 0.0;
for (var hand = 0; hand < 2; hand++)
{
if (actual[hand].HandType != expected[hand].HandType || actual[hand].Keypoints.Count != 21)
throw new Exception("GPU 左右手分类或关键点数量与 CPU 不一致");
for (var point = 0; point < 21; point++)
{
var a = actual[hand].Keypoints[point];var b = expected[hand].Keypoints[point];
maxError = Math.Max(maxError, Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2)));
}
}
if (maxError > 2) throw new Exception($"GPU/CPU 手部关键点偏差过大:{maxError:F3}px");
Console.WriteLine($"PASS: 帧 {index} 检出左右双手、各 21 点,与 CPU 最大偏差 {maxError:F4}px");
gpuHand.SetThresholds(MediaPipeHandDetector.DefaultPalmThreshold, MediaPipeHandDetector.DefaultKeypointThreshold, 1);
if (gpuHand.Detect(frame).Count != 1) throw new Exception("GPU MaxHands=1 未生效");
gpuHand.SetThresholds(MediaPipeHandDetector.DefaultPalmThreshold, MediaPipeHandDetector.DefaultKeypointThreshold, 2);
if (gpuHand.Detect(frame).Count != 2) throw new Exception("GPU MaxHands=2 未生效");
Console.WriteLine(JsonSerializer.Serialize(new { handGpuMs = Time(() => gpuHand.Detect(frame)), handCpuMs = Time(() => cpuHand.Detect(frame)) }));
found = true;
break;
}
if (!found) throw new Exception("前 300 帧未找到双手验证样本");
}
foreach (var model in new[] { "palm", "landmark" })
{
var files = Directory.GetFiles(profiles, model + "-*.json");
if (files.Length != 1) throw new Exception("缺少独立算子分析文件:" + model);
using var profile = JsonDocument.Parse(File.ReadAllText(files[0]));
var convolutions = profile.RootElement.EnumerateArray().Where(e => e.TryGetProperty("args", out var a) &&
a.TryGetProperty("op_name", out var op) && (op.GetString()?.Contains("Conv", StringComparison.Ordinal) ?? false) && a.TryGetProperty("provider", out _)).ToArray();
if (convolutions.Length == 0 || convolutions.Any(e => e.GetProperty("args").GetProperty("provider").GetString() != expectedProvider))
throw new Exception(model + " 的卷积计算未全部分配给 " + expectedProvider);
Console.WriteLine($"PASS: {model} 的 {convolutions.Length} 条卷积算子记录全部使用 {expectedProvider}");
}
foreach (var (path, hash) in hashes)
if (!SHA256.HashData(File.ReadAllBytes(path)).SequenceEqual(hash)) throw new Exception("修改了原始 ONNX 模型:" + path);
Console.WriteLine("PASS: 原始模型文件保持不变;算子分析:" + profiles);
static double Time(Action action)
{
action();var watch = Stopwatch.StartNew();
for (var i = 0; i < 5; i++) action();
return watch.Elapsed.TotalMilliseconds / 5;
}