File size: 11,494 Bytes
93783dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
"""
GPT-300M Chatbot Interface
============================
Interactive terminal chatbot using a trained GPT-300M model.

Usage:
  python chat.py --checkpoint ./checkpoints/best_model.pt

  # Or with custom generation parameters:
  python chat.py --checkpoint ./checkpoints/best_model.pt \
                 --temperature 0.8 --top_k 40 --max_tokens 256
"""

import argparse
import sys
import time
from typing import List, Dict, Optional

import torch

from config import GPT300MConfig
from model import GPT300M
from tokenizer import BPETokenizer


class ChatBot:
    """
    Interactive chatbot powered by GPT-300M.

    Maintains conversation history, handles tokenization/detokenization,
    and performs autoregressive generation with KV-caching.
    """

    def __init__(
        self,
        model: GPT300M,
        tokenizer: BPETokenizer,
        config: GPT300MConfig,
        device: str = "auto",
    ):
        self.config = config
        self.tokenizer = tokenizer

        # Device
        if device == "auto":
            if torch.cuda.is_available():
                self.device = "cuda"
            elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
                self.device = "mps"
            else:
                self.device = "cpu"
        else:
            self.device = device

        self.model = model.to(self.device)
        self.model.eval()

        # Conversation state
        self.history: List[Dict[str, str]] = []
        self.system_prompt = config.system_prompt

    def set_system_prompt(self, prompt: str):
        """Set the system prompt for the conversation."""
        self.system_prompt = prompt

    def reset(self):
        """Clear conversation history."""
        self.history = []
        print("\n✦ Conversation reset.\n")

    def chat(
        self,
        user_message: str,
        temperature: Optional[float] = None,
        top_k: Optional[int] = None,
        top_p: Optional[float] = None,
        max_new_tokens: Optional[int] = None,
        stream: bool = True,
    ) -> str:
        """
        Send a message and get a response.

        Args:
            user_message: The user's input
            temperature: Override sampling temperature
            top_k: Override top-k
            top_p: Override top-p
            max_new_tokens: Override max generation length
            stream: Whether to stream tokens to stdout

        Returns:
            The assistant's response text
        """
        temp = temperature or self.config.temperature
        k = top_k or self.config.top_k
        p = top_p or self.config.top_p
        max_tokens = max_new_tokens or self.config.max_new_tokens

        # Build conversation messages
        messages = []
        if self.system_prompt:
            messages.append({"role": "system", "content": self.system_prompt})
        messages.extend(self.history)
        messages.append({"role": "user", "content": user_message})

        # Tokenize
        input_ids = self.tokenizer.encode_chat(messages, add_generation_prompt=True)
        input_tensor = torch.tensor([input_ids], dtype=torch.long, device=self.device)

        # Check sequence length
        if input_tensor.size(1) > self.config.max_seq_len - max_tokens:
            # Truncate history if needed
            while (
                len(self.history) > 0
                and input_tensor.size(1) > self.config.max_seq_len - max_tokens
            ):
                self.history.pop(0)
                messages = []
                if self.system_prompt:
                    messages.append({"role": "system", "content": self.system_prompt})
                messages.extend(self.history)
                messages.append({"role": "user", "content": user_message})
                input_ids = self.tokenizer.encode_chat(messages, add_generation_prompt=True)
                input_tensor = torch.tensor([input_ids], dtype=torch.long, device=self.device)

        # Generate
        t0 = time.time()

        if stream:
            response_text = self._generate_streaming(
                input_tensor, max_tokens, temp, k, p
            )
        else:
            with torch.no_grad():
                output_ids = self.model.generate(
                    input_tensor,
                    max_new_tokens=max_tokens,
                    temperature=temp,
                    top_k=k,
                    top_p=p,
                    repetition_penalty=self.config.repetition_penalty,
                    eos_token_id=self.tokenizer.special_tokens.get("<|end|>"),
                )
            # Decode only the new tokens
            new_ids = output_ids[0, input_tensor.size(1):].tolist()
            response_text = self.tokenizer.decode(new_ids, skip_special=True)

        dt = time.time() - t0
        n_tokens = len(self.tokenizer.encode(response_text))

        # Update history
        self.history.append({"role": "user", "content": user_message})
        self.history.append({"role": "assistant", "content": response_text.strip()})

        if stream:
            print(f"\n  [{n_tokens} tokens, {dt:.1f}s, {n_tokens/dt:.1f} tok/s]")

        return response_text.strip()

    @torch.no_grad()
    def _generate_streaming(
        self,
        input_ids: torch.Tensor,
        max_new_tokens: int,
        temperature: float,
        top_k: int,
        top_p: float,
    ) -> str:
        """Generate tokens one at a time, printing as we go."""
        import torch.nn.functional as F

        model = self.model
        model.eval()

        eos_id = self.tokenizer.special_tokens.get("<|end|>")
        end_id = self.tokenizer.special_tokens.get("<eos>")

        # Initial forward pass
        logits, _, kv_caches = model(input_ids, use_cache=True)

        generated_ids = []
        buffer = b""

        for step in range(max_new_tokens):
            next_logits = logits[:, -1, :]

            # Repetition penalty
            if self.config.repetition_penalty != 1.0:
                for tid in set(generated_ids):
                    if next_logits[0, tid] > 0:
                        next_logits[0, tid] /= self.config.repetition_penalty
                    else:
                        next_logits[0, tid] *= self.config.repetition_penalty

            # Temperature + sampling
            if temperature > 0:
                next_logits = next_logits / temperature
                if top_k > 0:
                    topk_vals, _ = torch.topk(next_logits, min(top_k, next_logits.size(-1)))
                    next_logits[next_logits < topk_vals[:, -1:]] = float("-inf")
                probs = F.softmax(next_logits, dim=-1)
                next_token = torch.multinomial(probs, num_samples=1)
            else:
                next_token = next_logits.argmax(dim=-1, keepdim=True)

            token_id = next_token.item()

            # Check for stop tokens
            if token_id in (eos_id, end_id):
                break

            generated_ids.append(token_id)

            # Decode and print the new token
            token_bytes = self.tokenizer.vocab.get(token_id, b"")
            buffer += token_bytes
            try:
                text = buffer.decode("utf-8")
                sys.stdout.write(text)
                sys.stdout.flush()
                buffer = b""
            except UnicodeDecodeError:
                pass  # Wait for more bytes

            # Forward with KV-cache
            position_offset = input_ids.size(1) + step
            logits, _, kv_caches = model(
                next_token,
                kv_caches=kv_caches,
                use_cache=True,
                position_offset=position_offset,
            )

        # Flush remaining buffer
        if buffer:
            text = buffer.decode("utf-8", errors="replace")
            sys.stdout.write(text)
            sys.stdout.flush()

        return self.tokenizer.decode(generated_ids, skip_special=True)


