|
|
|
import torch |
|
from transformers import AutoTokenizer |
|
from evo_model import EvoDecoderModel |
|
from search_utils import web_search |
|
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") |
|
vocab_size = tokenizer.vocab_size |
|
|
|
model = EvoDecoderModel(vocab_size=vocab_size).to(device) |
|
model.load_state_dict(torch.load("evo_decoder_model.pt", map_location=device)) |
|
model.eval() |
|
|
|
def generate_response(prompt, use_web=False, max_length=100, top_k=40): |
|
if use_web: |
|
context = web_search(prompt) |
|
prompt = f"Relevant Info: {context}\nUser: {prompt}\nAssistant:" |
|
else: |
|
prompt = f"User: {prompt}\nAssistant:" |
|
|
|
input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device) |
|
|
|
for _ in range(max_length): |
|
with torch.no_grad(): |
|
logits = model(input_ids) |
|
next_token_logits = logits[:, -1, :] |
|
top_k_probs, top_k_indices = torch.topk(next_token_logits, top_k) |
|
probs = torch.softmax(top_k_probs, dim=-1) |
|
next_token = top_k_indices[0, torch.multinomial(probs, 1)] |
|
|
|
next_token = next_token.unsqueeze(0).unsqueeze(0) |
|
input_ids = torch.cat([input_ids, next_token], dim=1) |
|
|
|
if next_token.item() == tokenizer.eos_token_id: |
|
break |
|
|
|
output = tokenizer.decode(input_ids[0], skip_special_tokens=True) |
|
return output.split("Assistant:")[-1].strip() |
|
|