Create handler.py
Browse files- handler.py +100 -0
handler.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import Dict, List, Any
|
3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
|
4 |
+
import torch
|
5 |
+
from unsloth import FastLanguageModel # Import Unsloth
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
|
8 |
+
load_dotenv()
|
9 |
+
|
10 |
+
class EndpointHandler:
|
11 |
+
def __init__(self, path=""):
|
12 |
+
"""
|
13 |
+
Initializes the model and tokenizer.
|
14 |
+
"""
|
15 |
+
# Key settings (from environment variables, with defaults)
|
16 |
+
max_seq_length = int(os.getenv("MAX_SEQ_LENGTH", 2048))
|
17 |
+
max_new_tokens = int(os.getenv("MAX_NEW_TOKENS", 512))
|
18 |
+
self.hf_token = os.getenv("HUGGINGFACE_TOKEN")
|
19 |
+
self.model_dir = os.getenv("MODEL_DIR", ".") # Ensure this is set correctly
|
20 |
+
|
21 |
+
print(f"MODEL_DIR: {self.model_dir}") # Debug print
|
22 |
+
print(f"Files in model directory: {os.listdir(self.model_dir)}") # VERY IMPORTANT
|
23 |
+
|
24 |
+
# --- 1. Load Config ---
|
25 |
+
# Load the configuration first to determine the base model type
|
26 |
+
self.config = AutoConfig.from_pretrained(self.model_dir, token=self.hf_token)
|
27 |
+
|
28 |
+
# --- 2. Load Tokenizer ---
|
29 |
+
# Load the tokenizer. Handle tokenizer loading errors.
|
30 |
+
try:
|
31 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_dir, token=self.hf_token)
|
32 |
+
except Exception as e:
|
33 |
+
print(f"Error loading tokenizer: {e}")
|
34 |
+
raise
|
35 |
+
|
36 |
+
# --- 3. Load Model ---
|
37 |
+
# Load the base model *and* apply the LoRA adapter. Handle model loading.
|
38 |
+
try:
|
39 |
+
# Load base model (using config to determine correct class)
|
40 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
41 |
+
self.config.base_model_name_or_path, # Use base model from config!
|
42 |
+
config=self.config,
|
43 |
+
torch_dtype=torch.bfloat16, # Use bfloat16 if available
|
44 |
+
token=self.hf_token,
|
45 |
+
device_map="auto", # Let transformers handle device placement
|
46 |
+
)
|
47 |
+
|
48 |
+
# Load and apply the LoRA adapter
|
49 |
+
self.model = FastLanguageModel.get_peft_model(self.model, self.model_dir) #model_dir contains lora weights
|
50 |
+
FastLanguageModel.for_inference(self.model) #Unsloth speed up
|
51 |
+
|
52 |
+
except Exception as e:
|
53 |
+
print(f"Error loading model: {e}")
|
54 |
+
raise
|
55 |
+
|
56 |
+
# Define the prompt style
|
57 |
+
self.prompt_style = """Below is an instruction that describes a task, paired with an input that provides further context.
|
58 |
+
Write a response that appropriately completes the request.
|
59 |
+
Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.
|
60 |
+
### Instruction:
|
61 |
+
You are BuildwellAI, an AI assistant specialized in UK building regulations and construction standards. You provide accurate, helpful information about building codes, construction best practices, and regulatory compliance in the UK.
|
62 |
+
Always be professional and precise in your responses.
|
63 |
+
### Question:
|
64 |
+
{}
|
65 |
+
### Response:
|
66 |
+
<think>{}"""
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
71 |
+
"""
|
72 |
+
Processes the input and generates a response.
|
73 |
+
"""
|
74 |
+
inputs = data.pop("inputs", None)
|
75 |
+
if inputs is None:
|
76 |
+
return [{"error": "No input provided. 'inputs' key missing."}]
|
77 |
+
if not isinstance(inputs, str):
|
78 |
+
return [{"error": "Invalid input type. 'inputs' must be a string."}]
|
79 |
+
|
80 |
+
input_text = self.prompt_style.format(inputs, "")
|
81 |
+
|
82 |
+
# Tokenize and move to CUDA (if available)
|
83 |
+
input_tokens = self.tokenizer([input_text], return_tensors="pt")
|
84 |
+
if torch.cuda.is_available():
|
85 |
+
input_tokens = input_tokens.to("cuda")
|
86 |
+
|
87 |
+
|
88 |
+
with torch.no_grad(): # Ensure no gradient calculation
|
89 |
+
output_tokens = self.model.generate(
|
90 |
+
input_ids=input_tokens.input_ids,
|
91 |
+
attention_mask=input_tokens.attention_mask,
|
92 |
+
max_new_tokens=max_new_tokens,
|
93 |
+
use_cache=True,
|
94 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
95 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
96 |
+
)
|
97 |
+
|
98 |
+
generated_text = self.tokenizer.batch_decode(output_tokens, skip_special_tokens=True)[0]
|
99 |
+
response = generated_text.split("### Response:")[-1].strip()
|
100 |
+
return [{"generated_text": response}]
|