| |
| from typing import Dict, Any, List |
| import torch |
| from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig |
|
|
| class EndpointHandler(): |
| def __init__(self, path=""): |
| """ |
| Carrega o modelo e o tokenizador usando quantização de 4 bits (Q4). |
| """ |
| |
| quantization_config = BitsAndBytesConfig( |
| load_in_4bit=True, |
| bnb_4bit_quant_type="nf4", |
| bnb_4bit_compute_dtype=torch.float16, |
| bnb_4bit_use_double_quant=True |
| ) |
|
|
| |
| self.tokenizer = AutoTokenizer.from_pretrained(path) |
| self.model = AutoModelForCausalLM.from_pretrained( |
| path, |
| quantization_config=quantization_config, |
| device_map="auto" |
| ) |
| |
| |
| self.pipeline = pipeline( |
| "text-generation", |
| model=self.model, |
| tokenizer=self.tokenizer |
| ) |
|
|
| def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: |
| """ |
| Processa as requisições que chegam na API do Inference Endpoint. |
| """ |
| |
| inputs = data.pop("inputs", data) |
| parameters = data.pop("parameters", {}) |
|
|
| if not inputs: |
| return [{"error": "O campo 'inputs' é obrigatório."}] |
|
|
| |
| prediction = self.pipeline(inputs, **parameters) |
|
|
| |
| return prediction |