启用CUDA版PyTorch并验证GPU自动标注
This commit is contained in:
parent
56fd2194e1
commit
442fb282b7
@ -83,7 +83,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
|
||||
|
||||
普通调试构建需要机器安装 .NET 8。完整独立包使用 `pwsh -File tools/Publish-Avalonia.ps1 -RuntimeIdentifiers win-x64`,其中包含 .NET,可整体复制到其他 Windows x64 目录。使用 `SopHelper.Avalonia.exe --import-recipes 原数据根目录` 导入已有配方;以后整体移动运行目录时,启动会自动更新配方内部路径。
|
||||
|
||||
运行 `SopHelper.Avalonia.exe --check-standalone` 会实际验证 CPU 推理、本地 Python 依赖及 YOLO、SAM2 权重加载。GPU 另用 `--check-gpu` 验证,需要兼容的 NVIDIA 驱动和 CUDA 运行库;当前 Python 是 CPU 版,GPU 训练需要另备 CUDA 版 PyTorch。海康 USB/GigE 设备的系统驱动仍需在目标机器安装,复制用户态 DLL 不会安装硬件驱动。
|
||||
运行 `SopHelper.Avalonia.exe --check-standalone` 会实际验证 CPU 推理、本地 Python 依赖及 YOLO、SAM2 权重加载。GPU 另用 `--check-gpu` 验证。Windows 的 `tools/Setup-Python.ps1 -Sam2` 默认安装配套的 PyTorch 2.11.0 / TorchVision 0.26.0 CUDA 12.8 版本,并实际执行 CUDA 运算验证;需要兼容的 NVIDIA 驱动,CUDA 运行库随 PyTorch 提供。标注与训练的设备保持 `auto` 即优先使用 GPU;只需 CPU 时安装命令加 `-Cpu`。修改源码侧 Python 后,重新构建或发布以更新程序运行目录中的独立 Python。海康 USB/GigE 设备的系统驱动仍需在目标机器安装,复制用户态 DLL 不会安装硬件驱动。
|
||||
|
||||
## 验证
|
||||
|
||||
@ -92,6 +92,8 @@ dotnet run --project tests/Avalonia.Smoke -c Release
|
||||
dotnet run --project tests/PartCatalog.Smoke -c Release
|
||||
dotnet run --project tests/RecordingLimit.Smoke -c Release
|
||||
python/python.exe tests/Training.Smoke/test_recipe_training.py
|
||||
# GPU 检查会实际执行 TorchVision CUDA 算子及 SAM2 自动标注,使用临时测试帧。
|
||||
python/python.exe tests/Training.Smoke/check_gpu.py
|
||||
dotnet run --project tests/OpenCv.Smoke -c Release
|
||||
dotnet run --project tests/HandednessSmoke -c Release
|
||||
dotnet run --project tests/Training.Smoke -c Release -- python/python.exe
|
||||
|
||||
58
tests/Training.Smoke/check_gpu.py
Normal file
58
tests/Training.Smoke/check_gpu.py
Normal file
@ -0,0 +1,58 @@
|
||||
"""Verify real CUDA kernels and SAM2 propagation without touching user annotations."""
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from torchvision.ops import nms
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--runtime-root", type=Path, default=Path(__file__).resolve().parents[2])
|
||||
runtime_root = parser.parse_args().runtime_root.resolve()
|
||||
assert torch.cuda.is_available(), "CUDA is unavailable in this Python runtime"
|
||||
boxes = torch.tensor([[0, 0, 20, 20], [1, 1, 19, 19]], dtype=torch.float32, device="cuda")
|
||||
scores = torch.tensor([0.9, 0.8], device="cuda")
|
||||
assert nms(boxes, scores, 0.5).tolist() == [0], "TorchVision CUDA NMS failed"
|
||||
del boxes, scores
|
||||
torch.cuda.empty_cache()
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
spec = importlib.util.spec_from_file_location("worker", runtime_root / "tools" / "worker.py")
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(worker)
|
||||
messages = []
|
||||
worker.emit = lambda message, **kwargs: messages.append(message)
|
||||
started = time.perf_counter()
|
||||
with tempfile.TemporaryDirectory(prefix="sam2-gpu-check-") as temporary:
|
||||
root = Path(temporary)
|
||||
frames = root / "frames"
|
||||
frames.mkdir()
|
||||
for index in range(3):
|
||||
image = np.full((192, 256, 3), 210, dtype=np.uint8)
|
||||
cv2.rectangle(image, (70 + index * 2, 50), (150 + index * 2, 130), (40, 60, 200), -1)
|
||||
assert cv2.imwrite(str(frames / f"{index:06d}.jpg"), image)
|
||||
project = root / "project.json"
|
||||
worker.save_json(project, {"name": "GPU测试零件", "width": 256, "height": 192,
|
||||
"frames": [{"index": i, "image": f"frames/{i:06d}.jpg", "status": "reviewed" if i == 0 else "unlabeled",
|
||||
"prompt": i == 0, "box": [70, 50, 151, 131] if i == 0 else None} for i in range(3)]})
|
||||
worker.propagate({"project": str(project), "device": "auto"})
|
||||
torch.cuda.synchronize()
|
||||
result = worker.read_json(project)
|
||||
assert result["frames"][0]["status"] == "reviewed"
|
||||
assert all(f["status"] == "auto" for f in result["frames"][1:])
|
||||
assert any("cuda" in message for message in messages), "SAM2 did not select CUDA"
|
||||
assert torch.cuda.max_memory_allocated() > 50_000_000, "SAM2 did not allocate model memory on GPU"
|
||||
print(json.dumps({"passed": True, "torch": torch.__version__, "cuda": torch.version.cuda,
|
||||
"gpu": torch.cuda.get_device_name(0), "auto_frames": 2,
|
||||
"peak_gpu_mb": round(torch.cuda.max_memory_allocated() / 1024 ** 2, 1),
|
||||
"seconds": round(time.perf_counter() - started, 2)}, ensure_ascii=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -18,11 +18,9 @@ if (!(Test-Path -LiteralPath $pythonPath)) {
|
||||
Invoke-Checked $pythonPath @('-m', 'ensurepip', '--upgrade')
|
||||
}
|
||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--upgrade', 'pip')
|
||||
if ($Cpu) {
|
||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', 'torch', 'torchvision', '--index-url', 'https://download.pytorch.org/whl/cpu')
|
||||
} else {
|
||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', 'torch', 'torchvision', '--index-url', 'https://download.pytorch.org/whl/cu128')
|
||||
}
|
||||
$torchFlavor = if ($Cpu) { 'cpu' } else { 'cu128' }
|
||||
# Pin a matching pair: an already installed newer CPU wheel otherwise satisfies an unpinned install.
|
||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--upgrade', "torch==2.11.0+$torchFlavor", "torchvision==0.26.0+$torchFlavor", '--index-url', "https://download.pytorch.org/whl/$torchFlavor")
|
||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '-r', (Join-Path $PSScriptRoot 'requirements.txt'))
|
||||
if ($Sam2) {
|
||||
# SAM2's optional CUDA extension is unnecessary for basic box propagation on Windows.
|
||||
@ -30,4 +28,7 @@ if ($Sam2) {
|
||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', 'wheel', 'huggingface_hub')
|
||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--no-build-isolation', 'git+https://github.com/facebookresearch/sam2.git@2b90b9f5ceec907a1c18123530e92e794ad901a4')
|
||||
}
|
||||
if (!$Cpu) {
|
||||
Invoke-Checked $pythonPath @('-c', 'import torch; assert torch.cuda.is_available(), "CUDA unavailable: check the NVIDIA driver or explicitly use -Cpu"; x=torch.ones((32,32),device="cuda"); torch.cuda.synchronize(); print("GPU ready:",torch.cuda.get_device_name(0),"PyTorch",torch.__version__)')
|
||||
}
|
||||
Write-Host "完成。内置环境: $pythonPath;请重新构建/发布程序以携带 python 子目录。"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user