File size: 1,469 Bytes
2a339d3
3aac9e2
2a339d3
 
 
 
 
 
 
 
 
 
 
3aac9e2
2a339d3
 
 
 
 
 
 
 
 
 
 
 
 
4c71332
 
2a339d3
 
 
4c71332
2a339d3
4c71332
2a339d3
 
 
 
 
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
from typing import Dict, Any
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer
import torch

class EndpointHandler:
    def __init__(self, path=""):
        model_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
        quantization_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_compute_dtype=torch.float16
        )
        # load model and processor from path
        self.model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config)
        self.tokenizer = AutoTokenizer.from_pretrained(model_id)

    def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
        """
        Args:
            data (:dict:):
                The payload with the text prompt and generation parameters.
        """
        # process input
        inputs = data.pop("inputs", data)
        parameters = data.pop("parameters", None)
        inputs = f"[INST] {inputs} [/INST]"

        # preprocess
        inputs = self.tokenizer(inputs, return_tensors="pt")
        inputs = inputs.to(self.model.device)

        # pass inputs with all kwargs in data
        if parameters is not None:
            outputs = self.model.generate(inputs, **parameters)
        else:
            outputs = self.model.generate(inputs)

        # postprocess the prediction
        prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True)

        return [{"generated_text": prediction}]