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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#!/usr/bin/env python3
# Copyright (C) 2024 Louis Chua Bean Chong
#
# This file is part of OpenLLM.
#
# OpenLLM is dual-licensed:
# 1. For open source use: GNU General Public License v3.0
# 2. For commercial use: Commercial License (contact for details)
#
# See LICENSE and docs/LICENSES.md for full license information.

"""
Model Architecture Testing and Validation Script

This script provides comprehensive testing and validation for the GPT model architecture.
It helps verify that the model is correctly implemented and can run on your hardware.

FEATURES:
- Model initialization testing
- Forward pass validation
- Memory usage analysis
- Tokenizer integration testing
- Performance benchmarking
- Hardware compatibility checks

Usage:
    python core/src/test_model.py --model_size medium
    python core/src/test_model.py --model_size small --test_generation
    python core/src/test_model.py --all_sizes --benchmark

Requirements:
    - torch
    - sentencepiece (for tokenizer integration)
    - Our trained tokenizer in data/tokenizer/

Author: Louis Chua Bean Chong
License: GPLv3
"""

import argparse
import json
import os
import time
import traceback
from typing import Dict, List

import torch

# Import our model architecture
try:
    from model import GPTModel, create_model
except ImportError:
    import sys

    sys.path.append(os.path.dirname(__file__))
    from model import GPTModel, create_model

# Import tokenizer if available
try:
    import sentencepiece as spm

    TOKENIZER_AVAILABLE = True
except ImportError:
    TOKENIZER_AVAILABLE = False
    print("Warning: SentencePiece not available. Tokenizer tests will be skipped.")


