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

View File

@@ -18,6 +18,7 @@ import hashlib
import logging import logging
import os import os
import sys import sys
import threading
import urllib.request import urllib.request
import zipfile import zipfile
from collections.abc import Callable from collections.abc import Callable
@@ -43,6 +44,10 @@ _WHEEL_DIR = "nvidia/cublas/bin/"
ProgressCallback = Callable[[str, float], None] ProgressCallback = Callable[[str, float], None]
class DownloadCancelled(Exception):
"""사용자가 받는 도중에 번역을 정지했다."""
#: os.add_dll_directory 가 돌려준 핸들. 닫히면 검색 경로에서 빠지므로 붙잡아 둔다. #: os.add_dll_directory 가 돌려준 핸들. 닫히면 검색 경로에서 빠지므로 붙잡아 둔다.
_dll_dir_handle = None _dll_dir_handle = None
#: 불러온 DLL 핸들. 참조가 사라지면 내려갈 수 있으므로 들고 있는다. #: 불러온 DLL 핸들. 참조가 사라지면 내려갈 수 있으므로 들고 있는다.
@@ -69,11 +74,13 @@ def _system_has_cublas() -> bool:
return True 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. """GPU 를 쓸 수 있게 cuBLAS 를 준비한다. 새로 받았거나 불러왔으면 True.
Windows 가 아니거나 CPU 로 돌릴 때는 아무것도 하지 않는다. 받기·불러오기에 Windows 가 아니거나 CPU 로 돌릴 때는 아무것도 하지 않는다. 받기·불러오기에
실패하면 예외를 그대로 올린다. 호출한 쪽이 CPU 로 바꿀지 정한다. 실패하면 예외를 그대로 올린다. 호출한 쪽이 CPU 로 바꿀지 정한다.
`cancel` 이 켜지면 받기를 멈추고 `DownloadCancelled` 를 올린다.
""" """
global _ready global _ready
if sys.platform != "win32" or device != "cuda": if sys.platform != "win32" or device != "cuda":
@@ -85,7 +92,7 @@ def ensure(progress: ProgressCallback | None = None, device: str = "cuda") -> bo
log.info("시스템에 있는 cuBLAS 를 씁니다.") log.info("시스템에 있는 cuBLAS 를 씁니다.")
else: else:
if not installed(directory): if not installed(directory):
download(directory, progress) download(directory, progress, cancel=cancel)
activate(directory) activate(directory)
_ready = True _ready = True
return 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, def download(directory: Path, progress: ProgressCallback | None = None,
url: str = WHEEL_URL, sha256: str = WHEEL_SHA256, url: str = WHEEL_URL, sha256: str = WHEEL_SHA256,
size: int = WHEEL_SIZE) -> None: size: int = WHEEL_SIZE, cancel: threading.Event | None = None) -> None:
"""공식 패키지를 받아 DLL 두 개만 꺼낸다. 끝나면 패키지 파일은 지운다.""" """공식 패키지를 받아 DLL 두 개만 꺼낸다. 끝나면 패키지 파일은 지운다."""
directory.mkdir(parents=True, exist_ok=True) directory.mkdir(parents=True, exist_ok=True)
part = directory / "cublas.whl.part" part = directory / "cublas.whl.part"
@@ -105,6 +112,8 @@ def download(directory: Path, progress: ProgressCallback | None = None,
try: try:
with urllib.request.urlopen(url, timeout=30) as resp, part.open("wb") as out: with urllib.request.urlopen(url, timeout=30) as resp, part.open("wb") as out:
while chunk := resp.read(1 << 20): while chunk := resp.read(1 << 20):
if cancel is not None and cancel.is_set():
raise DownloadCancelled("GPU 계산 파일 받기를 멈췄습니다")
out.write(chunk) out.write(chunk)
digest.update(chunk) digest.update(chunk)
done += len(chunk) done += len(chunk)

View File

@@ -59,3 +59,18 @@ def test_ensure_is_a_no_op_off_windows_or_on_cpu(monkeypatch):
assert cuda_runtime.ensure(device="cuda") is False assert cuda_runtime.ensure(device="cuda") is False
monkeypatch.setattr(cuda_runtime.sys, "platform", "win32") monkeypatch.setattr(cuda_runtime.sys, "platform", "win32")
assert cuda_runtime.ensure(device="cpu") is False assert cuda_runtime.ensure(device="cpu") is False
def test_download_stops_when_cancelled(tmp_path):
import threading
url, sha, size = _fake_wheel(tmp_path)
target = tmp_path / "runtime"
cancel = threading.Event()
cancel.set()
with pytest.raises(cuda_runtime.DownloadCancelled):
cuda_runtime.download(target, None, url, sha, size, cancel=cancel)
assert not cuda_runtime.installed(target)
assert list(target.iterdir()) == []

View File

@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import threading
import time import time
import numpy as np import numpy as np
@@ -194,3 +195,61 @@ def test_gpu_runtime_download_failure_runs_on_cpu(engine, monkeypatch):
assert engine.models.device == "cpu" assert engine.models.device == "cpu"
running = [s for s in statuses if s.state.value == "running"] running = [s for s in statuses if s.state.value == "running"]
assert running and "GPU 계산 파일을 받지 못했습니다" in running[0].message assert running and "GPU 계산 파일을 받지 못했습니다" in running[0].message
def test_gpu_failure_while_preloading_falls_back_to_cpu(engine, monkeypatch):
"""기본값(preload_on_start=True)에서 GPU 로 모델이 안 올라가도 CPU 로 시작한다."""
statuses = []
engine._on_status = statuses.append
engine.config.models.preload_on_start = True
devices = []
def preload(progress=None):
devices.append(engine.models.device)
if engine.models.device == "cuda":
raise RuntimeError("CUDA failed with error no CUDA-capable device is detected")
monkeypatch.setattr(engine.models, "preload", preload)
engine.start()
assert _wait_for(lambda: engine.lines), "CPU 로 바꾼 뒤에도 자막이 나오지 않았습니다"
engine.stop()
assert devices == ["cuda", "cpu"]
assert not any(s.state.value == "error" for s in statuses)
running = [s for s in statuses if s.state.value == "running"]
assert running and "CPU로" in running[0].message
def test_stop_while_downloading_gpu_runtime_never_starts_capture(engine, monkeypatch):
"""cuBLAS 를 받는 중에 정지하면 받기를 멈추고, 캡처를 켜지 않는다."""
from livesub.models.cuda_runtime import DownloadCancelled
statuses = []
engine._on_status = statuses.append
downloading = threading.Event()
captures = []
def slow_download(progress=None, device="cuda", cancel=None):
downloading.set()
while not cancel.is_set():
progress("GPU 계산 파일 받는 중", 0.1)
time.sleep(0.05)
raise DownloadCancelled("멈춤")
def make_capture(cfg):
captures.append(cfg)
return FakeCapture()
monkeypatch.setattr("livesub.core.engine.cuda_runtime.ensure", slow_download)
monkeypatch.setattr("livesub.core.engine.create_capture", make_capture)
engine.start()
assert downloading.wait(5)
engine.stop()
boot_done = _wait_for(lambda: not any(t.name == "engine-boot" for t in threading.enumerate()), 5)
time.sleep(0.3)
assert boot_done, "정지했는데 시작 작업이 끝나지 않았습니다"
assert captures == [], "정지한 뒤에 캡처가 켜졌습니다"
assert engine.status.state.value == "idle"
assert statuses[-1].state.value == "idle"
assert engine.models.device == "cuda", "정지는 GPU 실패가 아니다"