Ephraimmm commited on
Commit
42b6b68
·
verified ·
1 Parent(s): abf7000

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +6 -118
handler.py CHANGED
@@ -1,117 +1,5 @@
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
@@ -231,11 +119,11 @@ class EndpointHandler:
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
 
@@ -277,9 +165,9 @@ class EndpointHandler:
277
 
278
  return {
279
 
280
- "predictions": [full_text],
281
 
282
- "continuations": [continuation],
283
 
284
  "usage": {
285
 
@@ -302,7 +190,7 @@ if __name__ == "__main__":
302
 
303
  "inputs": "Write in Nigerian Pidgin: How you dey?",
304
 
305
- "parameters": {"max_new_tokens": 40}
306
 
307
  })
308
 
 
1
  # handler.py
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  from typing import Any, Dict, List, Union
4
 
5
  import torch
 
119
 
120
  params = data.get("parameters", {}) or {}
121
 
122
+ max_new_tokens = int(params.get("max_new_tokens", 64))
123
 
124
+ temperature = float(params.get("temperature", 1))
125
 
126
+ top_k = int(params.get("top_k", 64))
127
 
128
  top_p = float(params.get("top_p", 0.95))
129
 
 
165
 
166
  return {
167
 
168
+ "reply": [full_text],
169
 
170
+ # "continuations": [continuation],
171
 
172
  "usage": {
173
 
 
190
 
191
  "inputs": "Write in Nigerian Pidgin: How you dey?",
192
 
193
+ "parameters": {"max_new_tokens": 64}
194
 
195
  })
196