File size: 1,106 Bytes
1c98e83 b28676e ccae0a9 1c98e83 ccae0a9 1c98e83 b28676e ccae0a9 5259900 b28676e 1c98e83 b28676e d7a4aba b28676e 7dc4300 b28676e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import torch
import torch.nn.functional as F
from evo_model import EvoDecoder
from transformers import GPT2Tokenizer
# Load tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
# Load trained model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = EvoDecoder(vocab_size=tokenizer.vocab_size, d_model=512, nhead=8, num_layers=6).to(device)
model.load_state_dict(torch.load("evo_decoder.pt", map_location=device))
model.eval()
@torch.no_grad()
def generate_response(prompt, max_length=50, temperature=1.0):
model.eval()
input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
for _ in range(max_length):
logits = model(input_ids)
logits = logits[:, -1, :] / temperature
probs = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
input_ids = torch.cat((input_ids, next_token), dim=1)
if next_token.item() == tokenizer.eos_token_id:
break
output = tokenizer.decode(input_ids.squeeze(), skip_special_tokens=True)
return output[len(prompt):].strip()
|