Update handler.py
Browse files- handler.py +31 -35
handler.py
CHANGED
|
@@ -1,47 +1,43 @@
|
|
| 1 |
-
|
| 2 |
import torch
|
| 3 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM,
|
| 4 |
-
from peft import PeftModel, PeftConfig
|
| 5 |
|
| 6 |
class EndpointHandler:
|
| 7 |
-
def __init__(self, model_dir
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
|
| 11 |
-
# Load
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
)
|
| 18 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
device_map="auto",
|
| 22 |
-
trust_remote_code=True
|
| 23 |
)
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
base_model = prepare_model_for_kbit_training(base_model)
|
| 27 |
-
|
| 28 |
-
# Load PEFT adapter
|
| 29 |
self.model = PeftModel.from_pretrained(base_model, model_dir)
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 34 |
-
inputs = data.get("inputs", "")
|
| 35 |
-
gen_kwargs = data.get("parameters", {"max_new_tokens": 256, "do_sample": True})
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
)
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import torch
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 4 |
+
from peft import PeftModel, PeftConfig
|
| 5 |
|
| 6 |
class EndpointHandler:
|
| 7 |
+
def __init__(self, model_dir):
|
| 8 |
+
# Optional: Get Hugging Face token for gated models
|
| 9 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 10 |
|
| 11 |
+
# Load the PEFT adapter config
|
| 12 |
+
peft_config = PeftConfig.from_pretrained(model_dir)
|
| 13 |
+
|
| 14 |
+
# Load the base model and tokenizer (add use_auth_token if model is gated)
|
| 15 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 16 |
+
peft_config.base_model_name_or_path,
|
| 17 |
+
use_auth_token=hf_token
|
| 18 |
)
|
| 19 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
+
peft_config.base_model_name_or_path,
|
| 21 |
+
use_auth_token=hf_token
|
|
|
|
|
|
|
| 22 |
)
|
| 23 |
|
| 24 |
+
# Load the adapter onto the base model
|
|
|
|
|
|
|
|
|
|
| 25 |
self.model = PeftModel.from_pretrained(base_model, model_dir)
|
| 26 |
+
self.model.eval() # Set to evaluation mode
|
| 27 |
|
| 28 |
+
# Set device for pipeline: 0 for GPU, -1 for CPU
|
| 29 |
+
device = 0 if torch.cuda.is_available() else -1
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# Create the text generation pipeline with device assignment
|
| 32 |
+
self.generator = pipeline(
|
| 33 |
+
"text-generation",
|
| 34 |
+
model=self.model,
|
| 35 |
+
tokenizer=self.tokenizer,
|
| 36 |
+
device=device
|
| 37 |
+
)
|
|
|
|
| 38 |
|
| 39 |
+
def __call__(self, inputs):
|
| 40 |
+
text = inputs.get("inputs", "")
|
| 41 |
+
# You can add more generation parameters here as needed
|
| 42 |
+
results = self.generator(text)
|
| 43 |
+
return results
|