fix: GPU 로 모델을 못 올려도 CPU 로 시작 · cuBLAS 받는 중 정지하면 캡처를 켜지 않게
Some checks failed
Windows / verify (push) Has been cancelled

- preload_on_start(기본값)에서 모델 로드가 GPU 오류를 내면 ERROR 로 끝나던 것을,
  CPU 로 바꿔 다시 올리게 했다.
- cuBLAS 를 받는 중에 정지하면 받기는 계속되고, 끝난 뒤 캡처가 켜져 상태가 다시
  RUNNING 이 되던 것을 고쳤다. 시작 작업마다 전용 정지 이벤트를 넘기고, 받기는
  그 이벤트를 보고 멈추며, 시작 작업은 정지된 뒤에는 캡처·상태를 건드리지 않는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-05 15:11:19 +09:00
parent 176e06c4bd
commit c2e600fa3d
4 changed files with 136 additions and 18 deletions

View File

@@ -27,6 +27,7 @@ from ..audio import (
from ..config import AppConfig
from ..constants import LANGUAGE_CODES, user_data_dir
from ..models import Glossary, ModelManager, cuda_runtime
from ..models.cuda_runtime import DownloadCancelled
from ..models.manager import apply_vram_limit
from ..models.packs import build_glossary
from ..models.speech_level import (
@@ -96,10 +97,15 @@ class TranslationEngine:
def start(self) -> None:
if self.running:
return
self._stop.clear()
# clear() 가 아니라 새로 만든다. 정지된 이전 시작 작업(예: cuBLAS 받는 중)이
# 아직 끝나지 않았을 수 있는데, 같은 이벤트를 다시 끄면 그 작업이 정지된
# 줄 모르고 캡처를 켜 버린다.
self._stop = threading.Event()
self._emit_status(EngineState.LOADING, "모델을 준비하고 있습니다…", 0.0)
thread = threading.Thread(target=self._bootstrap, name="engine-boot", daemon=True)
thread = threading.Thread(
target=self._bootstrap, args=(self._stop,), name="engine-boot", daemon=True
)
thread.start()
self._threads = [thread]
@@ -151,23 +157,40 @@ class TranslationEngine:
return True
# --- 내부 스레드 ----------------------------------------------------
def _bootstrap(self) -> None:
def _bootstrap(self, stop: threading.Event) -> None:
"""모델·캡처를 준비한다. `stop` 은 이 시작 작업 전용 정지 신호다.
준비 도중(cuBLAS 받기, 모델 올리기)에 정지를 누를 수 있다. 그때는
캡처를 켜지도 상태를 바꾸지도 않고 조용히 끝낸다.
"""
def report(msg: str, pct: float) -> None:
if not stop.is_set():
self._emit_status(EngineState.LOADING, msg, pct)
self._cpu_notice = ""
try:
# 설정이 바뀐 채로 재시작됐을 수 있으므로 매 시작마다 맞춘다.
self.sync_performance()
self.models.use_device(self.config.models.device)
self._prepare_gpu()
self._prepare_gpu(report, stop)
if stop.is_set():
return
perf = self.config.performance
if perf.game_mode and self.models.device == "cuda":
# 모델을 올리기 *전에* 걸어야 상한이 실제로 먹는다.
apply_vram_limit(perf.vram_limit_ratio, self.config.models.device_index)
if self.config.models.preload_on_start:
self.models.preload(
lambda msg, pct: self._emit_status(EngineState.LOADING, msg, pct)
)
self._capture = create_capture(self.config.audio)
self._capture.start()
self._preload(report)
if stop.is_set():
return
capture = create_capture(self.config.audio)
capture.start()
self._capture = capture
if stop.is_set():
# stop() 이 캡처를 확인한 뒤에 여기 왔을 수 있다. 직접 닫는다.
capture.stop()
self._capture = None
return
workers = [
threading.Thread(target=self._segment_loop, name="engine-segment", daemon=True),
@@ -177,21 +200,33 @@ class TranslationEngine:
w.start()
self._threads.extend(workers)
kind = "프로그램별 캡처" if self._capture.per_process else "출력 장치 전체"
kind = "프로그램별 캡처" if capture.per_process else "출력 장치 전체"
message = self._cpu_notice or f"듣는 중 · {kind}"
self._emit_status(EngineState.RUNNING, message, 1.0)
except (CaptureError, OSError, RuntimeError, ImportError) as exc:
log.exception("엔진 시작 실패")
self._emit_status(EngineState.ERROR, str(exc))
if not stop.is_set():
self._emit_status(EngineState.ERROR, str(exc))
def _prepare_gpu(self) -> None:
def _preload(self, report) -> None:
"""모델을 미리 올린다. GPU 로 안 올라가면 CPU 로 바꿔 다시 올린다."""
try:
self.models.preload(report)
except Exception as exc:
if self.models.device != "cuda" or not _GPU_ERROR.search(str(exc)):
raise
log.warning("GPU 로 모델을 올리지 못했습니다: %s", exc, exc_info=True)
self._fall_back_to_cpu(f"GPU 오류: {_short(exc)}")
self.models.preload(report)
def _prepare_gpu(self, report, stop: threading.Event) -> None:
"""GPU 계산에 필요한 파일을 준비한다. 안 되면 CPU 로 돌린다."""
if self.models.device != "cuda":
return
try:
cuda_runtime.ensure(
lambda msg, pct: self._emit_status(EngineState.LOADING, msg, pct)
)
cuda_runtime.ensure(report, cancel=stop)
except DownloadCancelled:
log.info("cuBLAS 받기를 멈췄습니다 (번역 정지)")
except Exception as exc: # noqa: BLE001 - 받기 실패여도 자막은 나와야 한다
log.warning("GPU 계산 파일을 준비하지 못했습니다: %s", exc, exc_info=True)
self._fall_back_to_cpu(f"GPU 계산 파일을 받지 못했습니다 ({_short(exc)})")

View File

@@ -18,6 +18,7 @@ import hashlib
import logging
import os
import sys
import threading
import urllib.request
import zipfile
from collections.abc import Callable
@@ -43,6 +44,10 @@ _WHEEL_DIR = "nvidia/cublas/bin/"
ProgressCallback = Callable[[str, float], None]
class DownloadCancelled(Exception):
"""사용자가 받는 도중에 번역을 정지했다."""
#: os.add_dll_directory 가 돌려준 핸들. 닫히면 검색 경로에서 빠지므로 붙잡아 둔다.
_dll_dir_handle = None
#: 불러온 DLL 핸들. 참조가 사라지면 내려갈 수 있으므로 들고 있는다.
@@ -69,11 +74,13 @@ def _system_has_cublas() -> bool:
return True
def ensure(progress: ProgressCallback | None = None, device: str = "cuda") -> bool:
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":
@@ -85,7 +92,7 @@ def ensure(progress: ProgressCallback | None = None, device: str = "cuda") -> bo
log.info("시스템에 있는 cuBLAS 를 씁니다.")
else:
if not installed(directory):
download(directory, progress)
download(directory, progress, cancel=cancel)
activate(directory)
_ready = True
return True
@@ -93,7 +100,7 @@ def ensure(progress: ProgressCallback | None = None, device: str = "cuda") -> bo
def download(directory: Path, progress: ProgressCallback | None = None,
url: str = WHEEL_URL, sha256: str = WHEEL_SHA256,
size: int = WHEEL_SIZE) -> None:
size: int = WHEEL_SIZE, cancel: threading.Event | None = None) -> None:
"""공식 패키지를 받아 DLL 두 개만 꺼낸다. 끝나면 패키지 파일은 지운다."""
directory.mkdir(parents=True, exist_ok=True)
part = directory / "cublas.whl.part"
@@ -105,6 +112,8 @@ def download(directory: Path, progress: ProgressCallback | None = None,
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)