feat: 启用 CUDA GPU 推理并保留 CPU 回退

This commit is contained in:
sophelper 2026-11-05 22:40:32 +08:00
parent e98b669a7c
commit cbf97b6b4f
10 changed files with 145 additions and 21 deletions

1
.gitignore vendored
View File

@ -390,3 +390,4 @@ FodyWeavers.xsd
# 海康 MVS 托管 SDK 随项目提供;原生运行时由现场安装。
!/libs/
!/libs/MvCameraControl.Net.dll
/libs/cuda/

View File

@ -19,7 +19,7 @@ SopHelper.App net8.0-windows,Prism.DryIoc
纯 WPF 样式,无 HandyControl / SkiaSharp.Views.WPF
```
依赖包括 Prism.DryIoc、OpenCvSharp4、Microsoft.ML.OnnxRuntime、YamlDotNet 和海康 MVS SDK —— 没有
依赖包括 Prism.DryIoc、OpenCvSharp4、Microsoft.ML.OnnxRuntime.Gpu、YamlDotNet 和海康 MVS SDK —— 没有
GPL/AGPL 组件(YOLO 那段是自己写的,就是为了不引 GPL-3.0 的 YoloDotNet)。
## 跑起来
@ -54,6 +54,30 @@ dotnet build SopHelper.slnx
dotnet run --project tests/HandDetectionSmoke/HandDetectionSmoke.csproj -- path/to/two-hands.mp4
```
### GPU 推理
使用 ONNX Runtime GPU 1.23.0,手掌、手部关键点与 YOLO 默认优先使用 NVIDIA CUDA,
不可用时自动回退 CPU。加载配方后,日志会显示手部与 YOLO 的实际推理后端,以及 GPU 回退原因。
图像裁剪、预处理及画面绘制仍在 CPU 上执行。
现场需安装 NVIDIA 驱动、兼容的 CUDA 12.x 运行库(本机为 CUDA 12.6),并确保 CUDA `bin`
在进程 PATH 中;还需要 cuDNN 9。可从项目目录执行以下脚本,从 NVIDIA 官方下载 cuDNN,
校验 SHA256 后将 DLL 及许可证放入 `libs/cuda/`:
```powershell
pwsh -NoProfile -File tools/Install-GpuRuntime.ps1
dotnet build SopHelper.slnx
```
`libs/cuda/` 不入 Git,构建/发布时自动携带其中的 DLL 和许可证。换机器部署时也需提供 CUDA 12.x
运行库。脚本不修改系统安装和 PATH。兼容要求见 [ONNX Runtime CUDA 文档](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html)。
强制验证 GPU(若回退 CPU 则测试失败);对比 CPU 可将 `--require-gpu` 换成 `--cpu`:
```bash
dotnet run --project tests/HandDetectionSmoke/HandDetectionSmoke.csproj -- path/to/two-hands.mp4 --require-gpu
```
### 海康相机取视频
参考 `plcsharp` 的 `MvCameraControl` 接法,支持海康机器人 GigE / USB 工业相机。

View File

@ -547,6 +547,7 @@ public class SopPageViewModel : ViewModelBase
};
_pipeline.LoadModels(options);
Log("info", $"推理设备:手部={_pipeline.HandBackend},YOLO={_pipeline.YoloBackend}");
StepCards.Clear();
Rois.Clear();

View File

@ -0,0 +1,16 @@
using System.Runtime.InteropServices;
namespace SopHelper.Engine.Inference;
internal static class CudaRuntime
{
// ORT 的 provider 位于 runtimes/win-x64/native,而随应用提供的 cuDNN 位于输出根目录。
// 显式加载其绝对路径,避免依赖当前工作目录或系统 PATH,句柄保留到进程结束。
private static readonly Lazy<nint> BundledCudnn = new(() =>
{
var path = Path.Combine(AppContext.BaseDirectory, "cudnn64_9.dll");
return OperatingSystem.IsWindows() && File.Exists(path) ? NativeLibrary.Load(path) : 0;
});
internal static void Prepare() => _ = BundledCudnn.Value;
}

View File

