git-excited commited on
Commit
ba021f2
·
1 Parent(s): 2ba72c1

Update handler to return meaningful words

Browse files
Files changed (1) hide show
  1. handler.py +35 -0
handler.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
+ import re
5
+
6
+ class EndpointHandler:
7
+ def __init__(self, path=""):
8
+ self.model = AutoModelForCausalLM.from_pretrained("EleutherAI/pythia-410m")
9
+ self.tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-410m")
10
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ self.model.to(self.device)
12
+
13
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
14
+ inputs = data.pop("inputs", data).strip()
15
+ input_tokens = self.tokenizer(inputs, return_tensors="pt").to(self.device)
16
+ with torch.no_grad():
17
+ outputs = self.model(**input_tokens)
18
+ logits = outputs.logits[:, -1, :]
19
+ probs = torch.softmax(logits, dim=-1)
20
+ top_k = torch.topk(probs, k=100) # Check top 100 tokens
21
+ top_predictions = []
22
+ input_ids = input_tokens["input_ids"]
23
+ for idx, prob in zip(top_k.indices[0], top_k.values[0]):
24
+ # Append token to input and decode
25
+ next_token_id = idx.item()
26
+ test_ids = torch.cat([input_ids, torch.tensor([[next_token_id]], device=self.device)], dim=-1)
27
+ text = self.tokenizer.decode(test_ids[0], skip_special_tokens=True).strip()
28
+ # Extract last word
29
+ last_word = text.split()[-1]
30
+ # Filter for meaningful words (3+ letters, alphabetic)
31
+ if re.match(r"^[a-zA-Z]{3,}$", last_word) and last_word not in [p["text"] for p in top_predictions]:
32
+ top_predictions.append({"text": last_word, "probability": prob.item()})
33
+ if len(top_predictions) >= 5:
34
+ break
35
+ return top_predictions if top_predictions else [{"text": "No valid words found", "probability": 0.0}]