File size: 1,604 Bytes
ca6258b
1c98e83
8469bea
1c98e83
ca6258b
1c98e83
 
 
ca6258b
8469bea
1c98e83
 
 
 
 
 
ca6258b
 
 
8469bea
ec74c4d
ca6258b
8469bea
ca6258b
ec74c4d
1c98e83
 
 
 
8469bea
ca6258b
 
8469bea
 
ca6258b
1c98e83
8469bea
1c98e83
8469bea
1c98e83
 
 
ca6258b
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
33
34
35
36
37
38
39
40
41
42
43
44
# generate.py — EvoDecoder response generation with optional DuckDuckGo RAG
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")

# Load tokenizer and model
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):
    # Augment with web context if enabled
    context = ""
    if use_web:
        web_context = web_search(prompt)
        context += f"Relevant Info: {web_context}\n"

    input_text = context + f"User: {prompt}\nAssistant:"
    input_ids = tokenizer.encode(input_text, 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 sampling
            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).item()].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()