File size: 1,864 Bytes
7a3dd67
e0da0b4
abaf9f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dad39b
 
32a90bc
86179ff
 
32a90bc
 
 
 
 
 
0dad39b
abaf9f1
16f48ef
86179ff
abaf9f1
86179ff
abaf9f1
32a90bc
0dad39b
abaf9f1
32a90bc
abaf9f1
 
 
 
 
2ebc95a
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
from transformers import AutoTokenizer, AutoModelForCausalLM, LlamaConfig
from config.config import settings
from sentence_transformers import SentenceTransformer
import torch
import logging

logger = logging.getLogger(__name__)

class ModelService:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance

    def __init__(self):
        if not self._initialized:
            self._initialized = True
            self._load_models()

    def _load_models(self):
        try:
            # Load tokenizer
            self.tokenizer = AutoTokenizer.from_pretrained(settings.MODEL_NAME)

            # Load model configuration
            config = LlamaConfig.from_pretrained(settings.MODEL_NAME)

            # Check quantization type and adjust accordingly
            if config.get('quantization_config', {}).get('type', '') == 'compressed-tensors':
                logger.warning("Quantization type 'compressed-tensors' is not supported. Switching to 'bitsandbytes_8bit'.")
                config.quantization_config['type'] = 'bitsandbytes_8bit'

            # Load model with the updated configuration
            self.model = AutoModelForCausalLM.from_pretrained(
                settings.MODEL_NAME, 
                config=config, 
                torch_dtype=torch.float16 if settings.DEVICE == "cuda" else torch.float32,
                device_map="auto" if settings.DEVICE == "cuda" else None
            )

            # Load sentence embedder
            self.embedder = SentenceTransformer(settings.EMBEDDER_MODEL)

        except Exception as e:
            logger.error(f"Error loading models: {e}")
            raise

    def get_models(self):
        return self.tokenizer, self.model, self.embedder