def interactive_chat(chatbot: ChatBot):
    """Run an interactive chat session in the terminal."""
    print("=" * 60)
    print("  GPT-300M Chatbot")
    print("  Type 'quit' to exit, 'reset' to clear history")
    print("  Type 'system: <prompt>' to set system prompt")
    print("=" * 60)
    print()

    while True:
        try:
            user_input = input("You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\n\nGoodbye!")
            break

        if not user_input:
            continue

        if user_input.lower() == "quit":
            print("Goodbye!")
            break

        if user_input.lower() == "reset":
            chatbot.reset()
            continue

        if user_input.lower().startswith("system:"):
            prompt = user_input[7:].strip()
            chatbot.set_system_prompt(prompt)
            print(f"✦ System prompt set: {prompt}\n")
            continue

        print("\nAssistant: ", end="", flush=True)
        chatbot.chat(user_input, stream=True)
        print()


def load_model(checkpoint_path: str, device: str = "auto"):
    """Load a trained model from checkpoint."""
    checkpoint = torch.load(checkpoint_path, map_location="cpu")

    # Reconstruct config
    config = GPT300MConfig(**checkpoint["config"])

    # Load model
    model = GPT300M(config)
    model.load_state_dict(checkpoint["model_state_dict"])

    # Load tokenizer
    tokenizer_path = os.path.join(
        os.path.dirname(checkpoint_path), "tokenizer.json"
    )
    if os.path.exists(tokenizer_path):
        tokenizer = BPETokenizer.load(tokenizer_path)
    else:
        tokenizer = BPETokenizer(vocab_size=config.vocab_size)
        print("Warning: Tokenizer not found, using untrained tokenizer")

    return model, tokenizer, config


# ═══════════════════════════════════════════════════════════════════════
#  MAIN
# ═══════════════════════════════════════════════════════════════════════

if __name__ == "__main__":
    import os

    parser = argparse.ArgumentParser(description="GPT-300M Chatbot")
    parser.add_argument("--checkpoint", type=str, default=None,
                        help="Path to model checkpoint")
    parser.add_argument("--temperature", type=float, default=0.7)
    parser.add_argument("--top_k", type=int, default=50)
    parser.add_argument("--top_p", type=float, default=0.9)
    parser.add_argument("--max_tokens", type=int, default=512)
    parser.add_argument("--device", type=str, default="auto")
    args = parser.parse_args()

    if args.checkpoint and os.path.exists(args.checkpoint):
        model, tokenizer, config = load_model(args.checkpoint, args.device)
    else:
        print("No checkpoint provided. Initializing random model for demo...")
        from config import gpt_tiny
        config = gpt_tiny()
        model = GPT300M(config)
        tokenizer = BPETokenizer(vocab_size=config.vocab_size)
        # Quick train on minimal data
        tokenizer.train("Hello! How are you? I am fine. " * 100)

    config.temperature = args.temperature
    config.top_k = args.top_k
    config.top_p = args.top_p
    config.max_new_tokens = args.max_tokens

    chatbot = ChatBot(model, tokenizer, config, device=args.device)
    interactive_chat(chatbot)