Update generate.py
Browse files- generate.py +37 -0
generate.py
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# generate.py — Loads EvoDecoder model and generates responses
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoTokenizer
|
| 4 |
+
from evo_model import EvoDecoderModel
|
| 5 |
+
|
| 6 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 7 |
+
|
| 8 |
+
# Load tokenizer and model
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
| 10 |
+
vocab_size = tokenizer.vocab_size
|
| 11 |
+
|
| 12 |
+
model = EvoDecoderModel(vocab_size=vocab_size).to(device)
|
| 13 |
+
model.load_state_dict(torch.load("evo_decoder_model.pt", map_location=device))
|
| 14 |
+
model.eval()
|
| 15 |
+
|
| 16 |
+
def generate_response(prompt, max_length=100, top_k=40):
|
| 17 |
+
input_text = f"User: {prompt}\nAssistant:"
|
| 18 |
+
input_ids = tokenizer.encode(input_text, return_tensors="pt").to(device)
|
| 19 |
+
|
| 20 |
+
for _ in range(max_length):
|
| 21 |
+
with torch.no_grad():
|
| 22 |
+
logits = model(input_ids)
|
| 23 |
+
next_token_logits = logits[:, -1, :]
|
| 24 |
+
|
| 25 |
+
# Top-k sampling
|
| 26 |
+
top_k_probs, top_k_indices = torch.topk(next_token_logits, top_k)
|
| 27 |
+
probs = torch.softmax(top_k_probs, dim=-1)
|
| 28 |
+
next_token = top_k_indices[torch.multinomial(probs, 1)]
|
| 29 |
+
|
| 30 |
+
input_ids = torch.cat([input_ids, next_token.unsqueeze(0)], dim=1)
|
| 31 |
+
|
| 32 |
+
# Optional EOS stop condition
|
| 33 |
+
if next_token.item() == tokenizer.eos_token_id:
|
| 34 |
+
break
|
| 35 |
+
|
| 36 |
+
output = tokenizer.decode(input_ids[0], skip_special_tokens=True)
|
| 37 |
+
return output.split("Assistant:")[-1].strip()
|