algorythmtechnologies commited on
Commit
009ab0e
·
verified ·
1 Parent(s): 218e6fa

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +56 -0
handler.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
+
5
+ class EndpointHandler():
6
+ def __init__(self, path=""):
7
+ """
8
+ Initialize the model and tokenizer using the local path.
9
+ Uses Zenith Coder v1.1 custom code (modeling_deepseek.py, configuration_deepseek.py, tokenization_deepseek_fast.py).
10
+ """
11
+ self.tokenizer = AutoTokenizer.from_pretrained(
12
+ path, trust_remote_code=True
13
+ )
14
+ self.model = AutoModelForCausalLM.from_pretrained(
15
+ path,
16
+ trust_remote_code=True,
17
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
18
+ device_map="auto"
19
+ )
20
+ self.model.eval()
21
+
22
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
23
+ """
24
+ Accepts a dictionary with the prompt and optional `max_new_tokens`.
25
+ Returns generated text.
26
+ """
27
+ prompt = data.get("inputs") or data.get("prompt")
28
+ if not prompt or not isinstance(prompt, str):
29
+ return [{"error": "No valid input prompt provided."}]
30
+
31
+ max_new_tokens = int(data.get("max_new_tokens", 256))
32
+ temperature = float(data.get("temperature", 1.0))
33
+ top_p = float(data.get("top_p", 0.95))
34
+ top_k = int(data.get("top_k", 50))
35
+
36
+ input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids
37
+ if torch.cuda.is_available():
38
+ input_ids = input_ids.cuda()
39
+
40
+ with torch.no_grad():
41
+ generated_ids = self.model.generate(
42
+ input_ids,
43
+ do_sample=True,
44
+ max_new_tokens=max_new_tokens,
45
+ temperature=temperature,
46
+ top_p=top_p,
47
+ top_k=top_k,
48
+ pad_token_id=self.tokenizer.pad_token_id,
49
+ eos_token_id=self.tokenizer.eos_token_id
50
+ )
51
+ # Skip the prompt part
52
+ gen_text = self.tokenizer.decode(
53
+ generated_ids[0][input_ids.shape[1]:],
54
+ skip_special_tokens=True
55
+ )
56
+ return [{"generated_text": gen_text}]