class ModelTester:
    """
    Comprehensive model testing class.

    Provides methods to test model initialization, forward passes, memory usage,
    and integration with the tokenizer.
    """

    def __init__(self, device: str = "auto"):
        """
        Initialize the model tester.

        Args:
            device: Device to use ("cpu", "cuda", or "auto")
        """
        if device == "auto":
            self.device = "cuda" if torch.cuda.is_available() else "cpu"
        else:
            self.device = device

        print("πŸ”§ Model Tester initialized")
        print(f"Device: {self.device}")
        print(f"PyTorch version: {torch.__version__}")

        # Try to load tokenizer
        self.tokenizer = None
        self.load_tokenizer()

    def load_tokenizer(self) -> None:
        """Load the trained SentencePiece tokenizer if available."""
        if not TOKENIZER_AVAILABLE:
            return

        tokenizer_path = "data/tokenizer/tokenizer.model"
        if os.path.exists(tokenizer_path):
            try:
                self.tokenizer = spm.SentencePieceProcessor()
                self.tokenizer.load(tokenizer_path)
                print(f"βœ“ Tokenizer loaded: {tokenizer_path}")
                print(f"  Vocabulary size: {self.tokenizer.vocab_size():,}")
            except Exception as e:
                print(f"⚠️  Failed to load tokenizer: {e}")
        else:
            print(f"⚠️  Tokenizer not found at {tokenizer_path}")

    def test_model_initialization(self, model_size: str = "medium") -> Dict:
        """
        Test model initialization and basic properties.

        Args:
            model_size: Size of model to test

        Returns:
            dict: Test results
        """
        print(f"\n🧠 Testing {model_size.upper()} model initialization...")

        try:
            # Create model
            start_time = time.time()
            model = create_model(model_size)
            init_time = time.time() - start_time

            # Move to device
            model = model.to(self.device)

            # Basic checks
            param_count = model.get_num_params()
            config = model.config

            print("βœ“ Model created successfully")
            print(f"  Parameters: {param_count:,}")
            print(f"  Layers: {config.n_layer}")
            print(f"  Heads: {config.n_head}")
            print(f"  Embedding dim: {config.n_embd}")
            print(f"  Block size: {config.block_size}")
            print(f"  Initialization time: {init_time:.2f}s")

            return {
                "success": True,
                "model_size": model_size,
                "parameters": param_count,
                "config": config.__dict__,
                "init_time": init_time,
                "device": str(next(model.parameters()).device),
            }

        except Exception as e:
            print(f"❌ Model initialization failed: {e}")
            traceback.print_exc()
            return {"success": False, "error": str(e)}

    def test_forward_pass(self, model: GPTModel, batch_size: int = 2, seq_len: int = 64) -> Dict:
        """
        Test model forward pass with synthetic data.

        Args:
            model: Model to test
            batch_size: Batch size for test
            seq_len: Sequence length for test

        Returns:
            dict: Test results
        """
        print(f"\nπŸ”„ Testing forward pass (batch={batch_size}, seq_len={seq_len})...")

        try:
            model.eval()

            # Create synthetic input
            x = torch.randint(0, model.config.vocab_size, (batch_size, seq_len))
            x = x.to(self.device)

            # Test inference mode
            start_time = time.time()
            with torch.no_grad():
                logits, _ = model(x)
            inference_time = time.time() - start_time

            # Test training mode with targets
            model.train()
            targets = torch.randint(0, model.config.vocab_size, (batch_size, seq_len))
            targets = targets.to(self.device)

            start_time = time.time()
            logits_train, loss = model(x, targets)
            train_time = time.time() - start_time

            print("βœ“ Forward pass successful")
            print(f"  Input shape: {x.shape}")
            print(f"  Output shape: {logits.shape}")
            print(f"  Loss: {loss.item():.4f}")
            print(f"  Inference time: {inference_time:.4f}s")
            print(f"  Training time: {train_time:.4f}s")

            return {
                "success": True,
                "input_shape": list(x.shape),
                "output_shape": list(logits.shape),
                "loss": loss.item(),
                "inference_time": inference_time,
                "training_time": train_time,
            }

        except Exception as e:
            print(f"❌ Forward pass failed: {e}")
            traceback.print_exc()
            return {"success": False, "error": str(e)}

    def test_memory_usage(self, model: GPTModel, batch_sizes: List[int] = [1, 2, 4]) -> Dict:
        """
        Test memory usage for different batch sizes.

        Args:
            model: Model to test
            batch_sizes: List of batch sizes to test

        Returns:
            dict: Memory usage results
        """
        print("\nπŸ’Ύ Testing memory usage...")

        results = {}

        for batch_size in batch_sizes:
            try:
                # Clear cache
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()

                # Get initial memory
                if torch.cuda.is_available():
                    initial_memory = torch.cuda.memory_allocated() / (1024**2)
                else:
                    initial_memory = 0

                # Forward pass
                seq_len = min(512, model.config.block_size)
                x = torch.randint(0, model.config.vocab_size, (batch_size, seq_len))
                x = x.to(self.device)

                with torch.no_grad():
                    logits, _ = model(x)

                # Get peak memory
                if torch.cuda.is_available():
                    peak_memory = torch.cuda.max_memory_allocated() / (1024**2)
                    memory_used = peak_memory - initial_memory
                else:
                    memory_used = model.estimate_memory_usage(batch_size, seq_len)[
                        "total_inference_mb"
                    ]

                results[f"batch_{batch_size}"] = {
                    "memory_mb": memory_used,
                    "memory_per_sample": memory_used / batch_size,
                }

                print(
                    f"  Batch size {batch_size}: {memory_used:.1f}MB ({memory_used/batch_size:.1f}MB per sample)"
                )

            except Exception as e:
                print(f"  Batch size {batch_size}: Failed - {e}")
                results[f"batch_{batch_size}"] = {"error": str(e)}

        return results

    def test_tokenizer_integration(self, model: GPTModel) -> Dict:
        """
        Test integration with the trained tokenizer.

        Args:
            model: Model to test

        Returns:
            dict: Integration test results
        """
        print("\nπŸ”€ Testing tokenizer integration...")

        if self.tokenizer is None:
            print("⚠️  No tokenizer available, skipping integration test")
            return {"success": False, "reason": "No tokenizer available"}

        try:
            # Test sentences
            test_sentences = [
                "The quick brown fox jumps over the lazy dog.",
                "Machine learning is transforming technology.",
                "GPT models use transformer architecture for language modeling.",
            ]

            results = []

            for sentence in test_sentences:
                # Tokenize
                tokens = self.tokenizer.encode(sentence)
                token_tensor = torch.tensor([tokens]).to(self.device)

                # Forward pass
                with torch.no_grad():
                    logits, _ = model(token_tensor)

                # Get predictions for next token
                next_token_logits = logits[0, -1, :]
                next_token_probs = torch.softmax(next_token_logits, dim=0)
                top5_tokens = torch.topk(next_token_probs, 5)

                # Decode top predictions
                top5_decoded = []
                for token_id in top5_tokens.indices:
                    try:
                        decoded = self.tokenizer.decode([token_id.item()])
                        prob = top5_tokens.values[len(top5_decoded)].item()
                        top5_decoded.append((decoded, prob))
                    except Exception:
                        top5_decoded.append(("<??>", 0.0))

                results.append(
                    {"input": sentence, "tokens": len(tokens), "top_predictions": top5_decoded}
                )

                print(f"βœ“ '{sentence[:30]}...' -> {len(tokens)} tokens")
                print(f"  Top prediction: '{top5_decoded[0][0]}' ({top5_decoded[0][1]:.3f})")

            return {
                "success": True,
                "vocab_size_match": self.tokenizer.vocab_size() == model.config.vocab_size,
                "test_results": results,
            }

        except Exception as e:
            print(f"❌ Tokenizer integration failed: {e}")
            traceback.print_exc()
            return {"success": False, "error": str(e)}

    def test_generation(self, model: GPTModel, prompt: str = "The future of AI") -> Dict:
        """
        Test text generation capabilities.

        Args:
            model: Model to test
            prompt: Starting prompt for generation

        Returns:
            dict: Generation test results
        """
        print("\n✍️  Testing text generation...")

        if self.tokenizer is None:
            print("⚠️  No tokenizer available, skipping generation test")
            return {"success": False, "reason": "No tokenizer available"}

        try:
            # Tokenize prompt
            tokens = self.tokenizer.encode(prompt)
            input_tensor = torch.tensor([tokens]).to(self.device)

            print(f"Prompt: '{prompt}'")
            print("Generating...")

            # Generate
            start_time = time.time()
            output = model.generate(input_tensor, max_new_tokens=50, temperature=0.8, top_k=50)
            generation_time = time.time() - start_time

            # Decode output
            generated_tokens = output[0].tolist()
            generated_text = self.tokenizer.decode(generated_tokens)

            print(f"βœ“ Generated text: '{generated_text}'")
            print(f"  Generation time: {generation_time:.2f}s")
            print(f"  Tokens per second: {50/generation_time:.1f}")

            return {
                "success": True,
                "prompt": prompt,
                "generated_text": generated_text,
                "generation_time": generation_time,
                "tokens_per_second": 50 / generation_time,
            }

        except Exception as e:
            print(f"❌ Text generation failed: {e}")
            traceback.print_exc()
            return {"success": False, "error": str(e)}

    def run_comprehensive_test(self, model_size: str = "medium") -> Dict:
        """
        Run all tests for a given model size.

        Args:
            model_size: Size of model to test

        Returns:
            dict: Complete test results
        """
        print(f"\nπŸ” Running comprehensive test for {model_size.upper()} model")
        print("=" * 60)

        results = {"model_size": model_size, "device": self.device}

        # Test 1: Model initialization
        init_result = self.test_model_initialization(model_size)
        results["initialization"] = init_result

        if not init_result["success"]:
            return results

        # Create model for remaining tests
        model = create_model(model_size).to(self.device)

        # Test 2: Forward pass
        results["forward_pass"] = self.test_forward_pass(model)

        # Test 3: Memory usage
        results["memory_usage"] = self.test_memory_usage(model)

        # Test 4: Tokenizer integration
        results["tokenizer_integration"] = self.test_tokenizer_integration(model)

        # Test 5: Text generation
        results["generation"] = self.test_generation(model)

        return results


