Update handler.py
Browse files- handler.py +21 -19
handler.py
CHANGED
@@ -2,7 +2,7 @@ import os
|
|
2 |
from typing import Dict, List, Any
|
3 |
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
|
4 |
import torch
|
5 |
-
from
|
6 |
from dotenv import load_dotenv
|
7 |
|
8 |
load_dotenv()
|
@@ -17,54 +17,55 @@ class EndpointHandler:
|
|
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", ".")
|
|
|
20 |
|
21 |
print(f"MODEL_DIR: {self.model_dir}")
|
22 |
print(f"Files in model directory: {os.listdir(self.model_dir)}")
|
23 |
|
24 |
# --- 1. Load Config ---
|
25 |
-
|
26 |
-
self.config = AutoConfig.from_pretrained(self.model_dir, token=self.hf_token, trust_remote_code=True)
|
27 |
|
28 |
# --- 2. Load Tokenizer ---
|
29 |
try:
|
30 |
-
self.tokenizer = AutoTokenizer.from_pretrained(self.
|
31 |
except Exception as e:
|
32 |
print(f"Error loading tokenizer: {e}")
|
33 |
raise
|
34 |
|
35 |
-
# --- 3. Load Model ---
|
36 |
try:
|
37 |
-
# Load base model
|
38 |
-
|
39 |
-
self.
|
40 |
config=self.config,
|
41 |
torch_dtype=torch.bfloat16,
|
42 |
token=self.hf_token,
|
43 |
device_map="auto",
|
44 |
-
trust_remote_code=True,
|
45 |
)
|
46 |
|
47 |
-
# Load
|
48 |
-
self.model =
|
49 |
-
FastLanguageModel.for_inference(
|
50 |
|
51 |
except Exception as e:
|
52 |
print(f"Error loading model: {e}")
|
53 |
raise
|
54 |
|
55 |
-
|
56 |
-
self.prompt_style = """Below is an instruction that describes a task, paired with an input that provides further context.
|
57 |
-
Write a response that appropriately completes the request.
|
58 |
Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.
|
59 |
### Instruction:
|
60 |
-
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.
|
61 |
-
Always be professional and precise in your responses.
|
62 |
-
|
63 |
### Question:
|
64 |
{}
|
65 |
### Response:
|
66 |
<think>{}"""
|
67 |
|
|
|
|
|
68 |
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
69 |
"""
|
70 |
Processes the input and generates a response.
|
@@ -82,7 +83,8 @@ Always be professional and precise in your responses.
|
|
82 |
if torch.cuda.is_available():
|
83 |
input_tokens = input_tokens.to("cuda")
|
84 |
|
85 |
-
|
|
|
86 |
output_tokens = self.model.generate(
|
87 |
input_ids=input_tokens.input_ids,
|
88 |
attention_mask=input_tokens.attention_mask,
|
|
|
2 |
from typing import Dict, List, Any
|
3 |
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
|
4 |
import torch
|
5 |
+
from peft import PeftModel # Import PeftModel
|
6 |
from dotenv import load_dotenv
|
7 |
|
8 |
load_dotenv()
|
|
|
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", ".")
|
20 |
+
self.base_model_name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B" # The base model ID
|
21 |
|
22 |
print(f"MODEL_DIR: {self.model_dir}")
|
23 |
print(f"Files in model directory: {os.listdir(self.model_dir)}")
|
24 |
|
25 |
# --- 1. Load Config ---
|
26 |
+
self.config = AutoConfig.from_pretrained(self.base_model_name, token=self.hf_token, trust_remote_code=True)
|
|
|
27 |
|
28 |
# --- 2. Load Tokenizer ---
|
29 |
try:
|
30 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.base_model_name, token=self.hf_token, trust_remote_code=True)
|
31 |
except Exception as e:
|
32 |
print(f"Error loading tokenizer: {e}")
|
33 |
raise
|
34 |
|
35 |
+
# --- 3. Load Model with PeftModel ---
|
36 |
try:
|
37 |
+
# Load base model
|
38 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
39 |
+
self.base_model_name,
|
40 |
config=self.config,
|
41 |
torch_dtype=torch.bfloat16,
|
42 |
token=self.hf_token,
|
43 |
device_map="auto",
|
44 |
+
trust_remote_code=True,
|
45 |
)
|
46 |
|
47 |
+
# Load the LoRA model using PeftModel
|
48 |
+
self.model = PeftModel.from_pretrained(base_model, self.model_dir)
|
49 |
+
# No need for FastLanguageModel.for_inference() here, PeftModel handles it
|
50 |
|
51 |
except Exception as e:
|
52 |
print(f"Error loading model: {e}")
|
53 |
raise
|
54 |
|
55 |
+
# Define the prompt style
|
56 |
+
self.prompt_style = """Below is an instruction that describes a task, paired with an input that provides further context.
|
57 |
+
Write a response that appropriately completes the request.
|
58 |
Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.
|
59 |
### Instruction:
|
60 |
+
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.
|
61 |
+
Always be professional and precise in your responses.
|
|
|
62 |
### Question:
|
63 |
{}
|
64 |
### Response:
|
65 |
<think>{}"""
|
66 |
|
67 |
+
|
68 |
+
|
69 |
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
70 |
"""
|
71 |
Processes the input and generates a response.
|
|
|
83 |
if torch.cuda.is_available():
|
84 |
input_tokens = input_tokens.to("cuda")
|
85 |
|
86 |
+
|
87 |
+
with torch.no_grad(): # Ensure no gradient calculation
|
88 |
output_tokens = self.model.generate(
|
89 |
input_ids=input_tokens.input_ids,
|
90 |
attention_mask=input_tokens.attention_mask,
|