Files
live-app-translator/src/livesub/models/cuda_runtime.py
EJClaw c2e600fa3d
Some checks failed
Windows / verify (push) Has been cancelled
fix: GPU 로 모델을 못 올려도 CPU 로 시작 · cuBLAS 받는 중 정지하면 캡처를 켜지 않게
- preload_on_start(기본값)에서 모델 로드가 GPU 오류를 내면 ERROR 로 끝나던 것을,
  CPU 로 바꿔 다시 올리게 했다.
- cuBLAS 를 받는 중에 정지하면 받기는 계속되고, 끝난 뒤 캡처가 켜져 상태가 다시
  RUNNING 이 되던 것을 고쳤다. 시작 작업마다 전용 정지 이벤트를 넘기고, 받기는
  그 이벤트를 보고 멈추며, 시작 작업은 정지된 뒤에는 캡처·상태를 건드리지 않는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:11:19 +09:00

157 lines
6.4 KiB
Python

"""GPU 로 받아 적고 번역할 때 필요한 cuBLAS DLL 을 준비한다 (Windows).
CTranslate2 의 Windows 패키지는 GPU 계산 때 `cublas64_12.dll` 을 이름으로 찾아
불러온다. 그런데 이 DLL 은 패키지에 들어 있지 않다. 리눅스 개발 환경에서는
torch 가 같이 깔아 둔 cuBLAS 를 쓰기 때문에 문제가 드러나지 않았고, torch 를 뺀
포터블 exe 에서는 모델은 GPU 에 잘 올라가는데 첫 문장을 받아 적는 순간부터
매번 실패했다. 소리 게이지는 움직이는데 자막이 하나도 안 나오던 원인이다.
두 DLL 이 790MB 라 exe 에 넣으면 실행할 때마다 그만큼 임시폴더에 풀어야 한다.
그래서 처음 GPU 를 쓸 때 NVIDIA 가 PyPI 에 올린 공식 패키지를 한 번 받아 모델
폴더에 둔다. CUDA Toolkit 이 깔려 있어 이미 불러올 수 있으면 받지 않는다.
"""
from __future__ import annotations
import ctypes
import hashlib
import logging
import os
import sys
import threading
import urllib.request
import zipfile
from collections.abc import Callable
from pathlib import Path
from ..constants import models_dir
log = logging.getLogger(__name__)
#: cuBLAS 12.8 부터 RTX 50 계열(Blackwell)을 지원한다.
WHEEL_VERSION = "12.8.4.1"
WHEEL_URL = (
"https://files.pythonhosted.org/packages/70/61/"
"7d7b3c70186fb651d0fbd35b01dbfc8e755f69fd58f817f3d0f642df20c3/"
"nvidia_cublas_cu12-12.8.4.1-py3-none-win_amd64.whl"
)
WHEEL_SHA256 = "47e9b82132fa8d2b4944e708049229601448aaad7e6f296f630f2d1a32de35af"
WHEEL_SIZE = 567_544_208
#: 불러오는 순서대로. cublas64_12 가 cublasLt64_12 를 import 하므로 Lt 가 먼저다.
DLLS = ("cublasLt64_12.dll", "cublas64_12.dll")
_WHEEL_DIR = "nvidia/cublas/bin/"
ProgressCallback = Callable[[str, float], None]
class DownloadCancelled(Exception):
"""사용자가 받는 도중에 번역을 정지했다."""
#: os.add_dll_directory 가 돌려준 핸들. 닫히면 검색 경로에서 빠지므로 붙잡아 둔다.
_dll_dir_handle = None
#: 불러온 DLL 핸들. 참조가 사라지면 내려갈 수 있으므로 들고 있는다.
_loaded: list = []
_ready = False
def runtime_dir() -> Path:
"""모델 폴더 안에 둔다. 저장 위치를 옮길 때 모델과 같이 따라간다."""
return models_dir() / f"cuda-runtime-cublas-{WHEEL_VERSION}"
def installed(directory: Path | None = None) -> bool:
directory = directory or runtime_dir()
return all((directory / name).is_file() for name in DLLS)
def _system_has_cublas() -> bool:
"""CUDA Toolkit 등으로 이미 이름만으로 불러올 수 있는가."""
try:
_loaded.append(ctypes.WinDLL(DLLS[-1])) # type: ignore[attr-defined]
except OSError:
return False
return True
def ensure(progress: ProgressCallback | None = None, device: str = "cuda",
cancel: threading.Event | None = None) -> bool:
"""GPU 를 쓸 수 있게 cuBLAS 를 준비한다. 새로 받았거나 불러왔으면 True.
Windows 가 아니거나 CPU 로 돌릴 때는 아무것도 하지 않는다. 받기·불러오기에
실패하면 예외를 그대로 올린다. 호출한 쪽이 CPU 로 바꿀지 정한다.
`cancel` 이 켜지면 받기를 멈추고 `DownloadCancelled` 를 올린다.
"""
global _ready
if sys.platform != "win32" or device != "cuda":
return False
if _ready:
return True
directory = runtime_dir()
if not installed(directory) and _system_has_cublas():
log.info("시스템에 있는 cuBLAS 를 씁니다.")
else:
if not installed(directory):
download(directory, progress, cancel=cancel)
activate(directory)
_ready = True
return True
def download(directory: Path, progress: ProgressCallback | None = None,
url: str = WHEEL_URL, sha256: str = WHEEL_SHA256,
size: int = WHEEL_SIZE, cancel: threading.Event | None = None) -> None:
"""공식 패키지를 받아 DLL 두 개만 꺼낸다. 끝나면 패키지 파일은 지운다."""
directory.mkdir(parents=True, exist_ok=True)
part = directory / "cublas.whl.part"
total_mb = size / 2**20
log.info("GPU 계산 파일(cuBLAS %s) 내려받기: %s", WHEEL_VERSION, url)
digest = hashlib.sha256()
done = 0
last_pct = -1
try:
with urllib.request.urlopen(url, timeout=30) as resp, part.open("wb") as out:
while chunk := resp.read(1 << 20):
if cancel is not None and cancel.is_set():
raise DownloadCancelled("GPU 계산 파일 받기를 멈췄습니다")
out.write(chunk)
digest.update(chunk)
done += len(chunk)
pct = int(done * 100 / size) if size else 0
if progress and pct != last_pct:
last_pct = pct
progress(
f"GPU 계산 파일 받는 중 (처음 한 번만) "
f"{done / 2**20:.0f}/{total_mb:.0f}MB",
min(done / size, 1.0) if size else 0.0,
)
if done != size or digest.hexdigest() != sha256:
raise RuntimeError(
f"GPU 계산 파일이 손상됐습니다 ({done}바이트, 다시 시도해 주세요)"
)
with zipfile.ZipFile(part) as wheel:
for name in DLLS:
tmp = directory / f"{name}.part"
with wheel.open(_WHEEL_DIR + name) as src, tmp.open("wb") as dst:
while block := src.read(1 << 20):
dst.write(block)
tmp.replace(directory / name)
finally:
part.unlink(missing_ok=True)
log.info("GPU 계산 파일 준비 완료: %s", directory)
def activate(directory: Path) -> None:
"""DLL 을 전체 경로로 미리 불러 둔다.
CTranslate2 는 `cublas64_12.dll` 을 이름으로만 찾는다. 같은 이름의 모듈이 이미
올라와 있으면 Windows 는 그것을 쓰므로, 검색 경로 규칙에 기대지 않아도 된다.
"""
global _dll_dir_handle
if _dll_dir_handle is None and hasattr(os, "add_dll_directory"):
_dll_dir_handle = os.add_dll_directory(str(directory))
os.environ["PATH"] = f"{directory}{os.pathsep}{os.environ.get('PATH', '')}"
for name in DLLS:
_loaded.append(ctypes.WinDLL(str(directory / name))) # type: ignore[attr-defined]
log.info("cuBLAS 불러옴: %s", directory)