File size: 6,954 Bytes
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb4ae44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04684e6
 
 
eb4ae44
04684e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""
Model registry for dynamic model loading
Author: Maaldeens
License: MIT
"""

import torch
from transformers import (
    WhisperProcessor,
    WhisperForConditionalGeneration,
    pipeline
)
from typing import Dict, Any, Optional, Tuple
import logging
import yaml
from pathlib import Path
import gc
import os

logger = logging.getLogger(__name__)

class ModelRegistry:
    """Registry for managing ASR models with caching and device management."""

    def __init__(self, config_path: Optional[str] = None):
        self.models = {}
        self.processors = {}
        self.pipelines = {}
        self.config = self._load_config(config_path)
        self.device = self._get_device()
        self.current_model = None
        # Respect HF_HOME env var for persistent model caching across restarts
        self.cache_dir = os.getenv(
            "HF_HOME",
            self.config.get("models", {}).get("cache_dir", "/app/model_cache")
        )

    def _load_config(self, config_path: Optional[str] = None) -> Dict:
        if config_path and Path(config_path).exists():
            with open(config_path, 'r') as f:
                return yaml.safe_load(f)
        return {"models": {"available": {}}}

    def _get_device(self) -> torch.device:
        if torch.cuda.is_available():
            return torch.device("cuda")
        elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
            return torch.device("mps")
        return torch.device("cpu")

    def load_model(self, model_key: str, force_reload: bool = False) -> Tuple[Any, Any]:
        if not force_reload and model_key in self.models:
            logger.info(f"Using cached model: {model_key}")
            return self.models[model_key], self.processors[model_key]

        available_models = self.config.get("models", {}).get("available", {})

        if model_key not in available_models:
            default = self.config.get("models", {}).get("default", "whisper-medium")
            if default in available_models:
                logger.warning(f"Model {model_key} not found, using default: {default}")
                model_key = default
            else:
                logger.warning(f"Using fallback model path: openai/whisper-{model_key}")
                return self._load_whisper_model(f"openai/whisper-{model_key}", model_key, force_reload)

        model_config = available_models.get(model_key, {})
        model_path = model_config.get("path", f"openai/whisper-{model_key}")
        return self._load_whisper_model(model_path, model_key, force_reload)

    def _load_whisper_model(self, model_path: str, model_key: str, force_reload: bool) -> Tuple[Any, Any]:
        logger.info(f"Loading Whisper model: {model_key} from {model_path}")
        try:
            if force_reload and model_key in self.models:
                del self.models[model_key]
                del self.processors[model_key]
                gc.collect()
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()

            processor = WhisperProcessor.from_pretrained(
                model_path,
                cache_dir=self.cache_dir
            )

            # FIX: Do NOT pass use_safetensors=True — many Whisper checkpoints
            # only ship .bin weights; safetensors would raise FileNotFoundError.
            # transformers auto-selects the best available format.
            model = WhisperForConditionalGeneration.from_pretrained(
                model_path,
                torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32,
                low_cpu_mem_usage=True,
                cache_dir=self.cache_dir
            )

            model = model.to(self.device)
            model.eval()

            self.models[model_key] = model
            self.processors[model_key] = processor
            self.current_model = model_key

            logger.info(f"Successfully loaded {model_key} on {self.device}")
            return model, processor

        except Exception as e:
            logger.error(f"Failed to load model {model_key}: {e}")
            raise

    def unload_all_except(self, keep_key: str) -> None:
        """Free every cached Whisper model/pipeline except `keep_key`.

        Models used to stay cached forever, so switching small -> large-v3
        kept both on the GPU and a long large-v3 job ran a 16 GB T4 out of
        memory.
        """
        dropped = [k for k in list(self.models) if k != keep_key]
        for key in dropped:
            self.models.pop(key, None)
            self.processors.pop(key, None)
            self.pipelines.pop(key, None)
        if dropped:
            gc.collect()
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
            logger.info(f"Unloaded models {dropped} to free memory for {keep_key}")

    def create_pipeline(self, model_key: str, **kwargs) -> Any:
        if model_key in self.pipelines and not kwargs.get("force_reload", False):
            return self.pipelines[model_key]
        self.unload_all_except(model_key)

        model, processor = self.load_model(model_key)

        # Match pipeline dtype to model dtype so audio tensors aren't rejected.
        # Model is loaded as float16 on CUDA; without this the pipeline feeds
        # float32 inputs into float16 weights → "Input type / weight type mismatch".
        torch_dtype = (
            torch.float16 if self.device.type == "cuda" else torch.float32
        )

        pipe = pipeline(
            task="automatic-speech-recognition",
            model=model,
            tokenizer=processor.tokenizer,
            feature_extractor=processor.feature_extractor,
            device=self.device,
            torch_dtype=torch_dtype,
            # Safety net: HF-level chunking handles any audio that slips past
            # our app-level chunker (e.g. metadata duration wrong for MP3/M4A).
            # Whisper's max window is 30s; without this it errors on long audio.
            chunk_length_s=30,
            stride_length_s=5,
        )

        self.pipelines[model_key] = pipe
        return pipe

    def list_available_models(self) -> Dict[str, Dict]:
        available = self.config.get("models", {}).get("available", {})
        if not available:
            available = {
                "whisper-tiny":     {"path": "openai/whisper-tiny",     "type": "whisper", "size": "39M",  "speed": "~32x"},
                "whisper-small":    {"path": "openai/whisper-small",    "type": "whisper", "size": "244M", "speed": "~8x"},
                "whisper-medium":   {"path": "openai/whisper-medium",   "type": "whisper", "size": "769M", "speed": "~2x"},
                "whisper-large-v3": {"path": "openai/whisper-large-v3", "type": "whisper", "size": "1.5B", "speed": "1x"},
            }
        return available

    def get_current_model(self) -> Optional[str]:
        return self.current_model