修复:补齐并预加载 Windows CUDA 13 推理依赖
This commit is contained in:
parent
000527f336
commit
5b0a9ca263
@ -4,13 +4,23 @@ namespace SopHelper.Engine.Inference;
|
||||
|
||||
internal static class CudaRuntime
|
||||
{
|
||||
// ORT 的 provider 位于 runtimes/win-x64/native,而随应用提供的 cuDNN 位于输出根目录。
|
||||
// 显式加载其绝对路径,避免依赖当前工作目录或系统 PATH,句柄保留到进程结束。
|
||||
private static readonly Lazy<nint> BundledCudnn = new(() =>
|
||||
// ORT 1.27+ 的 Windows GPU 包使用 CUDA 13。先加载应用目录中的依赖,
|
||||
// 避免 provider 子目录、dotnet 宿主或系统 CUDA 12 的搜索路径影响加载。
|
||||
private static readonly Lazy<nint[]> Libraries = new(() =>
|
||||
{
|
||||
var path = Path.Combine(AppContext.BaseDirectory, "cudnn64_9.dll");
|
||||
return OperatingSystem.IsWindows() && File.Exists(path) ? NativeLibrary.Load(path) : 0;
|
||||
if (!OperatingSystem.IsWindows()) return [];
|
||||
var handles = new List<nint>();
|
||||
foreach (var name in new[] { "cublasLt64_13.dll", "cublas64_13.dll", "cudart64_13.dll", "cudnn64_9.dll" })
|
||||
{
|
||||
var path = Path.Combine(AppContext.BaseDirectory, name);
|
||||
try { handles.Add(NativeLibrary.Load(File.Exists(path) ? path : name)); }
|
||||
catch (Exception error) when (error is DllNotFoundException or BadImageFormatException)
|
||||
{
|
||||
throw new InvalidOperationException($"无法加载 GPU 依赖 {name},请补齐匹配 CUDA 13 的运行库后重启程序。", error);
|
||||
}
|
||||
}
|
||||
return handles.ToArray(); // Keep libraries loaded for the process lifetime.
|
||||
});
|
||||
|
||||
internal static void Prepare() => _ = BundledCudnn.Value;
|
||||
internal static void Prepare() => _ = Libraries.Value;
|
||||
}
|
||||
|
||||
@ -5,7 +5,10 @@ using OpenCvSharp;
|
||||
using SopHelper.Engine.Common;
|
||||
using SopHelper.Engine.Inference;
|
||||
|
||||
if (args.Length < 1) throw new ArgumentException("用法:AmdGpu.Smoke 模型目录 双手视频路径 [--expect-unavailable]");
|
||||
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"))
|
||||
@ -36,8 +39,8 @@ using (var cpuYolo = new YoloDetector())
|
||||
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");
|
||||
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("测试视频无法读取");
|
||||
@ -88,9 +91,9 @@ foreach (var model in new[] { "yolo", "palm", "landmark" })
|
||||
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");
|
||||
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);
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
param(
|
||||
[string]$Destination = (Join-Path $PSScriptRoot '..\libs\cuda')
|
||||
[string]$Destination = (Join-Path $PSScriptRoot '..\libs\cuda'),
|
||||
[string]$CudaRuntimeSource = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@ -7,28 +8,57 @@ $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 校验失败,请移除下载文件后重试。'
|
||||
function Install-NvidiaArchive($Name, $BaseUri, $Package) {
|
||||
if (!$Package.relative_path -or !$Package.sha256) { throw "NVIDIA 清单缺少 Windows 运行库:$Name" }
|
||||
$archivePath = Join-Path $runtimeDirectory "$Name-runtime.zip"
|
||||
if (!(Test-Path -LiteralPath $archivePath)) {
|
||||
Write-Host "Downloading $Name..."
|
||||
Invoke-WebRequest -Uri ($BaseUri + $Package.relative_path) -OutFile $archivePath
|
||||
}
|
||||
if ((Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash -ne $Package.sha256) {
|
||||
throw "$Name SHA256 校验失败,请移除下载文件后重试。"
|
||||
}
|
||||
$archive = [IO.Compression.ZipFile]::OpenRead($archivePath)
|
||||
try {
|
||||
foreach ($entry in $archive.Entries) {
|
||||
$fileName = [IO.Path]::GetFileName($entry.Name)
|
||||
if ($entry.FullName -match '/bin/(?:x64/)?[^/]+\.dll$') {
|
||||
$target = Join-Path $runtimeDirectory $fileName
|
||||
} elseif ($fileName -match '^LICENSE|^EULA') {
|
||||
$target = Join-Path $runtimeDirectory "LICENSE-$Name-$fileName"
|
||||
} else { continue }
|
||||
[IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)
|
||||
Write-Host ('Extracted ' + $fileName)
|
||||
}
|
||||
}
|
||||
finally { $archive.Dispose() }
|
||||
Remove-Item -LiteralPath $archivePath
|
||||
}
|
||||
|
||||
$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)
|
||||
# ORT 1.27+ 的默认 Windows GPU 包使用 CUDA 13;仅放入应用目录,不修改系统 CUDA 或 PATH。
|
||||
$cudaDlls = @('cublasLt64_13.dll','cublas64_13.dll','cudart64_13.dll')
|
||||
if ($CudaRuntimeSource) {
|
||||
$source = [IO.Path]::GetFullPath($CudaRuntimeSource)
|
||||
foreach ($name in $cudaDlls) {
|
||||
if (!(Test-Path -LiteralPath (Join-Path $source $name))) { throw "CUDA 13 来源目录缺少 $name" }
|
||||
}
|
||||
foreach ($name in $cudaDlls) {
|
||||
$target = Join-Path $runtimeDirectory $name
|
||||
if ([IO.Path]::GetFullPath((Join-Path $source $name)) -ne $target) {
|
||||
Copy-Item -LiteralPath (Join-Path $source $name) -Destination $target -Force
|
||||
}
|
||||
}
|
||||
} elseif (@($cudaDlls | Where-Object { !(Test-Path -LiteralPath (Join-Path $runtimeDirectory $_)) }).Count) {
|
||||
$cuda = Invoke-RestMethod 'https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.2.json'
|
||||
foreach ($name in @('libcublas','cuda_cudart')) {
|
||||
Install-NvidiaArchive $name 'https://developer.download.nvidia.com/compute/cuda/redist/' $cuda.$name.'windows-x86_64'
|
||||
}
|
||||
}
|
||||
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.'
|
||||
if (!(Test-Path -LiteralPath (Join-Path $runtimeDirectory 'cudnn64_9.dll'))) {
|
||||
$cudnn = Invoke-RestMethod 'https://developer.download.nvidia.com/compute/cudnn/redist/redistrib_9.13.0.json'
|
||||
Install-NvidiaArchive 'cudnn' 'https://developer.download.nvidia.com/compute/cudnn/redist/' $cudnn.cudnn.'windows-x86_64'.cuda13
|
||||
}
|
||||
foreach ($name in $cudaDlls + 'cudnn64_9.dll') {
|
||||
if (!(Test-Path -LiteralPath (Join-Path $runtimeDirectory $name))) { throw "GPU 运行库不完整:$name" }
|
||||
}
|
||||
Write-Host 'CUDA 13 / cuDNN 9 ready. Rebuild and restart the application to use GPU inference.'
|
||||
|
||||
Loading…
Reference in New Issue
Block a user