From bd24063c15e068035d48e2b602b2c530e1359309 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Thu, 5 Nov 2026 14:49:45 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20exe=20=EC=97=90=EC=84=9C=20GPU=20?= =?UTF-8?q?=EB=A1=9C=20=EB=B0=9B=EC=95=84=20=EC=A0=81=EC=9D=84=20=EB=95=8C?= =?UTF-8?q?=EB=A7=88=EB=8B=A4=20=EC=8B=A4=ED=8C=A8=ED=95=B4=20=EC=9E=90?= =?UTF-8?q?=EB=A7=89=EC=9D=B4=20=EC=95=88=20=EB=82=98=EC=98=A4=EB=8D=98=20?= =?UTF-8?q?=EA=B2=83=20(cuBLAS=20=EB=88=84=EB=9D=BD)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CTranslate2 Windows 패키지는 GPU 계산 때 cublas64_12.dll 을 이름으로 불러오는데 포터블 exe 에는 이 파일(과 cublasLt64_12.dll)이 없다. 리눅스 GPU 점검은 torch 가 깔아 둔 cuBLAS 를 써서 통과했고, torch 를 뺀 exe 에서는 모델은 GPU 에 올라가지만 첫 문장부터 매번 실패했다. 실패는 로그에만 남아 화면은 '듣는 중' 그대로였다. - 처음 GPU 를 쓸 때 NVIDIA 공식 nvidia-cublas-cu12 12.8.4.1(Blackwell 지원)을 PyPI 에서 한 번 받아 모델 폴더에 두고 전체 경로로 미리 불러 둔다. 크기·sha256 을 확인하고 DLL 두 개만 꺼낸다. 시스템에 이미 있으면 받지 않는다. - 받기에 실패하거나 GPU 쪽 오류(cuda/cublas/cudnn)로 문장 처리가 실패하면 이번 실행만 CPU 로 바꿔 같은 구간을 다시 처리한다. 설정 파일 값은 바꾸지 않는다. - 문장 처리 실패와 CPU 전환 사유를 홈 화면 상태 줄에 띄운다. - windows_smoke 에 cuBLAS 받기·불러오기 점검을 넣었다. Co-Authored-By: Claude Opus 5.5 --- packaging/windows_smoke.py | 17 ++++ src/livesub/core/engine.py | 75 ++++++++++++--- src/livesub/models/cuda_runtime.py | 147 +++++++++++++++++++++++++++++ src/livesub/models/manager.py | 16 +++- tests/test_cuda_runtime.py | 61 ++++++++++++ tests/test_pipeline.py | 65 +++++++++++++ 6 files changed, 368 insertions(+), 13 deletions(-) create mode 100644 src/livesub/models/cuda_runtime.py create mode 100644 tests/test_cuda_runtime.py diff --git a/packaging/windows_smoke.py b/packaging/windows_smoke.py index fc17d48..a6419a0 100644 --- a/packaging/windows_smoke.py +++ b/packaging/windows_smoke.py @@ -130,6 +130,23 @@ def run_source_checks() -> None: raise RuntimeError(gpu.reason) return f"{gpu.name} · {gpu.total_vram_mb / 1024:.1f}GB" + # CTranslate2 는 GPU 계산 때 cublas64_12.dll 을 이름으로 불러오는데, 포터블 + # 빌드에는 이 파일이 없다 (v0.3.0-test8 까지 GPU 에서 자막이 안 나온 원인). + # 앱이 처음 GPU 를 쓸 때 받아 두는 경로가 실제로 받고 불러오는지 본다. + # GPU 가 없어도 DLL 은 올라간다. 한 번 받으면 다음부터는 캐시를 쓴다. + @check("GPU 계산 파일(cuBLAS) 받기·불러오기") + def _cublas(): + import ctypes + + from livesub.models import cuda_runtime + + if not cuda_runtime.ensure(device="cuda"): + raise RuntimeError("Windows 인데 준비를 건너뛰었습니다") + ctypes.WinDLL("cublas64_12.dll") # CTranslate2 처럼 이름만으로 찾아지는지 + import ctranslate2 # noqa: F401 - 미리 올린 DLL 과 같이 올라가는지 + + return str(cuda_runtime.runtime_dir()) + @check("사용 가능한 모델 티어") def _tiers(): from livesub.models.manager import has_torch, tier_availability diff --git a/src/livesub/core/engine.py b/src/livesub/core/engine.py index 43f0a5a..93f2eb1 100644 --- a/src/livesub/core/engine.py +++ b/src/livesub/core/engine.py @@ -9,6 +9,7 @@ from __future__ import annotations import logging import queue +import re import threading import time from collections.abc import Callable @@ -25,7 +26,7 @@ from ..audio import ( ) from ..config import AppConfig from ..constants import LANGUAGE_CODES, user_data_dir -from ..models import Glossary, ModelManager +from ..models import Glossary, ModelManager, cuda_runtime from ..models.manager import apply_vram_limit from ..models.packs import build_glossary from ..models.speech_level import ( @@ -38,6 +39,10 @@ from .events import EngineState, EngineStatus, TranslationLine log = logging.getLogger(__name__) +#: GPU 쪽 문제로 보이는 예외 문구. 이런 실패는 CPU 로 바꾸면 자막이 나온다. +_GPU_ERROR = re.compile(r"cuda|cublas|cudnn|gpu", re.IGNORECASE) +_FAILED_PREFIX = "듣는 중 · 문장 처리 실패: " + StatusCallback = Callable[[EngineStatus], None] LineCallback = Callable[[TranslationLine], None] @@ -67,6 +72,8 @@ class TranslationEngine: #: 마지막으로 실제 발화를 처리한 시각. 유휴 언로드 판단에 쓴다. self._last_activity = time.monotonic() self._models_unloaded = False + #: GPU 를 못 써서 CPU 로 돌고 있으면 그 사유. 홈 화면 상태에 보인다. + self._cpu_notice = "" # --- 수명주기 ------------------------------------------------------- @property @@ -145,11 +152,14 @@ class TranslationEngine: # --- 내부 스레드 ---------------------------------------------------- def _bootstrap(self) -> None: + self._cpu_notice = "" try: # 설정이 바뀐 채로 재시작됐을 수 있으므로 매 시작마다 맞춘다. self.sync_performance() + self.models.use_device(self.config.models.device) + self._prepare_gpu() perf = self.config.performance - if perf.game_mode and self.config.models.device == "cuda": + 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: @@ -168,11 +178,29 @@ class TranslationEngine: self._threads.extend(workers) kind = "프로그램별 캡처" if self._capture.per_process else "출력 장치 전체" - self._emit_status(EngineState.RUNNING, f"듣는 중 · {kind}", 1.0) + 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)) + def _prepare_gpu(self) -> None: + """GPU 계산에 필요한 파일을 준비한다. 안 되면 CPU 로 돌린다.""" + if self.models.device != "cuda": + return + try: + cuda_runtime.ensure( + lambda msg, pct: self._emit_status(EngineState.LOADING, msg, pct) + ) + except Exception as exc: # noqa: BLE001 - 받기 실패여도 자막은 나와야 한다 + log.warning("GPU 계산 파일을 준비하지 못했습니다: %s", exc, exc_info=True) + self._fall_back_to_cpu(f"GPU 계산 파일을 받지 못했습니다 ({_short(exc)})") + + def _fall_back_to_cpu(self, reason: str) -> None: + self.models.use_device("cpu") + self._cpu_notice = f"CPU로 받아 적는 중 · {reason}" + log.warning("CPU 로 전환합니다: %s", reason) + def _segment_loop(self) -> None: cfg = self.config.audio # 중간 결과는 같은 오디오를 여러 번 인식하므로 GPU 작업이 거의 두 배가 된다. @@ -240,21 +268,40 @@ class TranslationEngine: if not segment.is_final and not self._segments.empty(): continue + self._process_safely(segment, mcfg) + + # 게임에 GPU를 잠깐 돌려준다. 연속 발화 때 우리가 GPU를 독점하면 + # 프레임이 눈에 띄게 끊긴다. + if perf.game_mode and perf.yield_ms > 0: + self._stop.wait(perf.yield_ms / 1000) + + def _process_safely(self, segment: Segment, mcfg) -> None: + """한 구간을 처리한다. 실패해도 엔진은 계속 돌고, 사용자에게 보인다. + + 예전에는 실패를 로그에만 남겨서, 매 문장이 실패해도 화면은 '듣는 중' + 그대로였다. 사용자는 게이지만 움직이고 자막이 안 나오는 이유를 알 수 없었다. + """ + for attempt in range(2): # 모델 참조를 캐시하지 않는다. 유휴 언로드 뒤에는 새로 올려야 하고, # 캐시된 참조를 쓰면 이미 내려간 모델을 붙잡고 있게 된다. try: self._process( segment, self.models.recognizer(), self.models.translator(), mcfg ) - self._last_activity = time.monotonic() - self._models_unloaded = False except Exception as exc: # noqa: BLE001 - 한 문장 실패로 엔진이 죽으면 안 된다 - log.warning("구간 처리 실패: %s", exc, exc_info=log.isEnabledFor(logging.DEBUG)) - - # 게임에 GPU를 잠깐 돌려준다. 연속 발화 때 우리가 GPU를 독점하면 - # 프레임이 눈에 띄게 끊긴다. - if perf.game_mode and perf.yield_ms > 0: - self._stop.wait(perf.yield_ms / 1000) + log.warning("구간 처리 실패: %s", exc, exc_info=True) + if attempt == 0 and self.models.device == "cuda" and _GPU_ERROR.search(str(exc)): + # GPU 로는 안 되는 환경이다. 같은 구간을 CPU 로 다시 받아 적는다. + self._fall_back_to_cpu(f"GPU 오류: {_short(exc)}") + self._emit_status(EngineState.RUNNING, self._cpu_notice) + continue + self._emit_status(EngineState.RUNNING, f"{_FAILED_PREFIX}{_short(exc)}") + return + self._last_activity = time.monotonic() + self._models_unloaded = False + if self._status.message.startswith(_FAILED_PREFIX): + self._emit_status(EngineState.RUNNING, self._cpu_notice or "듣는 중") + return def _maybe_unload_idle(self) -> None: """한동안 말소리가 없으면 모델을 내려 VRAM을 통째로 돌려준다. @@ -363,3 +410,9 @@ class TranslationEngine: ) if self._on_status: self._on_status(self._status) + + +def _short(exc: Exception, limit: int = 120) -> str: + """상태 줄에 넣을 만큼 짧은 오류 문구.""" + text = " ".join(str(exc).split()) or type(exc).__name__ + return text if len(text) <= limit else text[: limit - 1] + "…" diff --git a/src/livesub/models/cuda_runtime.py b/src/livesub/models/cuda_runtime.py new file mode 100644 index 0000000..0b8dd13 --- /dev/null +++ b/src/livesub/models/cuda_runtime.py @@ -0,0 +1,147 @@ +"""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 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] + +#: 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") -> bool: + """GPU 를 쓸 수 있게 cuBLAS 를 준비한다. 새로 받았거나 불러왔으면 True. + + Windows 가 아니거나 CPU 로 돌릴 때는 아무것도 하지 않는다. 받기·불러오기에 + 실패하면 예외를 그대로 올린다. 호출한 쪽이 CPU 로 바꿀지 정한다. + """ + 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) + 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) -> 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): + 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) diff --git a/src/livesub/models/manager.py b/src/livesub/models/manager.py index b4eed37..ed5651a 100644 --- a/src/livesub/models/manager.py +++ b/src/livesub/models/manager.py @@ -191,6 +191,9 @@ class ModelManager: self.config = config #: 저부하(게임) 모드. 연산 정밀도를 낮춰 VRAM과 GPU 점유를 줄인다. self.low_power = low_power + #: 실제로 돌릴 장치. 설정값에서 시작하지만, GPU 가 안 되면 이번 실행만 + #: CPU 로 바꾼다. 설정 파일에는 남기지 않는다 — 다음엔 GPU 가 될 수 있다. + self.device = config.device self._tier: Tier = get_tier(config.tier) self._asr: SpeechRecognizer | None = None self._mt: Translator | None = None @@ -224,7 +227,7 @@ class ModelManager: with self._lock: if self._asr is None: self._asr = SpeechRecognizer( - self.effective_asr_spec(), self.config.device, self.config.device_index + self.effective_asr_spec(), self.device, self.config.device_index ) return self._asr @@ -233,7 +236,7 @@ class ModelManager: if self._mt is None: self._mt = create_translator( self.effective_mt_spec(), - self.config.device, + self.device, self.config.device_index, self.config.lora_adapter_path, ) @@ -251,6 +254,15 @@ class ModelManager: self.translator().load() report("준비 완료", 1.0) + def use_device(self, device: str) -> bool: + """돌릴 장치를 바꾼다. 바뀌었으면 올라가 있던 모델을 내리고 True.""" + if device == self.device: + return False + self.unload() + self.device = device + log.info("연산 장치 변경: %s", device) + return True + def switch_tier(self, tier_key: str) -> Tier: """티어 변경. 기존 모델은 내려서 VRAM을 즉시 돌려준다.""" if tier_key == self._tier.key: diff --git a/tests/test_cuda_runtime.py b/tests/test_cuda_runtime.py new file mode 100644 index 0000000..c0cf3cb --- /dev/null +++ b/tests/test_cuda_runtime.py @@ -0,0 +1,61 @@ +"""cuBLAS 내려받기·꺼내기 (Windows exe 에서 GPU 로 받아 적는 데 필요).""" + +from __future__ import annotations + +import hashlib +import zipfile + +import pytest + +from livesub.models import cuda_runtime + + +def _fake_wheel(tmp_path): + wheel = tmp_path / "fake.whl" + with zipfile.ZipFile(wheel, "w") as zf: + zf.writestr("nvidia/cublas/bin/cublasLt64_12.dll", b"LT" * 1000) + zf.writestr("nvidia/cublas/bin/cublas64_12.dll", b"BLAS" * 1000) + zf.writestr("nvidia/cublas/bin/nvblas64_12.dll", b"unused") + zf.writestr("nvidia/cublas/include/cublas.h", b"header") + data = wheel.read_bytes() + return wheel.as_uri(), hashlib.sha256(data).hexdigest(), len(data) + + +def test_download_extracts_only_the_two_dlls(tmp_path): + url, sha, size = _fake_wheel(tmp_path) + target = tmp_path / "runtime" + seen = [] + + cuda_runtime.download(target, lambda msg, pct: seen.append(pct), url, sha, size) + + assert cuda_runtime.installed(target) + assert (target / "cublasLt64_12.dll").read_bytes() == b"LT" * 1000 + assert (target / "cublas64_12.dll").read_bytes() == b"BLAS" * 1000 + assert sorted(p.name for p in target.iterdir()) == ["cublas64_12.dll", "cublasLt64_12.dll"] + assert seen and seen[-1] == 1.0 + + +def test_corrupted_download_leaves_nothing_behind(tmp_path): + url, _sha, size = _fake_wheel(tmp_path) + target = tmp_path / "runtime" + + with pytest.raises(RuntimeError, match="손상"): + cuda_runtime.download(target, None, url, "0" * 64, size) + + assert not cuda_runtime.installed(target) + assert list(target.iterdir()) == [] + + +def test_pinned_wheel_is_the_blackwell_capable_cublas(): + # RTX 50 계열(sm_120)은 cuBLAS 12.8 부터 지원한다. + major, minor = (int(x) for x in cuda_runtime.WHEEL_VERSION.split(".")[:2]) + assert (major, minor) >= (12, 8) + assert cuda_runtime.WHEEL_VERSION in cuda_runtime.WHEEL_URL + assert cuda_runtime.WHEEL_URL.endswith("win_amd64.whl") + + +def test_ensure_is_a_no_op_off_windows_or_on_cpu(monkeypatch): + monkeypatch.setattr(cuda_runtime.sys, "platform", "linux") + assert cuda_runtime.ensure(device="cuda") is False + monkeypatch.setattr(cuda_runtime.sys, "platform", "win32") + assert cuda_runtime.ensure(device="cpu") is False diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index ad2e49d..0f9fc03 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -129,3 +129,68 @@ def test_to_mono_16k_passthrough_when_already_correct(): mono = np.linspace(-1, 1, 16_000, dtype=np.float32) out = to_mono_16k(mono, channels=1, src_rate=16_000) assert np.array_equal(out, mono) + + +class CublasMissingRecognizer(FakeRecognizer): + """Windows exe 에서 cuBLAS 가 없을 때 CTranslate2 가 내는 오류를 흉내 낸다.""" + + def transcribe(self, *args, **kwargs): + raise RuntimeError("Library cublas64_12.dll is not found or cannot be loaded") + + +def _wait_for(predicate, timeout=12.0): + deadline = time.time() + timeout + while time.time() < deadline and not predicate(): + time.sleep(0.05) + return predicate() + + +def test_gpu_failure_falls_back_to_cpu_and_still_produces_lines(engine, monkeypatch): + statuses = [] + engine._on_status = statuses.append + monkeypatch.setattr( + engine.models, + "recognizer", + lambda: CublasMissingRecognizer() if engine.models.device == "cuda" else FakeRecognizer(), + ) + assert engine.models.device == "cuda" + + engine.start() + assert _wait_for(lambda: engine.lines), "CPU 로 바꾼 뒤에도 자막이 나오지 않았습니다" + engine.stop() + + assert engine.models.device == "cpu" + assert engine.config.models.device == "cuda", "설정 파일 값은 그대로 둬야 한다" + assert any("CPU로" in s.message and "cublas" in s.message for s in statuses) + + +def test_non_gpu_failure_is_shown_on_status(engine, monkeypatch): + statuses = [] + engine._on_status = statuses.append + + class Broken(FakeRecognizer): + def transcribe(self, *args, **kwargs): + raise ValueError("토크나이저가 깨졌습니다") + + monkeypatch.setattr(engine.models, "recognizer", lambda: Broken()) + engine.start() + assert _wait_for(lambda: any("문장 처리 실패" in s.message for s in statuses)) + engine.stop() + assert engine.models.device == "cuda", "GPU 와 상관없는 오류로 CPU 로 바꾸면 안 된다" + assert any("토크나이저가 깨졌습니다" in s.message for s in statuses) + + +def test_gpu_runtime_download_failure_runs_on_cpu(engine, monkeypatch): + statuses = [] + engine._on_status = statuses.append + + def fail(*args, **kwargs): + raise OSError("네트워크 연결 없음") + + monkeypatch.setattr("livesub.core.engine.cuda_runtime.ensure", fail) + engine.start() + assert _wait_for(lambda: engine.lines) + engine.stop() + assert engine.models.device == "cpu" + running = [s for s in statuses if s.state.value == "running"] + assert running and "GPU 계산 파일을 받지 못했습니다" in running[0].message