def load_model_config(model_size: str) -> Dict:
    """Load model configuration from JSON file."""
    config_path = f"configs/{model_size}_model.json"
    if os.path.exists(config_path):
        with open(config_path, "r") as f:
            return json.load(f)
    return {}


def print_hardware_recommendations(model_size: str) -> None:
    """Print hardware recommendations for the given model size."""
    config = load_model_config(model_size)

    if config:
        print(f"\nπŸ’» Hardware Recommendations for {model_size.upper()} model:")
        print(f"  Parameters: {config.get('parameters', 'Unknown')}")
        print(f"  Recommended: {config.get('recommended_hardware', 'Unknown')}")

        if "memory_estimates" in config:
            mem = config["memory_estimates"]
            print(f"  Memory usage: ~{mem.get('parameters_mb', '?')}MB parameters")
            print(f"  Training: ~{mem.get('training_mb_per_sample', '?')}MB per sample")
            print(f"  Inference: ~{mem.get('inference_mb_per_sample', '?')}MB per sample")

        if "cpu_training_notes" in config:
            cpu_notes = config["cpu_training_notes"]
            if cpu_notes.get("feasible"):
                print(
                    f"  CPU Training: Feasible but slow ({cpu_notes.get('expected_training_time', '?')})"
                )
            else:
                print(f"  CPU Training: Not recommended - {cpu_notes.get('reason', 'Too large')}")


