kgrabko commited on
Commit
d5fe266
·
verified ·
1 Parent(s): 3cd8a45

Upload chatbot_gpt2.py

Browse files
Files changed (1) hide show
  1. chatbot_gpt2.py +157 -0
chatbot_gpt2.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from transformers import GPT2TokenizerFast
4
+ from gpt_pytorch import GPTPyTorch # Using the same import as in fine_tune.py
5
+ import os
6
+ from pathlib import Path
7
+
8
+ # ============================= GENERATION SETTINGS =============================
9
+ # Temperature: Lower = more conservative and predictable answers.
10
+ # Start with 0.7. Increase to 0.8 if the model starts repeating itself.
11
+ TEMPERATURE = 0.7
12
+
13
+ # Top-K: Limits sampling to the K most likely tokens.
14
+ # Start with 50. Increase if responses feel too boring/repetitive.
15
+ TOP_K = 50
16
+
17
+ # Max Length: Maximum number of tokens to generate in one go
18
+ MAX_LENGTH = 120
19
+
20
+ # ============================= PATHS =============================
21
+ # LAST_TRAINED_PATH = Path("models/gpt_last_trained.pt")
22
+ LAST_TRAINED_PATH = Path("build/fine_tuning_output/epoch49/gpt_finetuned.pt")
23
+ # FINAL_OUTPUT_DIR = Path("build/fine_tuning_output/final")
24
+ FINAL_OUTPUT_DIR = Path("build/fine_tuning_output/epoch49/gpt_finetuned.pt")
25
+ MODEL_SAVE_NAME = "gpt_finetuned.pt"
26
+
27
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
28
+
29
+ # ============================= Chatbot CLASS =============================
30
+ class Chatbot:
31
+ def __init__(self, model_path):
32
+ # 1. Tokenizer
33
+ print("Loading standard tokenizer (gpt2)...")
34
+ self.tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
35
+ self.tokenizer.pad_token = self.tokenizer.eos_token
36
+
37
+ #2. Model
38
+ print("Initializing model...")
39
+ self.model = GPTPyTorch().to(device)
40
+ self.model.eval()
41
+
42
+ # Look for the latest weights: first check final folder, then last_trained
43
+ load_path = None
44
+ if (FINAL_OUTPUT_DIR / MODEL_SAVE_NAME).exists():
45
+ load_path = FINAL_OUTPUT_DIR / MODEL_SAVE_NAME
46
+ print(f"Weights from Epoch 50 found. Loading and moving to {device}...")
47
+ elif model_path.exists():
48
+ load_path = model_path
49
+ print(f"Loading weights from {load_path} and moving to {device}...")
50
+
51
+ if load_path:
52
+ self.model.load_state_dict(torch.load(load_path, map_location=device))
53
+ else:
54
+ print("Warning: No trained weights found. Using randomly initialized model.")
55
+
56
+ print(f"Model successfully loaded on {device} and ready for chat!")
57
+
58
+ def generate_response(self, prompt, max_length=MAX_LENGTH, temperature=TEMPERATURE, top_k=TOP_K):
59
+ # Tokenize input
60
+ input_ids = self.tokenizer.encode(prompt, return_tensors='pt').to(device)
61
+
62
+ # Generation loop
63
+ with torch.no_grad():
64
+ for _ in range(max_length):
65
+ # Forward pass through the model
66
+ logits, _ = self.model(input_ids)
67
+
68
+ # Take logits only for the last token
69
+ next_token_logits = logits[:, -1, :]
70
+
71
+ # Apply temperature
72
+ next_token_logits = next_token_logits / temperature
73
+
74
+ # Apply Top-K sampling
75
+ if top_k > 0:
76
+ # Keep only the top-k most likely tokens
77
+ values, indices = torch.topk(next_token_logits, top_k)
78
+ # Zero out everything else (set to -inf)
79
+ next_token_logits = torch.full_like(next_token_logits, float('-inf'))
80
+ next_token_logits.scatter_(1, indices, values)
81
+
82
+ # Convert to probabilities and sample the next token
83
+ probabilities = F.softmax(next_token_logits, dim=-1)
84
+ next_token = torch.multinomial(probabilities, num_samples=1)
85
+
86
+ # Append generated token to the sequence
87
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
88
+
89
+ # Stop if end-of-utterance (__eou__) or EOS token is generated
90
+ generated_token = self.tokenizer.decode(next_token.squeeze().item())
91
+ if "__eou__" in generated_token or next_token.squeeze().item() == self.tokenizer.eos_token_id:
92
+ break
93
+
94
+ # Decode the full generated sequence
95
+ output = self.tokenizer.decode(input_ids.squeeze().tolist())
96
+
97
+ # Remove the original prompt from the output
98
+ response = output[len(prompt):].strip()
99
+
100
+ # Clean up any leftover end-of-utterance tokens
101
+ response = response.replace("__eou__", "").strip()
102
+
103
+ return response
104
+
105
+
106
+ def main():
107
+ # Fix for modifying globals inside the function
108
+ global TEMPERATURE, TOP_K
109
+
110
+ chatbot = Chatbot(LAST_TRAINED_PATH)
111
+
112
+ print("\n" + "="*60)
113
+ print(f"CHATBOT ACTIVATED (PPL ~2.6 / Temperature {TEMPERATURE} / Top-K {TOP_K})")
114
+ print("Type 'exit' or 'quit' to quit. Use 'set temp=0.x' or 'set k=N' to change settings.")
115
+ print("="*60 + "\n")
116
+
117
+ while True:
118
+ try:
119
+ user_input = input(">>> You: ")
120
+
121
+ if user_input.lower() in ['quit', 'exit']:
122
+ print("Goodbye!")
123
+ break
124
+
125
+ # Settings commands
126
+ if user_input.lower().startswith('set temp='):
127
+ try:
128
+ TEMPERATURE = float(user_input.split('=')[1].strip())
129
+ print(f"Temperature updated to {TEMPERATURE}")
130
+ continue
131
+ except ValueError:
132
+ print("Invalid temperature. Use format: set temp=0.7")
133
+ continue
134
+
135
+ if user_input.lower().startswith('set k='):
136
+ try:
137
+ TOP_K = int(user_input.split('=')[1].strip())
138
+ print(f"Top-K updated to {TOP_K}")
139
+ continue
140
+ except ValueError:
141
+ print("Invalid value. Use format: set k=50")
142
+ continue
143
+
144
+ print("...Generating...")
145
+ response = chatbot.generate_response(user_input)
146
+ print(f"Model: {response}\n")
147
+
148
+ except KeyboardInterrupt:
149
+ print("\nGoodbye!")
150
+ break
151
+ except Exception as e:
152
+ print(f"An error occurred: {e}")
153
+ break
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()