@ -37,12 +37,15 @@ public class MediaPipeHandDetector : IDisposable
/// <summary>实际使用的设备(CUDA 不可用时回退 CPU)</summary>
public bool UsingGpu { get; private set; }
public string? GpuFallbackReason { get; private set; }
/// <summary>
/// 加载两个模型。任缺其一则整个手部检测不启用。
/// </summary>
public void Load(string palmModelPath, string landmarkModelPath, bool preferGpu = false)
public void Load(string palmModelPath, string landmarkModelPath, bool preferGpu = true)
{
Dispose();
GpuFallbackReason = null;
if (!File.Exists(palmModelPath) || !File.Exists(landmarkModelPath))
return;
@ -52,19 +55,26 @@ public class MediaPipeHandDetector : IDisposable
{
try
{
_palm = new InferenceSession(palmModel, Options(true));
_landmark = new InferenceSession(landmarkModelPath, Options(true));
using var options = Options(true);
_palm = new InferenceSession(palmModel, options);
_landmark = new InferenceSession(landmarkModelPath, options);
UsingGpu = true;
return;
}
catch
catch (Exception ex)
{
// CUDA 不可用,回退 CPU
Dispose(); // 第二个模型创建失败时也要释放第一个 GPU 会话。
GpuFallbackReason = ex.Message;
}
}
_palm = new InferenceSession(palmModel, Options(false));
_landmark = new InferenceSession(landmarkModelPath, Options(false));
using var cpuOptions = Options(false);
try
{
_palm = new InferenceSession(palmModel, cpuOptions);
_landmark = new InferenceSession(landmarkModelPath, cpuOptions);
}
catch { Dispose(); throw; }
UsingGpu = false;
}
@ -462,7 +472,15 @@ public class MediaPipeHandDetector : IDisposable
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
if (cuda) o.AppendExecutionProvider_CUDA(0);
try
{
if (cuda)
{
CudaRuntime.Prepare();
o.AppendExecutionProvider_CUDA(0);
}
}
catch { o.Dispose(); throw; }
return o;
}
@ -474,6 +492,7 @@ public class MediaPipeHandDetector : IDisposable
_landmark?.Dispose();
_palm = null;
_landmark = null;
UsingGpu = false;
}
/// <summary>letterbox 参数(回映射用)</summary>

View File

@ -23,12 +23,16 @@ public class YoloDetector : IDisposable
/// <summary>实际使用的设备</summary>
public bool UsingGpu { get; private set; }
public string? GpuFallbackReason { get; private set; }
/// <summary>
/// 加载模型。classNames 顺序必须与训练时一致(decoding 出来的类别索引直接按它取名)。
/// </summary>
public void Load(string modelPath, IReadOnlyList<string> classNames, int inputSize = 640, bool preferGpu = false)
public void Load(string modelPath, IReadOnlyList<string> classNames, int inputSize = 640, bool preferGpu = true)
{
Dispose();
UsingGpu = false;
GpuFallbackReason = null;
if (!File.Exists(modelPath)) return;
_classNames = classNames.ToArray();
@ -38,17 +42,19 @@ public class YoloDetector : IDisposable
{
try
{
_session = new InferenceSession(modelPath, Options(true));
using var options = Options(true);
_session = new InferenceSession(modelPath, options);
UsingGpu = true;
return;
}
catch
catch (Exception ex)
{
// CUDA 不可用,回退 CPU
GpuFallbackReason = ex.Message;
}
}
_session = new InferenceSession(modelPath, Options(false));
using var cpuOptions = Options(false);
_session = new InferenceSession(modelPath, cpuOptions);
UsingGpu = false;
}
@ -399,7 +405,15 @@ public class YoloDetector : IDisposable
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
if (cuda) o.AppendExecutionProvider_CUDA(0);
try
{
if (cuda)
{
CudaRuntime.Prepare();
o.AppendExecutionProvider_CUDA(0);
}
}
catch { o.Dispose(); throw; }
return o;
}
@ -409,5 +423,6 @@ public class YoloDetector : IDisposable
{
_session?.Dispose();
_session = null;
UsingGpu = false;
}
}

View File

