Remove internal serving handler from public release
Browse files- handler.py +0 -99
handler.py
DELETED
|
@@ -1,99 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import torch
|
| 3 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
-
|
| 5 |
-
# Keep only the last round (1 user+assistant pair) + the current user message
|
| 6 |
-
MAX_HISTORY_MESSAGES = 3
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
class EndpointHandler:
|
| 10 |
-
"""
|
| 11 |
-
Hugging Face Inference Endpoints custom handler.
|
| 12 |
-
|
| 13 |
-
Expects input like:
|
| 14 |
-
- {"inputs": "hello"} -> single-turn, auto-wrapped with chat template
|
| 15 |
-
- {"inputs": [{"role":"user","content":"hello"}, ...]} -> multi-turn chat (messages list)
|
| 16 |
-
- {"inputs": "hello", "parameters": {"raw": true}} -> sent as-is (no template)
|
| 17 |
-
|
| 18 |
-
Optional:
|
| 19 |
-
- {"parameters": {"max_new_tokens": 512, "temperature": 0.7, ...}}
|
| 20 |
-
"""
|
| 21 |
-
|
| 22 |
-
def __init__(self, path: str = ""):
|
| 23 |
-
model_dir = path or os.getenv("HF_MODEL_DIR", ".")
|
| 24 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 25 |
-
|
| 26 |
-
self.tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
| 27 |
-
|
| 28 |
-
# Ensure pad token exists (common for causal LMs)
|
| 29 |
-
if self.tokenizer.pad_token is None:
|
| 30 |
-
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 31 |
-
self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
self.model = AutoModelForCausalLM.from_pretrained(
|
| 35 |
-
model_dir,
|
| 36 |
-
torch_dtype="auto",
|
| 37 |
-
device_map="auto" if torch.cuda.is_available() else None,
|
| 38 |
-
trust_remote_code=True,
|
| 39 |
-
)
|
| 40 |
-
self.model.eval()
|
| 41 |
-
|
| 42 |
-
def __call__(self, data: dict) -> dict:
|
| 43 |
-
inputs = data.get("inputs", data)
|
| 44 |
-
params = data.get("parameters", {}) or {}
|
| 45 |
-
|
| 46 |
-
raw = bool(params.pop("raw", False))
|
| 47 |
-
|
| 48 |
-
if raw:
|
| 49 |
-
if not isinstance(inputs, str):
|
| 50 |
-
raise ValueError("raw mode requires inputs to be a string.")
|
| 51 |
-
prompt = inputs
|
| 52 |
-
elif isinstance(inputs, list):
|
| 53 |
-
# Multi-turn: inputs is a list of {"role": ..., "content": ...}
|
| 54 |
-
inputs = inputs[-MAX_HISTORY_MESSAGES:]
|
| 55 |
-
prompt = self.tokenizer.apply_chat_template(
|
| 56 |
-
inputs, tokenize=False,
|
| 57 |
-
)
|
| 58 |
-
elif isinstance(inputs, str):
|
| 59 |
-
# Single-turn: wrap in a one-message list
|
| 60 |
-
prompt = self.tokenizer.apply_chat_template(
|
| 61 |
-
[{"role": "user", "content": inputs}],
|
| 62 |
-
tokenize=False,
|
| 63 |
-
)
|
| 64 |
-
else:
|
| 65 |
-
raise ValueError("inputs must be a string or a list of messages.")
|
| 66 |
-
|
| 67 |
-
enc = self.tokenizer(
|
| 68 |
-
prompt,
|
| 69 |
-
return_tensors="pt",
|
| 70 |
-
padding=False,
|
| 71 |
-
truncation=True,
|
| 72 |
-
)
|
| 73 |
-
input_ids = enc["input_ids"].to(self.model.device)
|
| 74 |
-
attention_mask = enc.get("attention_mask", torch.ones_like(input_ids)).to(self.model.device)
|
| 75 |
-
|
| 76 |
-
gen_kwargs = {
|
| 77 |
-
"max_new_tokens": min(int(params.pop("max_new_tokens", 512)), 512),
|
| 78 |
-
"do_sample": bool(params.pop("do_sample", True)),
|
| 79 |
-
"temperature": float(params.pop("temperature", 0.7)),
|
| 80 |
-
"top_p": float(params.pop("top_p", 0.95)),
|
| 81 |
-
"repetition_penalty": float(params.pop("repetition_penalty", 1.2)),
|
| 82 |
-
"eos_token_id": self.tokenizer.eos_token_id,
|
| 83 |
-
"pad_token_id": self.tokenizer.pad_token_id,
|
| 84 |
-
}
|
| 85 |
-
gen_kwargs.update(params)
|
| 86 |
-
|
| 87 |
-
with torch.no_grad():
|
| 88 |
-
out = self.model.generate(
|
| 89 |
-
input_ids=input_ids,
|
| 90 |
-
attention_mask=attention_mask,
|
| 91 |
-
**gen_kwargs,
|
| 92 |
-
)
|
| 93 |
-
|
| 94 |
-
# Return only newly generated tokens (your current behavior)
|
| 95 |
-
new_tokens = out[0, input_ids.shape[-1]:]
|
| 96 |
-
text = self.tokenizer.decode(new_tokens, skip_special_tokens=True)
|
| 97 |
-
|
| 98 |
-
return {"generated_text": text}
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|