def main():
    """Main function to handle command line testing."""
    parser = argparse.ArgumentParser(
        description="Test and validate GPT model architecture",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Test medium model
  python core/src/test_model.py --model_size medium

  # Test all model sizes
  python core/src/test_model.py --all_sizes

  # Test with text generation
  python core/src/test_model.py --model_size small --test_generation

  # Show hardware recommendations
  python core/src/test_model.py --recommendations
        """,
    )

    parser.add_argument(
        "--model_size",
        choices=["small", "medium", "large"],
        default="medium",
        help="Model size to test (default: medium)",
    )

    parser.add_argument("--all_sizes", action="store_true", help="Test all model sizes")

    parser.add_argument(
        "--test_generation", action="store_true", help="Include text generation test"
    )

    parser.add_argument(
        "--device",
        choices=["cpu", "cuda", "auto"],
        default="auto",
        help="Device to use for testing (default: auto)",
    )

    parser.add_argument(
        "--recommendations",
        action="store_true",
        help="Show hardware recommendations for all model sizes",
    )

    parser.add_argument("--save_results", help="Save test results to JSON file")

    args = parser.parse_args()

    print("πŸ§ͺ GPT Model Architecture Tester")
    print("=" * 50)

    # Show hardware recommendations
    if args.recommendations:
        for size in ["small", "medium", "large"]:
            print_hardware_recommendations(size)
        return

    # Initialize tester
    tester = ModelTester(device=args.device)

    # Run tests
    all_results = {}

    if args.all_sizes:
        test_sizes = ["small", "medium", "large"]
    else:
        test_sizes = [args.model_size]

    for size in test_sizes:
        results = tester.run_comprehensive_test(size)
        all_results[size] = results

        # Print summary
        print(f"\nπŸ“Š {size.upper()} Model Test Summary:")
        print(f"  Initialization: {'βœ“' if results['initialization']['success'] else '❌'}")
        print(f"  Forward Pass: {'βœ“' if results.get('forward_pass', {}).get('success') else '❌'}")
        print(f"  Memory Test: {'βœ“' if 'memory_usage' in results else '❌'}")
        print(
            f"  Tokenizer: {'βœ“' if results.get('tokenizer_integration', {}).get('success') else '❌'}"
        )
        print(f"  Generation: {'βœ“' if results.get('generation', {}).get('success') else '❌'}")

    # Save results if requested
    if args.save_results:
        with open(args.save_results, "w") as f:
            json.dump(all_results, f, indent=2)
        print(f"\nπŸ’Ύ Results saved to {args.save_results}")

    print("\nπŸŽ‰ Testing completed!")


if __name__ == "__main__":
    main()