@ -29,7 +29,7 @@ public class PipelineOptions
public int MaxHands { get; set; } = 2;
/// <summary>允许 GPU(CUDA 不可用自动回退 CPU)</summary>
public bool PreferGpu { get; set; }
public bool PreferGpu { get; set; } = true;
/// <summary>
/// 抽帧间隔:推理跟不上时丢弃中间帧,绝不排队堆积。
@ -61,6 +61,9 @@ public class DetectionPipeline : IDisposable
/// <summary>推理平均耗时(毫秒)</summary>
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";
/// <summary>结果帧(在管线线程上触发)</summary>
public event Action<FrameResult>? ResultArrived;
@ -86,6 +89,7 @@ public class DetectionPipeline : IDisposable
if (File.Exists(options.YoloModelPath))
{
_yolo.Load(options.YoloModelPath, options.YoloClasses, options.YoloInputSize, options.PreferGpu);
if (_yolo.GpuFallbackReason is not null) Warnings.Add($"YOLO GPU 不可用,已回退 CPU:{_yolo.GpuFallbackReason}");
}
else
{
@ -98,6 +102,7 @@ public class DetectionPipeline : IDisposable
if (File.Exists(options.PalmModelPath) && File.Exists(options.LandmarkModelPath))
{
_hand.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu);
if (_hand.GpuFallbackReason is not null) Warnings.Add($"手部 GPU 不可用,已回退 CPU:{_hand.GpuFallbackReason}");
}
else
{

View File

@ -19,8 +19,13 @@
<Private>true</Private>
</Reference>
<PackageReference Include="OpenCvSharp4.Windows" Version="4.10.0.20241108" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.23.0" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.Gpu" Version="1.23.0" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\libs\cuda\*.dll" Link="%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<None Include="..\..\libs\cuda\LICENSE*" Link="licenses\cudnn\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@ -3,15 +3,19 @@ using OpenCvSharp;
using SopHelper.Engine.Common;
using SopHelper.Engine.Inference;
if (args.Length == 0)
var positional = args.Where(a => !a.StartsWith("--")).ToArray();
if (positional.Length == 0)
throw new ArgumentException("请提供含双手的视频路径;第二个参数可指定模型目录,默认 models");
var modelDirectory = args.Length > 1 ? args[1] : "models";
var modelDirectory = positional.Length > 1 ? positional[1] : "models";
var palm = Path.Combine(modelDirectory, "palm_detection_full_Nx3x192x192_post.onnx");
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);
using var video = new VideoCapture(args[0]);
detector.Load(palm, landmark, preferGpu: !args.Contains("--cpu"));
Console.WriteLine($"手部推理后端:{(detector.UsingGpu ? "GPU (CUDA)" : "CPU")}");
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]);
if (!video.IsOpened()) throw new InvalidOperationException("视频无法打开");
using var frame = new Mat();
var found = false;

View File

@ -0,0 +1,34 @@
param(
[string]$Destination = (Join-Path $PSScriptRoot '..\libs\cuda')
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$runtimeDirectory = [IO.Path]::GetFullPath($Destination)
New-Item -ItemType Directory -Path $runtimeDirectory -Force | Out-Null
# NVIDIA 官方 cuDNN 9 / CUDA 12 发行包;仅解压运行所需 DLL 和许可证,不修改系统 PATH。
$manifest = Invoke-RestMethod -Uri 'https://developer.download.nvidia.com/compute/cudnn/redist/redistrib_9.5.1.json'
$package = $manifest.cudnn.'windows-x86_64'.cuda12
$archivePath = Join-Path $runtimeDirectory 'cudnn-runtime.zip'
if (!(Test-Path -LiteralPath $archivePath)) {
Write-Host 'Downloading NVIDIA cuDNN (about 532 MiB)...'
Invoke-WebRequest -Uri ('https://developer.download.nvidia.com/compute/cudnn/redist/' + $package.relative_path) -OutFile $archivePath
}
if ((Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash -ne $package.sha256) {
throw 'cuDNN SHA256 校验失败,请移除下载文件后重试。'
}
$archive = [IO.Compression.ZipFile]::OpenRead($archivePath)
try {
foreach ($entry in $archive.Entries) {
if ($entry.FullName -notmatch '/bin/[^/]+\.dll$' -and $entry.Name -notmatch '^LICENSE') { continue }
$target = Join-Path $runtimeDirectory $entry.Name
[IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)
Write-Host ('Extracted ' + $entry.Name)
}
}
finally { $archive.Dispose() }
if (!(Test-Path -LiteralPath (Join-Path $runtimeDirectory 'cudnn64_9.dll'))) { throw '发行包中未找到 cuDNN DLL' }
Remove-Item -LiteralPath $archivePath
Write-Host 'cuDNN ready. Rebuild the application to copy DLLs to its output directory.'