Upload 2 files
Browse files- handler.py +48 -0
- requirements.txt +4 -0
handler.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from typing import Dict, List, Any
|
4 |
+
from transformers import AutoTokenizer, BitsAndBytesConfig
|
5 |
+
from peft import AutoPeftModelForCausalLM
|
6 |
+
|
7 |
+
|
8 |
+
def parse_output(text):
|
9 |
+
marker = "### Response:"
|
10 |
+
if marker in text:
|
11 |
+
pos = text.find(marker) + len(marker)
|
12 |
+
else:
|
13 |
+
pos = 0
|
14 |
+
return text[pos:].replace("<pad>", "").replace("</s>", "").strip()
|
15 |
+
|
16 |
+
|
17 |
+
class EndpointHandler:
|
18 |
+
def __init__(self, path="./", use_bnb=True):
|
19 |
+
|
20 |
+
bnb_config = BitsAndBytesConfig(
|
21 |
+
load_in_4bit=True,
|
22 |
+
bnb_4bit_use_double_quant=True,
|
23 |
+
bnb_4bit_quant_type="nf4",
|
24 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
25 |
+
)
|
26 |
+
self.model = AutoPeftModelForCausalLM.from_pretrained(
|
27 |
+
path, load_in_8bit=False, quantization_config=bnb_config, device_map="auto"
|
28 |
+
)
|
29 |
+
|
30 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
31 |
+
|
32 |
+
def __call__(self, data: Any) -> List[List[Dict[str, str]]]:
|
33 |
+
|
34 |
+
|
35 |
+
inputs = data.get("inputs", data)
|
36 |
+
prompt = f"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction: \n{inputs}\n\n### Response: \n"
|
37 |
+
parameters = data.get("parameters", {})
|
38 |
+
with torch.no_grad():
|
39 |
+
inputs = self.tokenizer(
|
40 |
+
prompt, return_tensors="pt", return_token_type_ids=False
|
41 |
+
).to(self.model.device)
|
42 |
+
outputs = self.model.generate(**inputs, **parameters)
|
43 |
+
|
44 |
+
return {
|
45 |
+
"generated_text": parse_output(
|
46 |
+
self.tokenizer.decode(outputs[0].tolist(), skip_special_tokens=True)
|
47 |
+
)
|
48 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
git+https://github.com/huggingface/transformers.git
|
2 |
+
bitsandbytes
|
3 |
+
git+https://github.com/huggingface/accelerate.git
|
4 |
+
git+https://github.com/huggingface/peft.git
|