amaraaa commited on
Commit
f92dacd
·
verified ·
1 Parent(s): 330be2c

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +189 -0
handler.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # handler.py
2
+ # Hugging Face Inference Endpoint custom handler for Mongolian GPT-2 summarization
3
+ # Input JSON:
4
+ # {
5
+ # "inputs": "ARTICLE TEXT ...",
6
+ # "parameters": {
7
+ # "max_new_tokens": 160,
8
+ # "num_beams": 4,
9
+ # "do_sample": false,
10
+ # "no_repeat_ngram_size": 3,
11
+ # "length_penalty": 1.0,
12
+ # "temperature": 1.0,
13
+ # "top_p": 1.0,
14
+ # "top_k": 50,
15
+ # "return_full_text": false
16
+ # }
17
+ # }
18
+ # Output JSON:
19
+ # { "summary_text": "...", "used_new_tokens": 152, "requested_new_tokens": 160 }
20
+
21
+ from typing import Any, Dict, List, Union
22
+ import torch
23
+ from transformers import AutoTokenizer, AutoModelForCausalLM
24
+
25
+ # Mongolian instruction + prompt template used during training
26
+ INSTRUCTION = "Дараах бичвэрийг хураангуйлж бич."
27
+ PROMPT_TEMPLATE = (
28
+ "### Даалгавар:\n"
29
+ f"{INSTRUCTION}\n\n"
30
+ "### Бичвэр:\n{article}\n\n"
31
+ "### Хураангуй:\n"
32
+ )
33
+
34
+ def _select_dtype() -> torch.dtype:
35
+ if torch.cuda.is_available():
36
+ # Prefer bf16 if supported; otherwise use fp16
37
+ return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
38
+ return torch.float32
39
+
40
+ class EndpointHandler:
41
+ """
42
+ Custom handler for HF Inference Endpoints:
43
+ - __init__(path): loads model assets from `path`
44
+ - __call__(data): performs generation given {"inputs": ..., "parameters": {...}}
45
+ """
46
+ def __init__(self, path: str = ""):
47
+ # Device & dtype
48
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
+ self.dtype = _select_dtype()
50
+
51
+ # Load tokenizer/model from the repository directory
52
+ self.tokenizer = AutoTokenizer.from_pretrained(path, use_fast=True)
53
+ # Decoder-only model requires left padding for correct generation
54
+ self.tokenizer.padding_side = "left"
55
+ if self.tokenizer.pad_token is None:
56
+ self.tokenizer.pad_token = self.tokenizer.eos_token
57
+
58
+ self.model = AutoModelForCausalLM.from_pretrained(
59
+ path,
60
+ torch_dtype=self.dtype,
61
+ ).to(self.device)
62
+ # Safer attention path on many endpoint stacks
63
+ self.model.config.attn_implementation = "eager"
64
+ self.model.config.pad_token_id = self.tokenizer.pad_token_id
65
+ self.model.config.eos_token_id = self.tokenizer.eos_token_id
66
+ self.model.eval()
67
+
68
+ # Read max context from config (GPT-2 default is 1024)
69
+ self.max_context = getattr(self.model.config, "max_position_embeddings", 1024)
70
+
71
+ def _build_prompt(self, article: str) -> str:
72
+ return PROMPT_TEMPLATE.format(article=article.strip())
73
+
74
+ def _prepare_inputs(
75
+ self,
76
+ articles: List[str],
77
+ requested_new: int
78
+ ):
79
+ """
80
+ Tokenize prompts so that prompt_len + max_new_tokens <= max_context.
81
+ We first clamp requested_new, then tokenize with truncation=max_context - requested_new.
82
+ """
83
+ # Basic safety clamps
84
+ requested_new = int(max(1, min(requested_new, 512)))
85
+ max_len_for_prompt = max(1, self.max_context - requested_new)
86
+
87
+ prompts = [self._build_prompt(a) for a in articles]
88
+ enc = self.tokenizer(
89
+ prompts,
90
+ add_special_tokens=False,
91
+ truncation=True,
92
+ max_length=max_len_for_prompt,
93
+ return_tensors="pt",
94
+ padding=True, # uses left padding because tokenizer.padding_side="left"
95
+ )
96
+ enc = {k: v.to(self.device) for k, v in enc.items()}
97
+
98
+ # Compute per-example available space and adjust new tokens if needed
99
+ input_lens = enc["attention_mask"].sum(dim=1).tolist()
100
+ per_example_new = []
101
+ for L in input_lens:
102
+ available = max(0, self.max_context - int(L))
103
+ per_example_new.append(max(1, min(requested_new, available)))
104
+
105
+ return enc, per_example_new, prompts
106
+
107
+ @torch.no_grad()
108
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
109
+ # Accept either {"inputs": "..."} or {"inputs": ["...", "..."]}
110
+ raw_inputs: Union[str, List[str], Dict[str, Any]] = data.get("inputs", "")
111
+ params: Dict[str, Any] = data.get("parameters", {}) or {}
112
+
113
+ # Default generation hyperparameters (aligned with training)
114
+ req_new = int(params.get("max_new_tokens", 160))
115
+ num_beams = int(params.get("num_beams", 4))
116
+ do_sample = bool(params.get("do_sample", False))
117
+ no_repeat = int(params.get("no_repeat_ngram_size", 3))
118
+ length_penalty = float(params.get("length_penalty", 1.0))
119
+ temperature = float(params.get("temperature", 1.0))
120
+ top_p = float(params.get("top_p", 1.0))
121
+ top_k = int(params.get("top_k", 50))
122
+ return_full_text = bool(params.get("return_full_text", False))
123
+
124
+ # Normalize inputs to a list of strings
125
+ if isinstance(raw_inputs, str):
126
+ articles = [raw_inputs]
127
+ elif isinstance(raw_inputs, list):
128
+ if not all(isinstance(x, str) for x in raw_inputs):
129
+ raise ValueError("All elements of 'inputs' must be strings.")
130
+ articles = raw_inputs
131
+ else:
132
+ # Accept {"article": "..."} as a courtesy
133
+ maybe_article = data.get("article")
134
+ if isinstance(maybe_article, str):
135
+ articles = [maybe_article]
136
+ else:
137
+ raise ValueError("Expect 'inputs' as a string or list of strings.")
138
+
139
+ # Tokenize prompts and cap new tokens per example
140
+ enc, per_example_new, prompts = self._prepare_inputs(articles, req_new)
141
+
142
+ # Generate (batched)
143
+ gen_out = self.model.generate(
144
+ **enc,
145
+ max_new_tokens=max(per_example_new), # upper bound; actual stopping still respects EOS
146
+ num_beams=num_beams,
147
+ do_sample=do_sample,
148
+ no_repeat_ngram_size=no_repeat,
149
+ length_penalty=length_penalty,
150
+ temperature=temperature,
151
+ top_p=top_p,
152
+ top_k=top_k,
153
+ pad_token_id=self.tokenizer.pad_token_id,
154
+ eos_token_id=self.tokenizer.eos_token_id,
155
+ early_stopping=True,
156
+ )
157
+
158
+ # Decode and postprocess per-item (cut after the prompt if needed)
159
+ decoded = self.tokenizer.batch_decode(gen_out, skip_special_tokens=True)
160
+
161
+ results = []
162
+ for i, text in enumerate(decoded):
163
+ if return_full_text:
164
+ full = text.strip()
165
+ # Try to extract summary part for convenience too
166
+ split_key = "### Хураангуй:\n"
167
+ summary = full.split(split_key, 1)[-1].strip() if split_key in full else full
168
+ else:
169
+ # Remove the prompt prefix, return only the generated summary
170
+ prefix = prompts[i]
171
+ if text.startswith(prefix):
172
+ summary = text[len(prefix):].strip()
173
+ else:
174
+ # Fallback split on the marker
175
+ split_key = "### Хураангуй:\n"
176
+ summary = text.split(split_key, 1)[-1].strip() if split_key in text else text.strip()
177
+ full = None
178
+
179
+ results.append({
180
+ "summary_text": summary,
181
+ "used_new_tokens": per_example_new[i],
182
+ "requested_new_tokens": req_new,
183
+ **({"full_text": full} if return_full_text else {})
184
+ })
185
+
186
+ # If the input was a single string, return a single object
187
+ if isinstance(raw_inputs, str):
188
+ return results[0]
189
+ return {"results": results}