|
| 1 | +from typing import Dict |
| 2 | + |
| 3 | +import torch |
| 4 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 5 | + |
| 6 | + |
| 7 | +class Model: |
| 8 | + def __init__(self, data_dir: str, config: Dict, **kwargs): |
| 9 | + self.data_dir = data_dir |
| 10 | + self.config = config |
| 11 | + self.cuda_available = torch.cuda.is_available() |
| 12 | + |
| 13 | + def load(self): |
| 14 | + self.tokenizer = AutoTokenizer.from_pretrained( |
| 15 | + "databricks/dbrx-instruct", trust_remote_code=True, token=True |
| 16 | + ) |
| 17 | + |
| 18 | + if self.cuda_available: |
| 19 | + self.model = AutoModelForCausalLM.from_pretrained( |
| 20 | + "databricks/dbrx-instruct", |
| 21 | + trust_remote_code=True, |
| 22 | + token=True, |
| 23 | + torch_dtype=( |
| 24 | + torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 |
| 25 | + ), |
| 26 | + device_map="auto", |
| 27 | + attn_implementation=( |
| 28 | + "flash_attention_2" if "flash_attn" in locals() else "eager" |
| 29 | + ), |
| 30 | + ) |
| 31 | + else: |
| 32 | + self.model = AutoModelForCausalLM.from_pretrained( |
| 33 | + "databricks/dbrx-instruct", trust_remote_code=True, token=True |
| 34 | + ) |
| 35 | + |
| 36 | + def predict(self, request: Dict) -> Dict: |
| 37 | + self.load() # Reload model for each request |
| 38 | + |
| 39 | + prompt = request["prompt"] |
| 40 | + messages = [{"role": "user", "content": prompt}] |
| 41 | + |
| 42 | + tokenized_input = self.tokenizer.apply_chat_template( |
| 43 | + messages, tokenize=True, add_generation_prompt=True, return_tensors="pt" |
| 44 | + ) |
| 45 | + tokenized_input = tokenized_input.to(self.model.device) |
| 46 | + |
| 47 | + generated = self.model.generate( |
| 48 | + input_ids=tokenized_input, |
| 49 | + max_new_tokens=self.config.get("max_new_tokens", 100), |
| 50 | + temperature=self.config.get("temperature", 0.7), |
| 51 | + top_p=self.config.get("top_p", 0.95), |
| 52 | + top_k=self.config.get("top_k", 50), |
| 53 | + repetition_penalty=self.config.get("repetition_penalty", 1.01), |
| 54 | + pad_token_id=self.tokenizer.pad_token_id, |
| 55 | + ) |
| 56 | + |
| 57 | + decoded_output = self.tokenizer.batch_decode(generated)[0] |
| 58 | + response_text = decoded_output.split("<|im_start|> assistant\n")[-1] |
| 59 | + |
| 60 | + return {"result": response_text} |
0 commit comments