Ephraimmm commited on
Commit
1e124b5
·
verified ·
1 Parent(s): 737433c

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +281 -83
handler.py CHANGED
@@ -1,113 +1,311 @@
1
  # handler.py
2
 
3
- from typing import Any, Dict
4
- import torch
5
- from transformers import AutoModelForCausalLM, AutoTokenizer
6
- from huggingface_inference_toolkit.logging import logger
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- model_dir = 'Ephraimmm/PIDGIN_gemma-3'
 
 
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
 
11
 
 
 
 
 
 
12
  class EndpointHandler:
 
13
  """
 
14
  Custom handler for Hugging Face Inference Endpoints.
 
 
 
15
  """
 
 
16
 
17
- def __init__(self, model_dir: str, **kwargs: Any):
18
  """
19
- Called once at startup. `model_dir` is the path to the downloaded model repository.
20
- You can load your model, tokenizer, etc. here.
 
21
  """
 
22
  logger.info(f"Initializing EndpointHandler with model_dir = {model_dir}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
- # load tokenizer and model from the model_dir or hub
25
- base_model_name = "unsloth/gemma-3-4b-it-unsloth-bnb-4bit"
26
- base_model, tokenizer = FastLanguageModel.from_pretrained(
27
- model_name=base_model_name,
28
- max_seq_length=2048,
29
- dtype=torch.float16,
30
- load_in_4bit=True,
31
- r = 8, # Larger = higher accuracy, but might overfit
32
- lora_alpha = 8, # Recommended alpha == r at least
33
- lora_dropout = 0,
34
  )
35
-
36
- # -----------------------------
37
- # 3️⃣ Load LoRA
38
- # -----------------------------
39
- lora_repo = "Ephraimmm/PIDGIN_gemma-3" #"Ephraimmm/pigin-gemma-3-0.2" #"Ephraimmm/Pidgin_llamma_model"
40
- lora_model = PeftModel.from_pretrained(base_model, lora_repo, adapter_name="adapter_model")
41
- FastLanguageModel.for_inference(lora_model)
42
-
43
- # we assume model files are present in model_dir
44
- # try:
45
- # self.tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False)
46
- # self.model = AutoModelForCausalLM.from_pretrained(model_dir)
47
- # except Exception as e:
48
- # # fallback: try loading from hub name
49
- # hf_model_id = "Ephraimmm/PIDGIN_gemma-3"
50
- # logger.warn(f"Loading model from hub id {hf_model_id} because fallback. Exception: {e}")
51
- # self.tokenizer = AutoTokenizer.from_pretrained(hf_model_id, use_fast=False)
52
- # self.model = AutoModelForCausalLM.from_pretrained(hf_model_id)
53
-
54
- # put the model on GPU if available
55
- self.device = "cuda" if torch.cuda.is_available() else "cpu"
56
- self.model = self.model.to(self.device)
57
- self.model.eval()
58
-
59
- # You could also load extra assets, set up config, etc.
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
 
62
  """
63
- Called on each API request. `data` is the parsed JSON body from the request.
64
- Must return a JSON-serializable structure.
65
- The `data` dict always has an “inputs” key (unless you change it).
66
  """
67
- logger.info(f"EndpointHandler received data: {data}")
68
-
69
- # Extract the prompt (the "inputs" key)
70
- prompt = data.get("inputs")
71
- if prompt is None:
72
- raise ValueError("Request JSON must contain an `inputs` field with the prompt string.")
73
-
74
- # optional: support generation parameters from the payload
75
- max_new_tokens = data.get("parameters", {}).get("max_new_tokens", 50)
76
- temperature = data.get("parameters", {}).get("temperature", 1.0)
77
- top_k = data.get("parameters", {}).get("top_k", 50)
78
- top_p = data.get("parameters", {}).get("top_p", 1.0)
79
- do_sample = data.get("parameters", {}).get("do_sample", True)
80
-
81
- # Tokenize
82
- inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
83
-
84
- # Generate
85
- output = self.model.generate(
86
- **inputs,
87
- max_new_tokens=max_new_tokens,
88
- temperature=temperature,
89
- top_k=top_k,
90
- top_p=top_p,
91
- do_sample=do_sample,
92
- )
93
 
94
- # Decode
95
- full = self.tokenizer.decode(output[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # Optionally remove the original prompt from the returned text to send only the continuation
98
- continuation = full[len(prompt):] if full.startswith(prompt) else full
99
 
100
- # Prepare response in the shape expected by Inference Endpoints
101
- # The “predictions” key is often used (the default inference service expects it)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  return {
103
- "predictions": [full],
 
 
104
  "continuations": [continuation],
105
- }
106
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
- # For local testing (not used in production)
109
  if __name__ == "__main__":
110
- # Quick local test
111
  h = EndpointHandler(model_dir=".")
112
- resp = h({"inputs": "Once upon a time", "parameters": {"max_new_tokens": 20}})
 
 
 
 
 
 
 
 
113
  print("Response:", resp)
 
 
 
1
  # handler.py
2
 
3
+ # from typing import Any, Dict
4
+ # import torch
5
+ # from transformers import AutoModelForCausalLM, AutoTokenizer
6
+ # from huggingface_inference_toolkit.logging import logger
7
+
8
+ # model_dir = 'Ephraimmm/PIDGIN_gemma-3'
9
+
10
+
11
+
12
+ # class EndpointHandler:
13
+ # """
14
+ # Custom handler for Hugging Face Inference Endpoints.
15
+ # """
16
+
17
+ # def __init__(self, model_dir: str, **kwargs: Any):
18
+ # """
19
+ # Called once at startup. `model_dir` is the path to the downloaded model repository.
20
+ # You can load your model, tokenizer, etc. here.
21
+ # """
22
+ # logger.info(f"Initializing EndpointHandler with model_dir = {model_dir}")
23
+
24
+ # # load tokenizer and model from the model_dir or hub
25
+ # base_model_name = "unsloth/gemma-3-4b-it-unsloth-bnb-4bit"
26
+ # base_model, tokenizer = FastLanguageModel.from_pretrained(
27
+ # model_name=base_model_name,
28
+ # max_seq_length=2048,
29
+ # dtype=torch.float16,
30
+ # load_in_4bit=True,
31
+ # r = 8, # Larger = higher accuracy, but might overfit
32
+ # lora_alpha = 8, # Recommended alpha == r at least
33
+ # lora_dropout = 0,
34
+ # )
35
+
36
+ # # -----------------------------
37
+ # # 3️⃣ Load LoRA
38
+ # # -----------------------------
39
+ # lora_repo = "Ephraimmm/PIDGIN_gemma-3" #"Ephraimmm/pigin-gemma-3-0.2" #"Ephraimmm/Pidgin_llamma_model"
40
+ # lora_model = PeftModel.from_pretrained(base_model, lora_repo, adapter_name="adapter_model")
41
+ # FastLanguageModel.for_inference(lora_model)
42
+
43
+ # # we assume model files are present in model_dir
44
+ # # try:
45
+ # # self.tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False)
46
+ # # self.model = AutoModelForCausalLM.from_pretrained(model_dir)
47
+ # # except Exception as e:
48
+ # # # fallback: try loading from hub name
49
+ # # hf_model_id = "Ephraimmm/PIDGIN_gemma-3"
50
+ # # logger.warn(f"Loading model from hub id {hf_model_id} because fallback. Exception: {e}")
51
+ # # self.tokenizer = AutoTokenizer.from_pretrained(hf_model_id, use_fast=False)
52
+ # # self.model = AutoModelForCausalLM.from_pretrained(hf_model_id)
53
+
54
+ # # put the model on GPU if available
55
+ # self.device = "cuda" if torch.cuda.is_available() else "cpu"
56
+ # self.model = self.model.to(self.device)
57
+ # self.model.eval()
58
+
59
+ # # You could also load extra assets, set up config, etc.
60
+
61
+ # def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
62
+ # """
63
+ # Called on each API request. `data` is the parsed JSON body from the request.
64
+ # Must return a JSON-serializable structure.
65
+ # The `data` dict always has an “inputs” key (unless you change it).
66
+ # """
67
+ # logger.info(f"EndpointHandler received data: {data}")
68
 
69
+ # # Extract the prompt (the "inputs" key)
70
+ # prompt = data.get("inputs")
71
+ # if prompt is None:
72
+ # raise ValueError("Request JSON must contain an `inputs` field with the prompt string.")
73
 
74
+ # # optional: support generation parameters from the payload
75
+ # max_new_tokens = data.get("parameters", {}).get("max_new_tokens", 50)
76
+ # temperature = data.get("parameters", {}).get("temperature", 1.0)
77
+ # top_k = data.get("parameters", {}).get("top_k", 50)
78
+ # top_p = data.get("parameters", {}).get("top_p", 1.0)
79
+ # do_sample = data.get("parameters", {}).get("do_sample", True)
80
+
81
+ # # Tokenize
82
+ # inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
83
+
84
+ # # Generate
85
+ # output = self.model.generate(
86
+ # **inputs,
87
+ # max_new_tokens=max_new_tokens,
88
+ # temperature=temperature,
89
+ # top_k=top_k,
90
+ # top_p=top_p,
91
+ # do_sample=do_sample,
92
+ # )
93
+
94
+ # # Decode
95
+ # full = self.tokenizer.decode(output[0], skip_special_tokens=True)
96
+
97
+ # # Optionally remove the original prompt from the returned text to send only the continuation
98
+ # continuation = full[len(prompt):] if full.startswith(prompt) else full
99
+
100
+ # # Prepare response in the shape expected by Inference Endpoints
101
+ # # The “predictions” key is often used (the default inference service expects it)
102
+ # return {
103
+ # "predictions": [full],
104
+ # "continuations": [continuation],
105
+ # }
106
+
107
+
108
+ # # For local testing (not used in production)
109
+ # if __name__ == "__main__":
110
+ # # Quick local test
111
+ # h = EndpointHandler(model_dir=".")
112
+ # resp = h({"inputs": "Once upon a time", "parameters": {"max_new_tokens": 20}})
113
+ # print("Response:", resp)
114
+
115
+ from typing import Any, Dict, List, Union
116
+
117
+ import torch
118
+
119
+ from huggingface_inference_toolkit.logging import logger
120
 
121
+ from unsloth import FastLanguageModel
122
 
123
+ from peft import PeftModel
124
+
125
+ Prompt = Union[str, List[Dict[str, str]]]
126
+
127
+
128
  class EndpointHandler:
129
+
130
  """
131
+
132
  Custom handler for Hugging Face Inference Endpoints.
133
+
134
+ Loads an Unsloth 4-bit base and attaches a LoRA adapter.
135
+
136
  """
137
+
138
+ def __init__(self, model_dir: str, **_: Any):
139
 
 
140
  """
141
+
142
+ Called once at startup. `model_dir` is the downloaded repo path.
143
+
144
  """
145
+
146
  logger.info(f"Initializing EndpointHandler with model_dir = {model_dir}")
147
+
148
+ # 1) Load Unsloth 4-bit base
149
+
150
+ base_model_name = "unsloth/gemma-3-4b-it-unsloth-bnb-4bit"
151
+
152
+ model, tokenizer = FastLanguageModel.from_pretrained(
153
+
154
+ model_name = base_model_name,
155
+
156
+ max_seq_length = 2048,
157
+
158
+ dtype = torch.float16,
159
+
160
+ load_in_4bit = True,
161
 
 
 
 
 
 
 
 
 
 
 
162
  )
163
+
164
+ # 2) Attach LoRA adapter
165
+
166
+ lora_repo = "Ephraimmm/PIDGIN_gemma-3"
167
+
168
+ model = PeftModel.from_pretrained(model, lora_repo) # use default adapter name
169
+
170
+ FastLanguageModel.for_inference(model) # optimize for generation
171
+
172
+ # 3) Finalize
173
+
174
+ self.model = model.eval()
175
+
176
+ self.tokenizer = tokenizer
177
+
178
+ self.device = getattr(self.model, "device", torch.device("cuda" if torch.cuda.is_available() else "cpu"))
179
+
180
+ logger.info(f"Model ready. Device: {self.device}, EOS: {self.tokenizer.eos_token_id}")
181
+
182
+ def _build_input_ids(self, prompt: Prompt):
183
+
184
+ """
185
+
186
+ Accepts either a single string, or OpenAI-style chat messages:
 
187
 
188
+ [{"role":"system|user|assistant","content":"..."}]
189
+
190
+ """
191
+
192
+ if isinstance(prompt, list):
193
+
194
+ # If tokenizer has a chat template, use it.
195
+
196
+ if hasattr(self.tokenizer, "apply_chat_template"):
197
+
198
+ text = self.tokenizer.apply_chat_template(
199
+
200
+ prompt, tokenize=False, add_generation_prompt=True
201
+
202
+ )
203
+
204
+ else:
205
+
206
+ # Fallback: naive concat
207
+
208
+ text = "\n".join(f"{m.get('role','user')}: {m.get('content','')}" for m in prompt) + "\nassistant:"
209
+
210
+ else:
211
+
212
+ text = prompt
213
+
214
+ return self.tokenizer(text, return_tensors="pt").to(self.device), text
215
+
216
  def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
217
+
218
  """
219
+
220
+ Called per request. Expects {"inputs": <str|messages>, "parameters": {...}}.
221
+
222
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
+ logger.info(f"EndpointHandler received data keys: {list(data.keys())}")
225
+
226
+ if "inputs" not in data:
227
+
228
+ raise ValueError("Request JSON must contain an `inputs` field (str or chat messages).")
229
+
230
+ prompt: Prompt = data["inputs"]
231
+
232
+ params = data.get("parameters", {}) or {}
233
+
234
+ max_new_tokens = int(params.get("max_new_tokens", 128))
235
+
236
+ temperature = float(params.get("temperature", 0.7))
237
+
238
+ top_k = int(params.get("top_k", 50))
239
+
240
+ top_p = float(params.get("top_p", 0.95))
241
+
242
+ do_sample = bool(params.get("do_sample", True))
243
+
244
+ repetition_penalty = float(params.get("repetition_penalty", 1.1))
245
+
246
+ eos_token_id = params.get("eos_token_id", self.tokenizer.eos_token_id)
247
+
248
+ inputs, rendered_prompt = self._build_input_ids(prompt)
249
+
250
+ with torch.no_grad():
251
 
252
+ output_ids = self.model.generate(
 
253
 
254
+ **inputs,
255
+
256
+ max_new_tokens=max_new_tokens,
257
+
258
+ temperature=temperature,
259
+
260
+ top_k=top_k,
261
+
262
+ top_p=top_p,
263
+
264
+ do_sample=do_sample,
265
+
266
+ repetition_penalty=repetition_penalty,
267
+
268
+ eos_token_id=eos_token_id,
269
+
270
+ )
271
+
272
+ full_text = self.tokenizer.decode(output_ids[0], skip_special_tokens=True)
273
+
274
+ # Best-effort continuation extraction
275
+
276
+ continuation = full_text[len(rendered_prompt):] if isinstance(prompt, str) and full_text.startswith(rendered_prompt) else full_text
277
+
278
  return {
279
+
280
+ "predictions": [full_text],
281
+
282
  "continuations": [continuation],
 
283
 
284
+ "usage": {
285
+
286
+ "prompt_tokens": int(inputs["input_ids"].shape[-1]),
287
+
288
+ "generated_tokens": int((output_ids.shape[-1] - inputs["input_ids"].shape[-1])),
289
+
290
+ },
291
+
292
+ }
293
+
294
+
295
+ # Local quick test
296
 
 
297
  if __name__ == "__main__":
298
+
299
  h = EndpointHandler(model_dir=".")
300
+
301
+ resp = h({
302
+
303
+ "inputs": "Write in Nigerian Pidgin: How you dey?",
304
+
305
+ "parameters": {"max_new_tokens": 40}
306
+
307
+ })
308
+
309
  print("Response:", resp)
310
+
311
+