File size: 2,023 Bytes
7a3dd67
abaf9f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dad39b
 
44c613f
 
0dad39b
44c613f
 
 
 
 
 
 
 
 
0dad39b
abaf9f1
 
 
fff699d
 
abaf9f1
44c613f
0dad39b
abaf9f1
44c613f
abaf9f1
 
 
 
44c613f
abaf9f1
 
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
from transformers import AutoTokenizer, AutoModelForCausalLM, LlamaConfig
from sentence_transformers import SentenceTransformer
import torch
from functools import lru_cache
from config.config import settings
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 and update rope_scaling if necessary
            if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
                logger.info("Updating rope_scaling in configuration...")
                config.rope_scaling = {
                    "type": "linear",  # Ensure this matches the expected type
                    "factor": config.rope_scaling.get('factor', 1.0)  # Use existing factor or default to 1.0
                }
    
            # Load model with the updated configuration
            self.model = AutoModelForCausalLM.from_pretrained(
                settings.MODEL_NAME,
                torch_dtype=torch.float16 if settings.DEVICE == "cuda" else torch.float32,
                device_map="auto" if settings.DEVICE == "cuda" else None,
                config=config
            )
    
            # 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