From b0b8d30174fa2f0bebf79d96ca89f22b98b28565 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Sun, 8 Nov 2026 22:15:06 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=9A=E9=80=9A=E8=BF=87?= =?UTF-8?q?=20WebGPU=20=E5=92=8C=20Vulkan=20=E5=90=AF=E7=94=A8=20Linux=20A?= =?UTF-8?q?MD=20=E6=A8=A1=E5=9E=8B=E6=8E=A8=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LINUX.md | 38 +++++- .../Diagnostics/RuntimeCheck.cs | 10 +- src/SopHelper.Avalonia/Program.cs | 1 + .../VVMs/SopPage/SopPageViewModel.cs | 1 + .../Inference/InferenceSessionOptions.cs | 65 +++++++++++ .../Inference/MediaPipeHandDetector.cs | 38 ++---- .../Inference/YoloDetector.cs | 31 ++--- .../Pipeline/DetectionPipeline.cs | 18 ++- .../SopHelper.CrossPlatform.Engine.csproj | 3 +- tests/AmdGpu.Smoke/AmdGpu.Smoke.csproj | 4 + tests/AmdGpu.Smoke/Program.cs | 109 ++++++++++++++++++ tests/HandDetectionSmoke/Program.cs | 4 +- tools/Deploy-Linux.ps1 | 2 +- 13 files changed, 255 insertions(+), 69 deletions(-) create mode 100644 src/SopHelper.CrossPlatform.Engine/Inference/InferenceSessionOptions.cs create mode 100644 tests/AmdGpu.Smoke/AmdGpu.Smoke.csproj create mode 100644 tests/AmdGpu.Smoke/Program.cs diff --git a/LINUX.md b/LINUX.md index 72317fb..3f89963 100644 --- a/LINUX.md +++ b/LINUX.md @@ -22,7 +22,7 @@ Linux 海康已验证 2448×2048 BayerRG8 采集和 BGR 转换;标注训练仍 ## 后续部署 `tools/Deploy-Linux.ps1` 已切换为统一 Avalonia 工程;仅在明确要求部署时执行。 -它在新版本目录执行 `--check-runtime` 后更新启动入口,保留 `configs`、`models`、`workspace`。 +它在新版本目录执行 `--check-runtime` 和 `--check-gpu`,通过后更新启动入口,保留 `configs`、`models`、`workspace`。 图形环境需要 X11/XWayland、fontconfig 和中文字体;发布包自带 .NET 运行时。 ## GPU 渲染和帧率验证(2026-11-08) @@ -50,9 +50,7 @@ BGR → BGRA 使用 OpenCV 原生转换,直接写入 Avalonia 缓冲。每帧 实机 SDK 报告 `ResultingFrameRate=18.5652`、曝光 20000μs、负载 5013504 字节、 包大小 1500、包间隔 400;保留了现场采集参数。更高实机帧率需要继续检查相机和网络吞吐。 -**本次启用的是 GPU 图形渲染,AMD GPU 模型推理尚未实现。** 当前检测器的 GPU 路径是 -[ONNX Runtime CUDA](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html), -用于 NVIDIA,不能用于此 Radeon 核显;Linux 包目前使用 CPU 推理运行时。 +以上是此前仅使用 GPU 图形渲染时的记录。AMD 模型推理现已接入,见下节。 Linux 图形会话中可运行诊断;默认使用假相机,不占用现场相机: @@ -64,6 +62,38 @@ dotnet run --project tests/Mvs.Smoke -c Release -- --inspect-timing dotnet run --project tests/Pipeline.Smoke -c Release ``` +## AMD GPU 模型推理(2026-11-08) + +Linux 使用 ONNX Runtime `1.31.1` 和官方 WebGPU EP `0.5.0`,通过 Vulkan 在 AMD GPU +上运行原始 ONNX 模型。无需 ROCm,也不需要把模型转换成另一种格式。系统需提供 +`libvulkan.so.1`、硬件 Vulkan 驱动以及对 GPU 设备节点的访问权限。 + +启动检测时 Linux 要求模型成功建立 GPU 会话,初始化失败会明确报错,不整体回退 CPU。 +设备日志显示 `GPU (WebGPU / Vulkan / AMD)`;Windows 继续使用 CUDA 路径。 +手部模型的少量形状/后处理算子仍允许由 CPU 执行,神经网络卷积计算在 GPU 上。 + +在 Radeon 780M 实机上使用同一段双手视频对比 CPU/GPU: + +- 同时检出左右双手、各 21 个关键点,最大坐标偏差 0.0368 像素;MaxHands=1/2 均生效。 +- YOLO 的一个非空目标与 CPU 类别、置信度和目标框匹配。 +- YOLO、手掌和关键点模型的卷积算子分析记录全部来自 `WebGpuExecutionProvider`。 +- 禁用 Vulkan 驱动的故障测试确认拒绝运行,没有静默回退纯 CPU。 +- 界面中 2448×2048 合成动态画面约 62.6 次更新/秒,手部推理后端为 AMD WebGPU。 + +小模型的 GPU 调度和数据传输有开销,启用 GPU 不保证每个模型都比 CPU 更快。 +上述预览更新率不代表模型结果帧率。可用以下命令复验: + +```bash +./SopHelper.Avalonia --check-gpu +dotnet run --project tests/AmdGpu.Smoke -c Release -- models /path/to/hand_video.mp4 +# 故障注入:在独立测试进程中禁用 Vulkan 驱动。 +VK_DRIVER_FILES=/nonexistent/vulkan-driver.json dotnet run --project tests/AmdGpu.Smoke -c Release -- models --expect-unavailable +``` + +设置 `SOPHELPER_INFERENCE_PROFILE` 为输出目录,可为三个 GPU 会话生成独立的 ORT 算子分析文件。 +常规运行不启用分析,避免分析开销。后端机制见 +[ONNX Runtime WebGPU 文档](https://onnxruntime.ai/docs/execution-providers/WebGPU-ExecutionProvider.html)。 + ## 界面调整同步(2026-11-08 22:00) 已将提交 `6359fad`(包含 `3436d08` 的运行设置页)部署到 diff --git a/src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs b/src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs index da513ae..d30f004 100644 --- a/src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs +++ b/src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs @@ -8,20 +8,22 @@ namespace SopHelper.Diagnostics; internal static class RuntimeCheck { - public static int Run() + public static int Run(bool requireGpu = false) { try { var root=AppContext.BaseDirectory; using var yolo=new YoloDetector();using var hand=new MediaPipeHandDetector(); - yolo.Load(Path.Combine(root,"models/yolo11n.onnx"),[],preferGpu:false); - hand.Load(Path.Combine(root,"models/palm_detection_full_Nx3x192x192_post.onnx"),Path.Combine(root,"models/hand_landmark_sparse_Nx3x224x224.onnx"),false); + yolo.Load(Path.Combine(root,"models/yolo11n.onnx"),[],preferGpu:requireGpu,requireGpu:requireGpu); + hand.Load(Path.Combine(root,"models/palm_detection_full_Nx3x192x192_post.onnx"),Path.Combine(root,"models/hand_landmark_sparse_Nx3x224x224.onnx"),requireGpu,requireGpu); if(!yolo.IsReady||!hand.IsReady)throw new InvalidOperationException("模型未加载"); + if(requireGpu && (!yolo.UsingGpu || !hand.UsingGpu))throw new InvalidOperationException("要求 GPU 推理,但模型未使用 GPU"); using var frame=new Mat(480,640,MatType.CV_8UC3,Scalar.Black);yolo.Detect(frame);hand.Detect(frame); var config=SopConfigLoader.Parse("sop:\n name: runtime-check\n settings:\n auto_reset_on_complete: false\n steps:\n - id: 1\n name: timer\n detection:\n method: time_elapsed\n duration_ms: 1\n"); var engine=new SopEngine();engine.Load(config);engine.Start();Thread.Sleep(10);engine.ProcessFrame(new FrameResult()); if(engine.State!=EngineState.Completed)throw new Exception("SOP 状态机测试失败"); - Console.WriteLine(JsonSerializer.Serialize(new{passed=true,opencv=Cv2.GetVersionString(),classes=yolo.ClassNames.Count,hand=hand.IsReady,sop=engine.State.ToString()}));return 0; + Console.WriteLine(JsonSerializer.Serialize(new{passed=true,opencv=Cv2.GetVersionString(),classes=yolo.ClassNames.Count,hand=hand.IsReady, + yoloBackend=yolo.Backend,handBackend=hand.Backend,sop=engine.State.ToString()}));return 0; } catch(Exception error){Console.Error.WriteLine(error);return 1;} } diff --git a/src/SopHelper.Avalonia/Program.cs b/src/SopHelper.Avalonia/Program.cs index fc91d91..8e6ba47 100644 --- a/src/SopHelper.Avalonia/Program.cs +++ b/src/SopHelper.Avalonia/Program.cs @@ -6,6 +6,7 @@ internal static class Program [STAThread] public static int Main(string[] args) { + if(args.Contains("--check-gpu"))return Diagnostics.RuntimeCheck.Run(requireGpu:true); if(args.Contains("--check-runtime"))return Diagnostics.RuntimeCheck.Run(); return Presentation.DesktopRendering.Configure(AppBuilder.Configure().UsePlatformDetect()) .LogToTrace().StartWithClassicDesktopLifetime(args); diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs index 563ad53..5dc03fc 100644 --- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs @@ -624,6 +624,7 @@ public class SopPageViewModel : ViewModelBase PalmModelPath = ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx"), LandmarkModelPath = ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx"), FrameStride = Math.Max(1, config.Sop.Settings.FrameStride), + RequireGpu = OperatingSystem.IsLinux(), }; _pipeline.LoadModels(options); diff --git a/src/SopHelper.CrossPlatform.Engine/Inference/InferenceSessionOptions.cs b/src/SopHelper.CrossPlatform.Engine/Inference/InferenceSessionOptions.cs new file mode 100644 index 0000000..b3b3f3b --- /dev/null +++ b/src/SopHelper.CrossPlatform.Engine/Inference/InferenceSessionOptions.cs @@ -0,0 +1,65 @@ +using Microsoft.ML.OnnxRuntime; + +namespace SopHelper.Engine.Inference; + +internal static class InferenceSessionOptions +{ + // Register once for the lifetime of OrtEnv; all three models share the physical GPU. + private static readonly Lazy WebGpuDevice = new(() => + { + var root = AppContext.BaseDirectory; + var paths = new[] + { + Path.Combine(root, "libonnxruntime_providers_webgpu.so"), + Path.Combine(root, "runtimes", "linux-x64", "native", "libonnxruntime_providers_webgpu.so"), + }; + var library = paths.FirstOrDefault(File.Exists) + ?? throw new FileNotFoundException("缺少 WebGPU 推理运行库,请重新发布完整 Linux 包"); + var env = OrtEnv.Instance(); + env.RegisterExecutionProviderLibrary("sophelper_webgpu", library); + // Exclude software adapters. Prefer AMD when multiple hardware vendors are present. + return env.GetEpDevices() + .Where(d => d.EpName == "WebGpuExecutionProvider" && d.HardwareDevice.Type == OrtHardwareDeviceType.GPU) + .OrderByDescending(d => d.HardwareDevice.VendorId == 0x1002) + .FirstOrDefault() ?? throw new InvalidOperationException("未发现支持 WebGPU/Vulkan 的硬件 GPU,请检查 Vulkan 驱动和设备权限"); + }); + + internal static SessionOptions Create(bool gpu, string model, out string backend) + { + var options = new SessionOptions { GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL }; + backend = "CPU"; + try + { + // Also bounds CPU shape/postprocessing work in a GPU session. + CpuSessionTuning.Apply(options); + if (!gpu) return options; + if (OperatingSystem.IsLinux()) + { + var device = WebGpuDevice.Value; + options.AppendExecutionProvider(OrtEnv.Instance(), new[] { device }, new Dictionary + { + ["preferredLayout"] = "NHWC", + ["powerPreference"] = "high-performance", + ["validationMode"] = "disabled", + }); + var vendor = device.HardwareDevice.VendorId == 0x1002 ? "AMD" : $"0x{device.HardwareDevice.VendorId:X}"; + backend = $"GPU (WebGPU / Vulkan / {vendor})"; + } + else + { + CudaRuntime.Prepare(); + options.AppendExecutionProvider_CUDA(0); + backend = "GPU (CUDA)"; + } + var profile = Environment.GetEnvironmentVariable("SOPHELPER_INFERENCE_PROFILE"); + if (!string.IsNullOrWhiteSpace(profile)) + { + Directory.CreateDirectory(profile); + options.ProfileOutputPathPrefix = Path.Combine(Path.GetFullPath(profile), model + "-" + Guid.NewGuid().ToString("N")); + options.EnableProfiling = true; + } + return options; + } + catch { options.Dispose(); throw; } + } +} diff --git a/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs b/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs index 1c0b7f5..8b21cea 100644 --- a/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs +++ b/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs @@ -36,17 +36,20 @@ public class MediaPipeHandDetector : IDisposable /// 模型是否就绪(缺文件时上层跳过手部判定,不报错) public bool IsReady => _palm is not null && _landmark is not null; - /// 实际使用的设备(CUDA 不可用时回退 CPU) + /// 是否已创建 GPU 推理会话。 public bool UsingGpu { get; private set; } + private string _gpuBackend = "CPU"; + public string Backend => !IsReady ? "未加载" : UsingGpu ? _gpuBackend : "CPU"; public string? GpuFallbackReason { get; private set; } /// /// 加载两个模型。任缺其一则整个手部检测不启用。 /// - public void Load(string palmModelPath, string landmarkModelPath, bool preferGpu = true) + public void Load(string palmModelPath, string landmarkModelPath, bool preferGpu = true, bool requireGpu = false) { Dispose(); GpuFallbackReason = null; + if (requireGpu && !preferGpu) throw new ArgumentException("要求 GPU 推理时必须启用 preferGpu"); if (!File.Exists(palmModelPath) || !File.Exists(landmarkModelPath)) return; @@ -56,9 +59,10 @@ public class MediaPipeHandDetector : IDisposable { try { - using var options = Options(true); - _palm = new InferenceSession(palmModel, options); - _landmark = new InferenceSession(landmarkModelPath, options); + using var palmOptions = InferenceSessionOptions.Create(true, "palm", out _gpuBackend); + using var landmarkOptions = InferenceSessionOptions.Create(true, "landmark", out _); + _palm = new InferenceSession(palmModel, palmOptions); + _landmark = new InferenceSession(landmarkModelPath, landmarkOptions); UsingGpu = true; return; } @@ -66,10 +70,11 @@ public class MediaPipeHandDetector : IDisposable { Dispose(); // 第二个模型创建失败时也要释放第一个 GPU 会话。 GpuFallbackReason = ex.Message; + if (requireGpu) throw new InvalidOperationException("手部 GPU 推理初始化失败:" + ex.Message, ex); } } - using var cpuOptions = Options(false); + using var cpuOptions = InferenceSessionOptions.Create(false, "hand", out _); try { _palm = new InferenceSession(palmModel, cpuOptions); @@ -467,27 +472,6 @@ public class MediaPipeHandDetector : IDisposable } } - private static SessionOptions Options(bool cuda) - { - var o = new SessionOptions - { - GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, - }; - - try - { - if (!cuda) CpuSessionTuning.Apply(o); - if (cuda) - { - CudaRuntime.Prepare(); - o.AppendExecutionProvider_CUDA(0); - } - } - catch { o.Dispose(); throw; } - - return o; - } - /// public void Dispose() { diff --git a/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs b/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs index 5131aed..e032d2c 100644 --- a/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs +++ b/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs @@ -26,16 +26,19 @@ public class YoloDetector : IDisposable /// 实际使用的设备 public bool UsingGpu { get; private set; } + private string _gpuBackend = "CPU"; + public string Backend => !IsReady ? "未加载" : UsingGpu ? _gpuBackend : "CPU"; public string? GpuFallbackReason { get; private set; } /// /// 加载模型。classNames 顺序必须与训练时一致(decoding 出来的类别索引直接按它取名)。 /// - public void Load(string modelPath, IReadOnlyList classNames, int inputSize = 640, bool preferGpu = true) + public void Load(string modelPath, IReadOnlyList classNames, int inputSize = 640, bool preferGpu = true, bool requireGpu = false) { Dispose(); UsingGpu = false; GpuFallbackReason = null; + if (requireGpu && !preferGpu) throw new ArgumentException("要求 GPU 推理时必须启用 preferGpu"); if (!File.Exists(modelPath)) return; _classNames = classNames.ToArray(); @@ -45,13 +48,14 @@ public class YoloDetector : IDisposable { try { - using var options = Options(true); + using var options = InferenceSessionOptions.Create(true, "yolo", out _gpuBackend); _session = new InferenceSession(modelPath, options); UsingGpu = true; } catch (Exception ex) { GpuFallbackReason = ex.Message; + if (requireGpu) throw new InvalidOperationException("YOLO GPU 推理初始化失败:" + ex.Message, ex); } } @@ -59,7 +63,7 @@ public class YoloDetector : IDisposable { if (_session is null) { - using var cpuOptions = Options(false); + using var cpuOptions = InferenceSessionOptions.Create(false, "yolo", out _); _session = new InferenceSession(modelPath, cpuOptions); UsingGpu = false; } @@ -425,27 +429,6 @@ public class YoloDetector : IDisposable } } - private static SessionOptions Options(bool cuda) - { - var o = new SessionOptions - { - GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, - }; - - try - { - if (!cuda) CpuSessionTuning.Apply(o); - if (cuda) - { - CudaRuntime.Prepare(); - o.AppendExecutionProvider_CUDA(0); - } - } - catch { o.Dispose(); throw; } - - return o; - } - /// public void Dispose() { diff --git a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs index 75f2893..0a0e259 100644 --- a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs +++ b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs @@ -28,8 +28,10 @@ public class PipelineOptions /// 检测到的手最多几只 public int MaxHands { get; set; } = 2; - /// 允许 GPU(CUDA 不可用自动回退 CPU) + /// 优先 GPU:Linux 使用 WebGPU/Vulkan,Windows 使用 CUDA。 public bool PreferGpu { get; set; } = true; + /// GPU 初始化失败时拒绝运行,不回退到纯 CPU 会话。 + public bool RequireGpu { get; set; } /// /// 抽帧间隔:推理跟不上时丢弃中间帧,绝不排队堆积。 @@ -67,8 +69,8 @@ public class DetectionPipeline : IDisposable /// 推理平均耗时(毫秒) public double AvgInferenceMs { get; private set; } - public string HandBackend => !_hand.IsReady ? "未加载" : _hand.UsingGpu ? "GPU (CUDA)" : "CPU"; - public string YoloBackend => !_yolo.IsReady ? "未加载" : _yolo.UsingGpu ? "GPU (CUDA)" : "CPU"; + public string HandBackend => _hand.Backend; + public string YoloBackend => _yolo.Backend; /// 结果帧(在管线线程上触发) public event Action? ResultArrived; @@ -99,10 +101,14 @@ public class DetectionPipeline : IDisposable { try { - _yolo.Load(options.YoloModelPath, options.YoloClasses, options.YoloInputSize, options.PreferGpu); + _yolo.Load(options.YoloModelPath, options.YoloClasses, options.YoloInputSize, options.PreferGpu, options.RequireGpu); if (_yolo.GpuFallbackReason is not null) Warnings.Add($"YOLO GPU 不可用,已回退 CPU:{_yolo.GpuFallbackReason}"); } - catch (Exception ex) { Warnings.Add("目标检测模型加载失败:" + ex.Message); } + catch (Exception ex) + { + Warnings.Add("目标检测模型加载失败:" + ex.Message); + if (options.RequireGpu) throw; + } } else { @@ -114,7 +120,7 @@ public class DetectionPipeline : IDisposable { if (File.Exists(options.PalmModelPath) && File.Exists(options.LandmarkModelPath)) { - _hand.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu); + _hand.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu, options.RequireGpu); if (_hand.GpuFallbackReason is not null) Warnings.Add($"手部 GPU 不可用,已回退 CPU:{_hand.GpuFallbackReason}"); } else diff --git a/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj b/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj index d0691b7..5c2f8d9 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj +++ b/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj @@ -17,7 +17,8 @@ - + + diff --git a/tests/AmdGpu.Smoke/AmdGpu.Smoke.csproj b/tests/AmdGpu.Smoke/AmdGpu.Smoke.csproj new file mode 100644 index 0000000..5716f4b --- /dev/null +++ b/tests/AmdGpu.Smoke/AmdGpu.Smoke.csproj @@ -0,0 +1,4 @@ + + Exenet8.0enableenable + + diff --git a/tests/AmdGpu.Smoke/Program.cs b/tests/AmdGpu.Smoke/Program.cs new file mode 100644 index 0000000..6f9e389 --- /dev/null +++ b/tests/AmdGpu.Smoke/Program.cs @@ -0,0 +1,109 @@ +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 模型目录 双手视频路径 [--expect-unavailable]"); +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("AMD") || !gpuYolo.Backend.Contains("AMD")) + throw new Exception("三个模型必须实际使用 AMD 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() != "WebGpuExecutionProvider")) + throw new Exception(model + " 的卷积计算未全部分配给 WebGPU"); + Console.WriteLine($"PASS: {model} 的 {convolutions.Length} 条卷积算子记录全部使用 WebGpuExecutionProvider"); +} +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); +} diff --git a/tests/HandDetectionSmoke/Program.cs b/tests/HandDetectionSmoke/Program.cs index 6efbe3c..bbe7e1d 100644 --- a/tests/HandDetectionSmoke/Program.cs +++ b/tests/HandDetectionSmoke/Program.cs @@ -11,8 +11,8 @@ var palm = Path.Combine(modelDirectory, "palm_detection_full_Nx3x192x192_post.on var landmark = Path.Combine(modelDirectory, "hand_landmark_sparse_Nx3x224x224.onnx"); var before = SHA256.HashData(File.ReadAllBytes(palm)); using var detector = new MediaPipeHandDetector(); -detector.Load(palm, landmark, preferGpu: !args.Contains("--cpu")); -Console.WriteLine($"手部推理后端:{(detector.UsingGpu ? "GPU (CUDA)" : "CPU")}"); +detector.Load(palm, landmark, preferGpu: !args.Contains("--cpu"), requireGpu: args.Contains("--require-gpu")); +Console.WriteLine($"手部推理后端:{detector.Backend}"); if (detector.GpuFallbackReason is not null) Console.WriteLine($"GPU 回退原因:{detector.GpuFallbackReason}"); if (args.Contains("--require-gpu") && !detector.UsingGpu) throw new Exception("测试要求使用 GPU,但实际回退了 CPU"); using var video = new VideoCapture(positional[0]); diff --git a/tools/Deploy-Linux.ps1 b/tools/Deploy-Linux.ps1 index 38de7f6..f2e27ad 100644 --- a/tools/Deploy-Linux.ps1 +++ b/tools/Deploy-Linux.ps1 @@ -26,6 +26,6 @@ foreach ($model in $models) { & scp -o BatchMode=yes $path "${Target}:sophelper/models/" if ($LASTEXITCODE) { throw "Model transfer failed: $model" } } -& ssh -o BatchMode=yes $Target "tar -xzf ~/sophelper/$release.tar.gz -C ~/sophelper/releases/$release && chmod +x ~/sophelper/releases/$release/SopHelper.Avalonia && ~/sophelper/releases/$release/SopHelper.Avalonia --check-runtime && bash ~/sophelper/install-desktop.sh ~/sophelper/releases/$release" +& ssh -o BatchMode=yes $Target "tar -xzf ~/sophelper/$release.tar.gz -C ~/sophelper/releases/$release && chmod +x ~/sophelper/releases/$release/SopHelper.Avalonia && ~/sophelper/releases/$release/SopHelper.Avalonia --check-runtime && ~/sophelper/releases/$release/SopHelper.Avalonia --check-gpu && bash ~/sophelper/install-desktop.sh ~/sophelper/releases/$release" if ($LASTEXITCODE) { throw 'Installation or self-test failed; see ~/sophelper/workspace/logs/desktop.log' } Write-Host "Installed $release on $Target. Start SopHelper from its desktop launcher."