Chris4K commited on
Commit
16bdb61
·
verified ·
1 Parent(s): 3b677f6

Create model_manager.py

Browse files
Files changed (1) hide show
  1. services/model_manager.py +78 -0
services/model_manager.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # model_manager.py
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from llama_cpp import Llama
5
+ from typing import Optional, Dict
6
+ import logging
7
+ from functools import lru_cache
8
+ from config.config import GenerationConfig, ModelConfig
9
+
10
+
11
+ class ModelManager:
12
+ def __init__(self, device: Optional[str] = None):
13
+ self.logger = logging.getLogger(__name__)
14
+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
15
+ self.models: Dict[str, Any] = {}
16
+ self.tokenizers: Dict[str, Any] = {}
17
+
18
+ def load_model(self, model_id: str, model_path: str, model_type: str, config: ModelConfig) -> None:
19
+ """Load a model with specified configuration."""
20
+ try:
21
+ ##could be differnt models, so we can use a factory pattern to load the correct model - textgen, llama, gguf, text2video, text2image etc.
22
+ if model_type == "llama":
23
+ self.tokenizers[model_id] = AutoTokenizer.from_pretrained(
24
+ model_path,
25
+ padding_side='left',
26
+ trust_remote_code=True,
27
+ **config.tokenizer_kwargs
28
+ )
29
+ if self.tokenizers[model_id].pad_token is None:
30
+ self.tokenizers[model_id].pad_token = self.tokenizers[model_id].eos_token
31
+
32
+ self.models[model_id] = AutoModelForCausalLM.from_pretrained(
33
+ model_path,
34
+ device_map="auto",
35
+ trust_remote_code=True,
36
+ **config.model_kwargs
37
+ )
38
+ elif model_type == "gguf":
39
+ #TODO load the model first from the cache, if not found load the model and save it in the cache
40
+ #from huggingface_hub import hf_hub_download
41
+ #prm_model_path = hf_hub_download(
42
+ # repo_id="tensorblock/Llama3.1-8B-PRM-Mistral-Data-GGUF",
43
+ # filename="Llama3.1-8B-PRM-Mistral-Data-Q4_K_M.gguf"
44
+ #)
45
+
46
+
47
+ self.models[model_id] = self._load_quantized_model(
48
+ model_path,
49
+ **config.quantization_kwargs
50
+ )
51
+ except Exception as e:
52
+ self.logger.error(f"Failed to load model {model_id}: {str(e)}")
53
+ raise
54
+
55
+
56
+ def unload_model(self, model_id: str) -> None:
57
+ """Unload a model and free resources."""
58
+ if model_id in self.models:
59
+ del self.models[model_id]
60
+ if model_id in self.tokenizers:
61
+ del self.tokenizers[model_id]
62
+ torch.cuda.empty_cache()
63
+
64
+ def _load_quantized_model(self, model_path: str, **kwargs) -> Llama:
65
+ """Load a quantized GGUF model."""
66
+ try:
67
+ n_gpu_layers = -1 if torch.cuda.is_available() else 0
68
+ model = Llama(
69
+ model_path=model_path,
70
+ n_ctx=kwargs.get('n_ctx', 2048),
71
+ n_batch=kwargs.get('n_batch', 512),
72
+ n_gpu_layers=kwargs.get('n_gpu_layers', n_gpu_layers),
73
+ verbose=kwargs.get('verbose', False)
74
+ )
75
+ return model
76
+ except Exception as e:
77
+ self.logger.error(f"Failed to load GGUF model: {str(e)}")
78
+ raise