|
|
import torch |
|
|
import torch.nn.functional as F |
|
|
from evo_model import EvoDecoder |
|
|
from transformers import GPT2Tokenizer |
|
|
|
|
|
|
|
|
tokenizer = GPT2Tokenizer.from_pretrained("gpt2") |
|
|
|
|
|
|
|
|
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() |
|
|
|