fix: .gitignore 가 소스 패키지 src/livesub/models 를 통째로 먹고 있었다
Some checks failed
Windows / verify (push) Has been cancelled
Some checks failed
Windows / verify (push) Has been cancelled
`models/` 처럼 슬래시 없이 쓴 규칙은 깊이에 상관없이 같은 이름의 폴더를 전부 무시한다. 의도는 루트의 모델 캐시였는데 소스 패키지까지 같이 걸렸고, 그래서 asr/translator/manager/tiers/glossary/packs/speech_level 8개 파일이 한 번도 커밋된 적이 없다. 증상: Gitea 에서 clone 하면 `ModuleNotFoundError: No module named 'livesub.models'` 로 앱이 아예 임포트되지 않는다. 로컬 작업 트리에는 파일이 있으니 개발 중에는 절대 안 보인다. 방금 붙인 Windows CI VM 이 첫 검증에서 바로 잡아냈다. /models/, /adapters/, /data/ 로 루트에 고정하고 빠진 파일을 추가한다.
This commit is contained in:
242
src/livesub/models/manager.py
Normal file
242
src/livesub/models/manager.py
Normal file
@@ -0,0 +1,242 @@
|
||||
"""티어에 맞는 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 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
|
||||
return GpuInfo(False, reason=f"GPU 조회 실패: {exc}")
|
||||
|
||||
|
||||
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 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
|
||||
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.config.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.config.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 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
|
||||
Reference in New Issue
Block a user