113 lines
6.7 KiB
C#
113 lines
6.7 KiB
C#
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 yoloPath = Path.Combine(models, "yolo11n.onnx");
|
||
if (args.Contains("--expect-unavailable"))
|
||
{
|
||
using var unavailable = new YoloDetector();
|
||
try { unavailable.Load(yoloPath, [], 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 palmPath = Path.Combine(models, "palm_detection_full_Nx3x192x192_post.onnx");
|
||
var landmarkPath = Path.Combine(models, "hand_landmark_sparse_Nx3x224x224.onnx");
|
||
var hashes = new[] { yoloPath, palmPath, landmarkPath }.ToDictionary(p => p, p => SHA256.HashData(File.ReadAllBytes(p)));
|
||
using (var gpuHand = new MediaPipeHandDetector())
|
||
using (var cpuHand = new MediaPipeHandDetector())
|
||
using (var gpuYolo = new YoloDetector())
|
||
using (var cpuYolo = new YoloDetector())
|
||
{
|
||
gpuHand.Load(palmPath, landmarkPath, requireGpu: true);
|
||
cpuHand.Load(palmPath, landmarkPath, preferGpu: false);
|
||
gpuYolo.Load(yoloPath, [], requireGpu: true);
|
||
cpuYolo.Load(yoloPath, [], preferGpu: false);
|
||
if (!gpuHand.UsingGpu || !gpuYolo.UsingGpu || !gpuHand.Backend.Contains(expectedBackend) || !gpuYolo.Backend.Contains(expectedBackend))
|
||
throw new Exception($"三个模型必须实际使用 {expectedBackend} GPU");
|
||
Console.WriteLine($"BACKEND: hand={gpuHand.Backend}, yolo={gpuYolo.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");
|
||
var expectedObjects = cpuYolo.Detect(frame);
|
||
var actualObjects = gpuYolo.Detect(frame);
|
||
if (expectedObjects.Count == 0) throw new Exception("样本缺少 YOLO 检测目标,不能验证空结果");
|
||
if (expectedObjects.Count != actualObjects.Count || expectedObjects.Any(e => !actualObjects.Any(a => a.Label == e.Label &&
|
||
Math.Abs(a.Confidence - e.Confidence) < 0.02 && IoU(a.Rect, e.Rect) > 0.95)))
|
||
throw new Exception("GPU YOLO 目标框、置信度或类别与 CPU 不一致");
|
||
Console.WriteLine($"PASS: YOLO {actualObjects.Count} 个非空目标与 CPU 基准一致");
|
||
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)),
|
||
yoloGpuMs = Time(() => gpuYolo.Detect(frame)), yoloCpuMs = Time(() => cpuYolo.Detect(frame)) }));
|
||
found = true;
|
||
break;
|
||
}
|
||
if (!found) throw new Exception("前 300 帧未找到双手验证样本");
|
||
}
|
||
foreach (var model in new[] { "yolo", "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;
|
||
}
|
||
static float IoU(DetRect a, DetRect b)
|
||
{
|
||
var intersection = Math.Max(0, Math.Min(a.Right, b.Right) - Math.Max(a.X, b.X)) * Math.Max(0, Math.Min(a.Bottom, b.Bottom) - Math.Max(a.Y, b.Y));
|
||
return intersection / Math.Max(1e-6f, a.W * a.H + b.W * b.H - intersection);
|
||
}
|