HemanM commited on
Commit
e94ab3b
·
verified ·
1 Parent(s): f4fcc11

Create evo_plugin_example.py

Browse files
Files changed (1) hide show
  1. evo_plugin_example.py +48 -0
evo_plugin_example.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ evo_plugin_example.py
3
+ Step 8: Example text generator plugin (for immediate testing).
4
+ (Objective)
5
+ - Provides the same interface your real Evo plugin will expose.
6
+ - Uses a tiny HF model (distilgpt2) so you can test generative mode now.
7
+ - Replace this later with `evo_plugin.py` wrapping your EvoDecoder/Evo QA.
8
+
9
+ Real Evo instructions:
10
+ - Create a file `evo_plugin.py` with a `load_model()` that returns an object
11
+ exposing `generate(prompt: str, max_new_tokens: int, temperature: float) -> str`.
12
+ - The app will auto-prefer `evo_plugin.py` if it exists.
13
+ """
14
+
15
+ import torch
16
+ from transformers import AutoTokenizer, AutoModelForCausalLM
17
+
18
+
19
+ class _HFGenerator:
20
+ def __init__(self, model_name: str = "distilgpt2"):
21
+ self.device = torch.device("cpu")
22
+ self.tok = AutoTokenizer.from_pretrained(model_name)
23
+ self.model = AutoModelForCausalLM.from_pretrained(model_name).to(self.device)
24
+ # GPT-2 models have no pad token; set to eos to avoid warnings
25
+ if self.tok.pad_token_id is None and self.tok.eos_token_id is not None:
26
+ self.tok.pad_token_id = self.tok.eos_token_id
27
+
28
+ @torch.no_grad()
29
+ def generate(self, prompt: str, max_new_tokens: int = 200, temperature: float = 0.4) -> str:
30
+ inputs = self.tok(prompt, return_tensors="pt").to(self.device)
31
+ out = self.model.generate(
32
+ **inputs,
33
+ max_new_tokens=int(max_new_tokens),
34
+ do_sample=temperature > 0.0,
35
+ temperature=float(max(0.01, temperature)),
36
+ top_p=0.95,
37
+ pad_token_id=self.tok.pad_token_id,
38
+ )
39
+ text = self.tok.decode(out[0], skip_special_tokens=True)
40
+ # Return only the completion after the prompt to reduce echo
41
+ return text[len(prompt):].strip()
42
+
43
+
44
+ def load_model():
45
+ """
46
+ (Objective) Entry-point used by evo_inference.py.
47
+ """
48
+ return _HFGenerator()