Commit
·
fe561b9
1
Parent(s):
4456dcd
Upload handler.py
Browse files- handler.py +51 -0
handler.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Any
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
+
from peft import PeftConfig, PeftModel
|
| 6 |
+
import torch.cuda
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
LOGGER = logging.getLogger(__name__)
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class EndpointHandler():
|
| 15 |
+
def __init__(self, path=""):
|
| 16 |
+
config = PeftConfig.from_pretrained(path)
|
| 17 |
+
model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, load_in_4bit=True, device_map='auto')
|
| 18 |
+
self.tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
|
| 19 |
+
# Load the Lora model
|
| 20 |
+
self.model = PeftModel.from_pretrained(model, path)
|
| 21 |
+
|
| 22 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 23 |
+
"""
|
| 24 |
+
Args:
|
| 25 |
+
data (Dict): The payload with the text prompt and generation parameters.
|
| 26 |
+
"""
|
| 27 |
+
LOGGER.info(f"Received data: {data}")
|
| 28 |
+
# Get inputs
|
| 29 |
+
query = data.pop("inputs", None)
|
| 30 |
+
prompt_template = """
|
| 31 |
+
Below is a screenplay prompt followed by a screenplay response. Generate only screenplay response.
|
| 32 |
+
### Screenplay Prompt:
|
| 33 |
+
{query}
|
| 34 |
+
|
| 35 |
+
### Screenplay Response:
|
| 36 |
+
"""
|
| 37 |
+
prompt = prompt_template.format(query=query)
|
| 38 |
+
parameters = data.pop("parameters", None)
|
| 39 |
+
if prompt is None:
|
| 40 |
+
raise ValueError("Missing prompt.")
|
| 41 |
+
# Preprocess
|
| 42 |
+
encodeds = self.tokenizer(prompt, return_tensors="pt", add_special_tokens=True)
|
| 43 |
+
|
| 44 |
+
model_inputs = encodeds.to(device)
|
| 45 |
+
|
| 46 |
+
# Forward
|
| 47 |
+
LOGGER.info(f"Start generation.")
|
| 48 |
+
generated_ids = self.model.generate(**model_inputs, max_new_tokens=9999999, do_sample=True, pad_token_id=tokenizer.eos_token_id)
|
| 49 |
+
decoded = self.tokenizer.batch_decode(generated_ids)
|
| 50 |
+
LOGGER.info(f"Generated text length: {len(decoded[0])}")
|
| 51 |
+
return {"generated_text": decoded[0]}
|