"""티어에 맞는 ASR + MT 모델 쌍을 관리한다.""" from __future__ import annotations import logging import threading from dataclasses import dataclass, replace from ..config import ModelConfig from .asr import SpeechRecognizer from .tiers import DEFAULT_TIER, TIERS, MTBackend, Tier, get_tier from .translator import Translator, create_translator log = logging.getLogger(__name__) @dataclass class GpuInfo: available: bool name: str = "" total_vram_mb: int = 0 free_vram_mb: int = 0 reason: str = "" def detect_gpu() -> GpuInfo: """CUDA 사용 가능 여부와 VRAM. torch 가 없으면 nvidia-smi 로 대체 조회.""" try: import torch if torch.cuda.is_available(): idx = torch.cuda.current_device() free, total = torch.cuda.mem_get_info(idx) return GpuInfo( available=True, name=torch.cuda.get_device_name(idx), total_vram_mb=total // (1024 * 1024), free_vram_mb=free // (1024 * 1024), ) return GpuInfo(False, reason="CUDA를 사용할 수 없습니다 (드라이버/빌드 확인).") except ImportError: pass import shutil import subprocess smi = shutil.which("nvidia-smi") if not smi: return GpuInfo(False, reason="PyTorch와 nvidia-smi 모두 찾지 못했습니다.") try: out = subprocess.run( [smi, "--query-gpu=name,memory.total,memory.free", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=5, check=True, ).stdout.strip().splitlines() name, total, free = (v.strip() for v in out[0].split(",")) return GpuInfo(True, name, int(total), int(free), reason="PyTorch 미설치 — 정보만 조회했습니다.") except Exception as exc: # noqa: BLE001 # 예외 문자열에는 실행한 명령줄이 통째로 들어 있다. 그대로 화면에 # 띄우면 안내가 아니라 로그 덤프가 된다. 자세한 건 로그로 보낸다. log.warning("nvidia-smi 조회 실패: %s", exc) return GpuInfo(False, reason="nvidia-smi 로 GPU 정보를 읽지 못했습니다.") def apply_vram_limit(ratio: float, device_index: int = 0) -> bool: """이 프로세스가 쓸 수 있는 VRAM 상한을 건다. 게임과 동시에 돌 때 가장 큰 문제는 연산 시간이 아니라 **VRAM 고갈**이다. 게임이 쓸 메모리를 우리가 먹어버리면 텍스처 스트리밍이 시스템 메모리로 밀려나면서 프레임이 뚝뚝 끊긴다. 상한을 걸면 그 대신 우리 쪽이 먼저 OOM 을 맞으므로, 티어를 낮추라는 안내로 이어진다. """ if ratio <= 0 or ratio >= 1: return False try: import torch if not torch.cuda.is_available(): return False torch.cuda.set_per_process_memory_fraction(ratio, device_index) log.info("VRAM 상한 적용: 전체의 %d%%", int(ratio * 100)) return True except Exception as exc: # noqa: BLE001 - 상한 실패가 치명적이지는 않다 log.warning("VRAM 상한을 걸지 못했습니다: %s", exc) return False def has_torch() -> bool: """PyTorch 가 설치돼 있는가. 포터블 exe 빌드는 torch 를 넣지 않는다. torch+CUDA 만 2.5GB 라 한 파일로 묶으면 실행할 때마다 그걸 임시폴더에 풀어야 해서 쓸 수 없다. CTranslate2 기반 1~3티어는 torch 없이 동작하므로, 포터블은 그쪽만 담는다. """ import importlib.util return importlib.util.find_spec("torch") is not None def has_awq() -> bool: """4티어(AWQ Int4) 로드에 필요한 autoawq 가 있는지.""" import importlib.util return importlib.util.find_spec("awq") is not None def tier_availability(tier: Tier, gpu: GpuInfo | None = None) -> tuple[bool, str]: """이 설치 환경에서 해당 티어를 쓸 수 있는지와, 안 되면 그 이유. torch 유무만 보면 부족하다. 실제로 막히는 경우가 둘 더 있다. - 4티어(AWQ Int4)는 autoawq 가 있어야 로드된다. requirements.txt 에 없는 선택 의존성이라 없을 때가 많다. - VRAM 이 모자라면 설치가 아무리 멀쩡해도 안 올라간다. 기존에도 min_vram_gb 로 경고 배지는 띄웠지만 선택은 막지 않아서, 골랐다가 로드에서 죽었다. 예: RTX 5050(7.5GB)은 정밀 10GB / 극한 16GB 라 둘 다 영영 못 쓴다. "사용 가능"이라고 해놓고 로드에서 죽으면 사용자는 원인을 알 수 없다. 그래서 고를 수 있다고 말하기 전에 여기서 걸러낸다. """ if tier.mt.backend is not MTBackend.TRANSFORMERS: return True, "" if not has_torch(): return False, "PyTorch가 없어 사용할 수 없습니다 (포터블 버전은 1~3티어만 지원)" if tier.mt.compute_type == "int4" and not has_awq(): return False, "autoawq가 없어 사용할 수 없습니다 (pip install autoawq)" info = detect_gpu() if gpu is None else gpu # free 가 아니라 total 로 본다. free 는 다른 프로그램 때문에 수시로 # 변해서, 그걸로 막으면 "아까는 되던 티어가 지금은 안 보인다"가 된다. have_gb = info.total_vram_mb / 1024 if info.available and have_gb < tier.min_vram_gb: return False, ( f"VRAM이 부족합니다 " f"({tier.min_vram_gb:g}GB 필요, 이 GPU는 {have_gb:.1f}GB)" ) return True, "" def recommended_tier(gpu: GpuInfo | None = None) -> str: """이 환경에서 실제로 권할 만한 티어. 티어 표에 박아둔 `recommended` 는 "GPU 가 넉넉할 때" 를 전제로 한 값이라, 그대로 쓰면 GPU 가 없는 사람에게 10GB 짜리를 추천하게 된다. 그래서 환경을 보고 정한다. GPU 가 없으면 CTranslate2 계열(1~3티어)만 후보에 둔다. LLM 계열은 CPU 에서 한 문장에 수십 초가 걸려 실시간 자막으로 쓸 수 없다. 그중에서도 가장 가벼운 쪽을 고른다 — CPU 에서는 연산량이 그대로 지연으로 돌아온다. """ info = detect_gpu() if gpu is None else gpu usable = [t for t in TIERS.values() if tier_availability(t, info)[0]] if not usable: return DEFAULT_TIER if not info.available: light = [t for t in usable if t.mt.backend is MTBackend.CTRANSLATE2] return min(light or usable, key=lambda t: t.order).key preferred = [t for t in usable if t.recommended] if preferred: return max(preferred, key=lambda t: t.order).key return max(usable, key=lambda t: t.order).key def first_available_tier(preferred: str) -> str: """선호 티어가 불가능하면 쓸 수 있는 가장 좋은 티어로 내린다.""" tier = get_tier(preferred) gpu = detect_gpu() if tier_availability(tier, gpu)[0]: return tier.key usable = [t for t in TIERS.values() if tier_availability(t, gpu)[0]] if not usable: return preferred return max(usable, key=lambda t: t.order).key def downgrade_compute(compute_type: str) -> str: """저부하 모드에서 쓸 더 가벼운 연산 정밀도.""" if compute_type in ("float16", "float32"): return "int8_float16" return compute_type class ModelManager: """현재 선택된 티어의 모델 두 개를 들고 있는다.""" def __init__(self, config: ModelConfig, low_power: bool = False) -> None: 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 self._lock = threading.Lock() @property def tier(self) -> Tier: return self._tier @property def ready(self) -> bool: return bool(self._asr and self._asr.loaded and self._mt and self._mt.loaded) def effective_asr_spec(self): """저부하 모드가 켜져 있으면 정밀도를 낮춘 사양을 돌려준다.""" spec = self._tier.asr if not self.low_power: return spec return replace( spec, compute_type=downgrade_compute(spec.compute_type), beam_size=1 ) def effective_mt_spec(self): spec = self._tier.mt # 양자화 LLM(int4)은 이미 최소 상태라 더 낮출 수 없다. if not self.low_power or spec.compute_type == "int4": return spec return replace(spec, compute_type=downgrade_compute(spec.compute_type)) def recognizer(self) -> SpeechRecognizer: with self._lock: if self._asr is None: self._asr = SpeechRecognizer( self.effective_asr_spec(), self.device, self.config.device_index ) return self._asr def translator(self) -> Translator: with self._lock: if self._mt is None: self._mt = create_translator( self.effective_mt_spec(), self.device, self.config.device_index, self.config.lora_adapter_path, ) return self._mt def preload(self, progress=None) -> None: """두 모델을 미리 올린다. progress(str, float) 콜백으로 상태를 보고.""" def report(msg: str, value: float) -> None: if progress: progress(msg, value) report(f"'{self._tier.name}' 음성인식 모델 준비 중…", 0.1) self.recognizer().load() report(f"'{self._tier.name}' 번역 모델 준비 중…", 0.6) 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: return self._tier self.unload() self.config.tier = tier_key self._tier = get_tier(tier_key) log.info("모델 티어 변경: %s", self._tier.name) return self._tier def unload(self) -> None: with self._lock: if self._asr is not None: self._asr.unload() self._asr = None if self._mt is not None: self._mt.unload() self._mt = None