repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
cs249r_book
tinytorch/datasets/tinydigits/create_tinydigits.py
.py
#!/usr/bin/env python3 """ Create TinyDigits Dataset ========================= Extracts a balanced, curated subset from sklearn's digits dataset (8x8 grayscale). This creates a TinyTorch-branded educational dataset optimized for fast iteration. Following Karpathy's "~1000 samples" philosophy for educational datasets....
112
3,822
cs249r_book
tinytorch/datasets/tinytalks/scripts/generate_tinytalks.py
.py
""" TinyTalks Dataset Generator Systematically generates the TinyTalks v1.0 dataset with 350 Q&A pairs across 5 difficulty levels. Usage: python scripts/generate_tinytalks.py Output: - tinytalks_v1.txt (full dataset) - splits/train.txt (70%) - splits/val.txt (15%) - splits/test.txt (15%) """ imp...
589
27,735
cs249r_book
tinytorch/datasets/tinytalks/scripts/stats.py
.py
""" TinyTalks Dataset Statistics Generates comprehensive statistics about the TinyTalks dataset including: - Vocabulary statistics - Length distributions - Character frequencies - Split sizes Usage: python scripts/stats.py """ from pathlib import Path from collections import Counter import json def load_qa_pai...
194
6,454
cs249r_book
tinytorch/datasets/tinytalks/scripts/validate_dataset.py
.py
""" TinyTalks Dataset Validation Script Validates the TinyTalks dataset for: - Format consistency - No duplicate pairs - Balanced splits - Character encoding (UTF-8) - Line endings (Unix) Usage: python scripts/validate_dataset.py """ from pathlib import Path from collections import Counter def load_qa_pairs(fi...
257
8,050
cs249r_book
tinytorch/datasets/tinytalks/examples/demo_usage.py
.py
""" TinyTalks Dataset Usage Examples Demonstrates how to load and use the TinyTalks dataset for training transformer models. Usage: python examples/demo_usage.py """ from pathlib import Path def example1_load_full_dataset(): """Example 1: Load the full dataset""" print("=" * 60) print("Example 1: L...
237
6,741
cs249r_book
tinytorch/quarto/tools/measure-pdf-images.py
.py
#!/usr/bin/env python3 # ruff: noqa: E501 r""" measure-pdf-images.py โ€” observed-size figure sizing recommendations. Walk the rendered TinyTorch Lab Guide PDF, read every image's actual on-page bounding box (the geometry XeLaTeX put on the page AFTER our global \includegraphics cap fired). For each image, match it back...
377
13,747
cs249r_book
tinytorch/tests/validate_nbgrader_config.py
.py
#!/usr/bin/env python3 """ NBGrader Configuration Validation Script Validates all TinyTorch modules for NBGrader compatibility """ import argparse import re import json from pathlib import Path from collections import defaultdict from typing import Dict, List, Tuple, Set class NBGraderValidator: """Validates NBGr...
521
20,207
cs249r_book
tinytorch/tests/test_utils.py
.py
""" TinyTorch Test Utilities Shared utilities for integration tests across all modules. Provides setup functions and common test helpers. """ import sys import os from pathlib import Path def setup_integration_test(): """ Set up the environment for integration testing. This function ensures: 1. The...
113
3,191
cs249r_book
tinytorch/tests/conftest.py
.py
""" Pytest configuration for TinyTorch tests. This file is automatically loaded by pytest and sets up the test environment. It also provides a Rich-based educational test output that helps students understand what each test does and why it matters. CRITICAL: This conftest validates that the tinytorch package is prope...
349
11,997
cs249r_book
tinytorch/tests/04_losses/test_04_losses_progressive.py
.py
""" Module 04: Progressive Integration Tests Tests that Module 04 (Losses) works correctly AND that the entire foundation stack works. DEPENDENCY CHAIN: 01_tensor โ†’ 02_activations โ†’ 03_layers โ†’ 04_losses โ†’ 05_dataloader This is the FOUNDATION MILESTONE - everything should work together for neural networks! """ import...
346
12,733
cs249r_book
tinytorch/tests/04_losses/test_losses_core.py
.py
""" Module 04: Losses - Core Functionality Tests ============================================= WHY LOSSES MATTER: ----------------- The loss function defines what "good" means for your model. It's the signal that drives all learning. Wrong loss = wrong learning. WHAT STUDENTS LEARN: ------------------- 1. MSE for reg...
107
3,186
cs249r_book
tinytorch/tests/07_optimizers/test_optimizer_core.py
.py
""" Module 07: Optimizer Core Tests ================================ These tests verify that optimizers correctly update model parameters. WHY THESE TESTS MATTER: ----------------------- Optimizers are the "learning" part of machine learning. If they don't work: - Weights never change โ†’ model never learns - Weights e...
288
9,407
cs249r_book
tinytorch/tests/07_optimizers/test_07_optimizers_progressive.py
.py
""" Module 07: Progressive Integration Tests Tests that Module 07 (Optimizers) works correctly AND that the foundation stack (01โ†’06) still works. DEPENDENCY CHAIN: 01_tensor โ†’ 02_activations โ†’ 03_layers โ†’ 04_losses โ†’ 05_dataloader โ†’ 06_autograd โ†’ 07_optimizers This is where we enable learning through sophisticated opt...
453
16,626
cs249r_book
tinytorch/tests/milestones/test_milestones_smoke.py
.py
""" Milestone Smoke Tests โ€” Model Construction =========================================== Lightweight tests that verify every milestone script can at least import its dependencies and construct its model. No data downloads, no training โ€” just "does the code not crash on import?" These catch API drift between milesto...
149
5,295
cs249r_book
tinytorch/tests/milestones/test_milestones_run.py
.py
""" Milestone Full Run Tests ======================== These tests run each milestone script fully to verify the complete educational experience works end-to-end. This is Option C: Full run (~10-15 minutes total) - Runs each milestone with actual training - Verifies outputs are correct (accuracy thresholds, etc.) - Su...
197
7,767
cs249r_book
tinytorch/tests/milestones/milestone_tracker.py
.py
""" Compatibility milestone progress tracker for TinyTorch tests and older hooks. The canonical milestone definitions live in ``tito.commands.milestone``. This file mirrors that table so legacy imports do not carry stale module names or write to a separate home-directory progress file. """ import json from pathlib im...
255
9,546
cs249r_book
tinytorch/tests/10_tokenization/test_tokenization_core.py
.py
""" Module 10: Tokenization - Core Functionality Tests =================================================== WHY TOKENIZATION MATTERS: ------------------------ Models can't read text - they need numbers. Tokenization: - Splits text into tokens (words or subwords) - Maps tokens to integer IDs - Enables text โ†’ numbers con...
101
3,022
cs249r_book
tinytorch/tests/10_tokenization/test_10_tokenization_progressive.py
.py
""" Module 10: Progressive Integration Tests Tests that Module 10 (Tokenization) works correctly AND that Foundation + Architecture tier work. DEPENDENCY CHAIN: 01_tensor โ†’ ... โ†’ 05_dataloader โ†’ ... โ†’ 08_training โ†’ 09_convolutions โ†’ 10_tokenization This is where text processing begins for NLP pipelines. """ import nu...
609
23,342
cs249r_book
tinytorch/tests/15_quantization/test_quantizer_core.py
.py
""" Module 15: Quantization Core Tests =================================== These tests verify that quantization reduces model size correctly. WHY THESE TESTS MATTER: ----------------------- Quantization converts FP32 (4 bytes) to INT8 (1 byte) = 4x smaller model. If quantization is broken: - Model stays big (defeats ...
180
6,500
cs249r_book
tinytorch/tests/15_quantization/test_quantization_integration.py
.py
#!/usr/bin/env python3 """ Integration tests for Module 16: Quantization Tests INT8 quantization, dequantization, and quantized operations """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) def test_quantization_integration(): """Test quantization system integrati...
24
695
cs249r_book
tinytorch/tests/18_memoization/test_kv_cache_core.py
.py
""" Module 18: KV Cache (Memoization) Core Tests ============================================= These tests verify that KV caching works for efficient inference. WHY THESE TESTS MATTER: ----------------------- KV caching is essential for efficient text generation: - Without cache: O(nยฒ) per token (recompute all attent...
182
6,681
cs249r_book
tinytorch/tests/18_memoization/test_kv_cache_integration.py
.py
""" Integration Tests for Module 18: KV Caching Tests integration with transformer components and generation """ import numpy as np rng = np.random.default_rng(7) import pytest import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) from tinytorch.c...
369
14,575
cs249r_book
tinytorch/tests/18_memoization/test_tinygpt_integration.py
.py
""" Integration test for Module 18: Memoization (TinyGPT) Tests language model components and GPT-style transformer integration. """ import sys import numpy as np rng = np.random.default_rng(7) from pathlib import Path def run_integration_test(): """Run integration test for TinyGPT module.""" try: pri...
143
5,636
cs249r_book
tinytorch/tests/18_memoization/test_18_memoization_progressive.py
.py
""" Module 18: Progressive Integration Tests Tests that Module 18 (Memoization/KV-Cache) works correctly AND that prior modules (01โ†’17) still work. DEPENDENCY CHAIN: 01_tensor โ†’ ... โ†’ 13_transformers โ†’ ... โ†’ 17_acceleration โ†’ 18_memoization โš ๏ธ IMPORTANT: This test ONLY uses modules 01-18. Future modules (19_benchm...
343
11,452
cs249r_book
tinytorch/tests/02_activations/test_tensor_activations_integration.py
.py
""" Integration Tests - Tensor and Activations Tests cross-module interfaces and compatibility between Tensor and Activation modules. Focuses on integration, not re-testing individual module functionality. """ import pytest import numpy as np rng = np.random.default_rng(7) from test_utils import setup_integration_tes...
270
11,236
cs249r_book
tinytorch/tests/02_activations/test_activations_core.py
.py
""" Module 02: Activations - Core Functionality Tests ================================================== These tests verify that activation functions work correctly. WHY ACTIVATIONS MATTER: ---------------------- Without activations, neural networks are just linear transformations. No matter how many layers you stack...
449
15,004
cs249r_book
tinytorch/tests/02_activations/test_02_activations_progressive.py
.py
""" Module 02: Progressive Integration Tests Tests that Module 02 (Activations) works correctly AND that all previous modules still work. DEPENDENCY CHAIN: 01_tensor โ†’ 02_activations Students can trace back exactly where issues originate. """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib i...
275
9,462
cs249r_book
tinytorch/tests/02_activations/test_activations_integration.py
.py
""" Module 02: Activations - Integration Tests Tests that activations work with Tensor and enable non-linear networks """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) class TestActivation...
159
5,372
cs249r_book
tinytorch/tests/integration/test_forward_passes.py
.py
#!/usr/bin/env python """ Forward Pass Tests for TinyTorch ================================= Tests that all architectures can do forward passes correctly. This validates the "plumbing" - data flows through without errors. """ import sys import os import numpy as np rng = np.random.default_rng(7) # Add project root to...
383
11,220
cs249r_book
tinytorch/tests/integration/test_api_simplification_integration.py
.py
""" Integration test for API Simplification Validates that the new PyTorch-compatible API integrates correctly across all components: - nn module with Module, Linear, Conv2d - nn.functional with relu, flatten, max_pool2d - optim module with Adam, SGD - Complete workflow integration (model creation โ†’ optimizer โ†’ traini...
397
14,824
cs249r_book
tinytorch/tests/integration/test_gradients.py
.py
#!/usr/bin/env python """ Gradient Flow Validation Tests for TinyTorch ============================================= Ensures gradients propagate correctly through all architectures. Critical for verifying that models can actually learn. Test Categories: - Gradient existence through deep networks - Gradient magnitude (...
513
16,469
cs249r_book
tinytorch/tests/integration/test_module_05_dense.py
.py
""" Integration Tests for Module 05: DataLoader These tests verify that the module exports correctly and works as expected. Run with pytest for detailed reporting. """ import pytest import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(...
183
6,347
cs249r_book
tinytorch/tests/integration/test_optimizers_integration.py
.py
""" Integration tests for TinyTorch optimizers with other modules. Tests that optimizers correctly integrate with: - Module 01: Tensor operations - Module 02: Activation functions - Module 03: Layers (Linear, Sequential) - Module 06: Autograd (Tensor with gradients) - Module 04: Losses (MSE, CrossEntropy) """ import ...
488
13,621
cs249r_book
tinytorch/tests/integration/test_training_flow.py
.py
""" Training Flow Integration Tests ================================ Tests that the complete training pipeline works: 1. Forward pass produces valid outputs 2. Loss computes correctly 3. Backward pass populates gradients 4. Optimizer updates weights 5. Loss decreases over iterations These tests catch issues that unit...
381
11,726
cs249r_book
tinytorch/tests/integration/test_shapes.py
.py
#!/usr/bin/env python """ Shape Validation Tests for TinyTorch ===================================== Comprehensive shape validation ensuring all operations produce expected dimensions. Uses pytest style - one test per specific behavior for clear reporting. Run with: pytest tests/system/test_shapes.py -v """ import sy...
453
15,067
cs249r_book
tinytorch/tests/integration/test_dataloader_integration.py
.py
""" Integration tests for DataLoader with training workflows. These tests verify that DataLoader works correctly when integrated with actual training pipelines, not just in isolation. """ import numpy as np rng = np.random.default_rng(7) import sys import os # Add project root to path sys.path.insert(0, os.path.join...
152
5,380
cs249r_book
tinytorch/tests/integration/test_module_integration.py
.py
""" TinyTorch Module Integration Tests Tests that modules work together correctly when integrated. These tests focus on inter-module compatibility, not individual module functionality. Integration test categories: 1. Core module integration (tensor + autograd + layers) 2. Training pipeline integration (optimizers + t...
217
6,829
cs249r_book
tinytorch/tests/integration/__init__.py
.py
""" Integration tests for TinyTorch. These tests validate that multiple modules work together correctly. They catch issues that unit tests miss, like: - Gradient flow through entire training pipelines - Module compatibility and interface contracts - End-to-end training scenarios Critical for catching bugs like: - Mis...
15
415
cs249r_book
tinytorch/tests/integration/test_module_dependencies.py
.py
#!/usr/bin/env python3 """ Module Dependency Integration Testing Tests how each module interfaces with modules that came before it """ import numpy as np rng = np.random.default_rng(7) # Module dependency graph for TinyTorch # Current module structure: # 01_tensor, 02_activations, 03_layers, 04_losses, 05_dataloader,...
353
12,317
cs249r_book
tinytorch/tests/integration/test_nlp_pipeline_flow.py
.py
""" NLP Pipeline Flow Integration Tests ==================================== Tests that the NLP pipeline works end-to-end: 1. Tokenization produces valid token IDs 2. Embeddings convert tokens to vectors 3. Attention mechanisms process sequences 4. Transformers combine everything correctly 5. Gradients flow back throu...
319
10,154
cs249r_book
tinytorch/tests/integration/test_network_capability.py
.py
""" Network Capability Tests for Module 05 Tests that networks can solve non-linear problems """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) class TestXORCapability: """Test that mul...
128
3,947
cs249r_book
tinytorch/tests/integration/test_xor_thorough.py
.py
#!/usr/bin/env python3 """ Thorough XOR test to verify multi-layer networks work correctly. """ import sys sys.path.insert(0, '.') import numpy as np from tinytorch import Tensor, Linear, ReLU, Sigmoid, BinaryCrossEntropyLoss, SGD print("=" * 70) print("๐Ÿงช THOROUGH XOR TEST - Verifying Multi-Layer Networks") print("=...
92
2,588
cs249r_book
tinytorch/tests/integration/test_integration_gradient_flow.py
.py
#!/usr/bin/env python3 """ Comprehensive Gradient Flow Tests for TinyTorch ================================================ Tests that gradients flow correctly through: 1. Simple networks (single layer) 2. Multi-layer networks (MLP) 3. Convolutional networks (CNN) 4. Attention mechanisms 5. Complete training loops Th...
454
14,606
cs249r_book
tinytorch/tests/integration/test_layers_integration.py
.py
#!/usr/bin/env python3 """ Integration Tests for TinyTorch Layers Module This file contains the integration tests that were removed from Module 03 to keep the module focused on unit testing only. These tests demonstrate how layers work together with other modules and complete system behaviors. """ import sys import o...
229
8,255
cs249r_book
tinytorch/tests/integration/test_cnn_integration.py
.py
#!/usr/bin/env python3 """ Integration Tests for CNN (Spatial) Operations Tests that verify: 1. Convolutions are actually working (not just shape manipulation) 2. Gradients flow through conv layers correctly 3. Shape transformations are correct 4. MaxPooling/AvgPooling work as expected 5. Complete CNN forward/backward...
360
14,932
cs249r_book
tinytorch/tests/integration/test_loss_gradients.py
.py
""" Comprehensive test for loss function gradients. Tests which losses have proper autograd integration and work for training. """ import numpy as np import sys import os # Add project root to path sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) from tinytorch import Tensor, Linear, MSELoss,...
227
7,648
cs249r_book
tinytorch/tests/integration/test_training_capabilities.py
.py
#!/usr/bin/env python """ Training Capability Tests for TinyTorch ======================================== Tests that models can actually learn (not just forward pass). Validates gradient flow, parameter updates, and convergence. """ import sys import os import numpy as np rng = np.random.default_rng(7) # Add project...
417
11,612
cs249r_book
tinytorch/tests/03_layers/test_layers_core.py
.py
""" Module 03: Layers - Core Functionality Tests ============================================= These tests verify that Layer abstractions work correctly. WHY LAYERS MATTER: ----------------- Layers are the building blocks of neural networks: - Linear (Dense): y = Wx + b - Conv2d: sliding window feature detection - RN...
493
15,969
cs249r_book
tinytorch/tests/03_layers/test_dense_integration.py
.py
""" Integration test for Module 04: Linear Validates that the dense module integrates correctly with the TinyTorch package. This is a quick validation test, not a comprehensive capability test. """ import sys import importlib import warnings import numpy as np rng = np.random.default_rng(7) def test_dense_module_in...
195
6,793
cs249r_book
tinytorch/tests/03_layers/test_03_layers_progressive.py
.py
""" Module 03: Progressive Integration Tests Tests that Module 03 (Layers) works correctly AND that the foundation stack (01โ†’02) still works. DEPENDENCY CHAIN: 01_tensor โ†’ 02_activations โ†’ 03_layers This is where we create reusable building blocks for neural networks. ๐ŸŽฏ WHAT THIS TESTS: - Module 03: Layer base class...
995
36,767
cs249r_book
tinytorch/tests/03_layers/test_layers_networks_integration.py
.py
""" Integration Tests - Layers and Dense Networks Tests cross-module interfaces and compatibility between individual Layers and Dense Network modules. Focuses on integration, not re-testing individual module functionality. """ import pytest import numpy as np rng = np.random.default_rng(7) from test_utils import setu...
332
13,475
cs249r_book
tinytorch/tests/03_layers/test_dense_layer.py
.py
""" Tests for Module 04: Linear/Networks """ import pytest import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) class TestLinearExports: """Test that Linear layer is properly exported.""" ...
118
3,471
cs249r_book
tinytorch/tests/03_layers/test_layers_integration.py
.py
""" Module 03: Layers - Integration Tests Tests that Layer base class enables building neural network components """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) class TestLayerFoundation...
222
7,058
cs249r_book
tinytorch/tests/environment/test_setup_validation.py
.py
""" Environment Setup Validation Tests These tests verify that the TinyTorch environment is correctly configured and all dependencies work as expected. Run these after `tito setup` to ensure students can actually use TinyTorch. Usage: pytest tests/environment/test_setup_validation.py -v Or via TITO: tito...
436
15,137
cs249r_book
tinytorch/tests/environment/test_all_requirements.py
.py
""" Automated Requirements Validation Tests Automatically tests ALL packages from requirements.txt to ensure: 1. They can be imported 2. They have the correct version 3. They actually work (basic functionality test) This discovers ALL requirements files and validates every package. Usage: pytest tests/environmen...
394
12,861
cs249r_book
tinytorch/tests/11_embeddings/test_embeddings_core.py
.py
""" Module 11: Embeddings - Core Functionality Tests ================================================= WHY EMBEDDINGS MATTER: --------------------- Embeddings turn discrete IDs into dense vectors: - Token ID 156 โ†’ [0.2, -0.5, 0.8, ...] (512 dims) - These vectors capture meaning - Similar words have similar embeddings...
117
3,205
cs249r_book
tinytorch/tests/11_embeddings/test_11_embeddings_progressive.py
.py
""" Module 11: Progressive Integration Tests Tests that Module 11 (Embeddings) works correctly AND that prior modules (01โ†’10) still work. DEPENDENCY CHAIN: 01_tensor โ†’ 02_activations โ†’ 03_layers โ†’ 04_losses โ†’ 05_dataloader โ†’ 06_autograd โ†’ 07_optimizers โ†’ 08_training โ†’ 09_convolutions โ†’ 10_tokenizati...
346
11,646
cs249r_book
tinytorch/tests/11_embeddings/test_embedding_gradient_flow.py
.py
""" Test gradient flow through Embedding layer. These tests ensure that: 1. EmbeddingBackward is properly attached to Embedding outputs 2. Gradients flow correctly to embedding weight matrix 3. Integration with autograd system works end-to-end Prevents regression of gradient flow issues discovered in milestone testin...
216
6,795
cs249r_book
tinytorch/tests/11_embeddings/test_training_integration.py
.py
""" Module 08: Training - Integration Tests Tests that complete training loops work with all system components """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) class TestTrainingLoopInteg...
272
9,091
cs249r_book
tinytorch/tests/14_profiling/test_profiler_core.py
.py
""" Module 14: Profiler Core Tests =============================== These tests verify that the profiling tools work correctly. WHY THESE TESTS MATTER: ----------------------- Profiling is essential for ML systems engineering. Without it: - You can't find bottlenecks - You can't measure improvement - Optimization is g...
119
3,330
cs249r_book
tinytorch/tests/14_profiling/test_14_profiling_progressive.py
.py
""" Module 14: Progressive Integration Tests Tests that Module 14 (Profiling) works correctly AND that prior modules (01โ†’13) still work. DEPENDENCY CHAIN: 01_tensor โ†’ ... โ†’ 12_attention โ†’ 13_transformers โ†’ 14_profiling โš ๏ธ IMPORTANT: This test ONLY uses modules 01-14. Future modules (15_quantization, 16_compression...
352
11,378
cs249r_book
tinytorch/tests/20_capstone/test_capstone_integration.py
.py
#!/usr/bin/env python3 """ Integration tests for Module 20: Capstone Tests end-to-end ML system integration """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) def test_capstone_integration(): """Test capstone project integration.""" # TODO: Implement integrati...
24
654
cs249r_book
tinytorch/tests/20_capstone/test_capstone_core.py
.py
""" Module 20: Capstone Core Tests =============================== These tests verify the capstone submission and reporting system. WHY THESE TESTS MATTER: ----------------------- The capstone is where students prove their TinyTorch implementation works. These tests verify: 1. BenchmarkReport can aggregate all metric...
179
5,416
cs249r_book
tinytorch/tests/13_transformers/test_training_simple.py
.py
""" Simple end-to-end training test for transformers. This test validates that a transformer can successfully learn from a tiny dataset, demonstrating that the entire training pipeline (forward, loss, backward, update) works. """ import sys import time from pathlib import Path import numpy as np rng = np.random.defa...
247
7,575
cs249r_book
tinytorch/tests/13_transformers/test_transformers_core.py
.py
""" Module 13: Transformers - Core Functionality Tests =================================================== WHY TRANSFORMERS MATTER: ----------------------- Transformers power modern AI: - GPT, ChatGPT, Claude (language) - BERT (understanding) - Vision Transformers (images) - Whisper (speech) WHAT STUDENTS LEARN: ----...
114
3,268
cs249r_book
tinytorch/tests/13_transformers/test_13_transformers_progressive.py
.py
""" Module 13: Progressive Integration Tests Tests that Module 13 (Transformers) works correctly AND that prior modules (01โ†’12) still work. DEPENDENCY CHAIN: 01_tensor โ†’ ... โ†’ 11_embeddings โ†’ 12_attention โ†’ 13_transformers โš ๏ธ IMPORTANT: This test ONLY uses modules 01-13. Future modules (14_profiling, 19_benchmarki...
400
12,982
cs249r_book
tinytorch/tests/13_transformers/test_transformer_gradient_flow.py
.py
""" Test gradient flow through complete transformer architecture. This test validates that all transformer components (embeddings, attention, LayerNorm, MLP) properly propagate gradients during backpropagation. """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add parent dir...
258
8,178
cs249r_book
tinytorch/tests/08_training/test_autograd_integration.py
.py
""" Module 08: Training - Autograd Integration Tests Tests that automatic differentiation works with all previous modules """ import numpy as np import pytest import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) pytestmark = pytest.mark.skip( ...
222
7,358
cs249r_book
tinytorch/tests/08_training/test_training_core.py
.py
""" Module 08: Training - Core Functionality Tests =============================================== WHY TRAINING MATTERS: -------------------- Training is where learning happens: 1. Forward pass: compute predictions 2. Loss: measure error 3. Backward: compute gradients 4. Update: adjust weights WHAT STUDENTS LEARN: --...
267
8,149
cs249r_book
tinytorch/tests/08_training/test_training_coverage.py
.py
""" Module 08: Training - Coverage Tests ====================================== Tests for the parts of Module 08 that are implemented but have no test coverage: - CosineSchedule correctness - clip_grad_norm behaviour - Trainer.save_checkpoint / load_checkpoint round-trip - Trainer.evaluate (loss and accuracy) - Schedu...
481
19,942
cs249r_book
tinytorch/tests/08_training/test_08_training_progressive.py
.py
""" Module 08: Progressive Integration Tests Tests that Module 08 (Training) works correctly AND that prior modules (01โ†’07) still work. DEPENDENCY CHAIN: 01_tensor โ†’ 02_activations โ†’ 03_layers โ†’ 04_losses โ†’ 05_dataloader โ†’ 06_autograd โ†’ 07_optimizers โ†’ 08_training โš ๏ธ IMPORTANT: This test ONLY uses modules 01-08. F...
501
18,007
cs249r_book
tinytorch/tests/12_attention/test_12_attention_progressive.py
.py
""" Module 12: Progressive Integration Tests Tests that Module 12 (Attention) works correctly AND that prior modules (01โ†’11) still work. DEPENDENCY CHAIN: 01_tensor โ†’ ... โ†’ 10_tokenization โ†’ 11_embeddings โ†’ 12_attention โš ๏ธ IMPORTANT: This test ONLY uses modules 01-12. Future modules (13_transformers, 16_compressio...
354
11,905
cs249r_book
tinytorch/tests/12_attention/test_attention_core.py
.py
""" Module 12: Attention Core Tests ================================ These tests verify that attention mechanisms compute correctly. WHY THESE TESTS MATTER: ----------------------- Attention is the core innovation behind Transformers (GPT, BERT, etc.). If attention doesn't work: - Model can't focus on relevant parts ...
288
9,877
cs249r_book
tinytorch/tests/17_acceleration/test_acceleration_integration.py
.py
#!/usr/bin/env python3 """ Integration tests for Module 17: Acceleration Tests operator fusion, kernel optimization, and hardware acceleration """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) def test_acceleration_integration(): """Test acceleration system integ...
24
697
cs249r_book
tinytorch/tests/17_acceleration/test_acceleration_core.py
.py
""" Module 17: Acceleration Core Tests =================================== These tests verify optimization techniques for faster inference. WHY THESE TESTS MATTER: ----------------------- Acceleration techniques (SIMD, parallel execution, memory layout) can provide significant speedups. These tests verify: - Optimiza...
122
3,746
cs249r_book
tinytorch/tests/regression/test_nlp_components_gradient_flow.py
.py
#!/usr/bin/env python3 """ Comprehensive Gradient Flow Tests for NLP Components Tests gradient flow through all NLP-specific modules: - Module 10: Tokenization - Module 11: Embedding + PositionalEncoding - Module 12: Attention (scaled dot-product + multi-head) - Module 13: Transformer (LayerNorm, MLP, TransformerBlock...
579
19,151
cs249r_book
tinytorch/tests/regression/run_sandbox_tests.py
.py
#!/usr/bin/env python """ TinyTorch Sandbox Integrity Tests ================================== Run this to ensure the student learning sandbox is robust. All core infrastructure must work perfectly so students can focus on learning ML systems, not debugging framework issues. """ import sys import os import importlib ...
86
2,561
cs249r_book
tinytorch/tests/regression/test_transformer_reshaping.py
.py
""" BUG TRACKING: ============ Bug ID: BUG-2024-11-25-002 Date Found: 2024-11-25 Found By: PyTorch Expert Architecture Review Severity: High DESCRIPTION: TinyGPT example fails with "matmul requires 2D tensors" when passing transformer output (3D: batch x seq x embed) directly to Linear layer projection. REPRODUCTION:...
274
9,263
cs249r_book
tinytorch/tests/regression/test_gradient_flow_fixes.py
.py
#!/usr/bin/env python3 """ Regression Tests for Gradient Flow Fixes This test suite verifies that specific gradient flow bugs have been fixed and don't regress. These tests document the issues we encountered during transformer milestone implementation and ensure the fixes remain in place. Regression Issues Tested: 1....
313
10,654
cs249r_book
tinytorch/tests/regression/test_conv_linear_dimensions.py
.py
""" BUG TRACKING: ============ Bug ID: BUG-2024-11-25-001 Date Found: 2024-11-25 Found By: PyTorch Expert Architecture Review Severity: High DESCRIPTION: CNN example fails with "Inner dimensions must match: 2304 != 1600" when connecting Conv2d outputs to Linear layer inputs in CIFAR-10 training. REPRODUCTION: 1. Load...
211
7,122
cs249r_book
tinytorch/tests/01_tensor/test_tensor_core.py
.py
""" Module 01: Tensor - Core Functionality Tests ============================================= These tests verify that Tensor, the fundamental data structure of TinyTorch, works correctly. WHY TENSORS MATTER: ------------------ Tensors are the foundation of ALL deep learning: - Every input (images, text, audio) becom...
574
19,827
cs249r_book
tinytorch/tests/01_tensor/test_tensor_integration.py
.py
""" Module 01: Tensor - Integration Tests Tests that Tensor works as foundation for all other modules """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) class TestTensorFoundation: """T...
146
4,834
cs249r_book
tinytorch/tests/01_tensor/test_01_tensor_progressive.py
.py
""" Module 01: Progressive Integration Tests Tests that Module 01 (Tensor) works correctly. DEPENDENCY CHAIN: 01_tensor This ensures students can trace back exactly where issues originate. """ import numpy as np rng = np.random.default_rng(7) import sys from pathlib import Path # Add project root to path sys.path.in...
176
6,453
cs249r_book
tinytorch/tests/cli/test_cli_registry.py
.py
""" CLI Registry Tests - Validate all commands are properly registered and accessible This test suite ensures: 1. All commands in TinyTorchCLI.commands are valid BaseCommand subclasses 2. All commands have proper metadata (name, description) 3. All commands can be invoked via argparse 4. No commands are missing from r...
222
8,476
cs249r_book
tinytorch/tests/cli/test_nbgrader_command.py
.py
import argparse import json import os import subprocess from argparse import Namespace from pathlib import Path import pytest from tito.commands.nbgrader import NBGraderCommand from tito.core.config import CLIConfig def make_config(project_root: Path) -> CLIConfig: return CLIConfig.from_project_root(project_roo...
554
20,035
cs249r_book
tinytorch/tests/cli/test_community_flow.py
.py
""" Tests for the TinyTorch community submission and progress syncing flow. These tests validate: 1. Retrieval of authentication status and tokens. 2. Creation and structure of the progress payload. 3. Execution of progress syncing POST requests with mock servers. """ import json import pytest from unittest.mock impo...
148
5,870
cs249r_book
tinytorch/tests/cli/test_progress_sync.py
.py
""" Regression tests for community progress sync (issue #1849). These guard the bug where the TinyTorch dashboard did not reflect CLI progress: 1. Automatic sync was silently skipped on any non-TTY shell (Git Bash / MinTTY on Windows, IDE terminals), because the trigger gated on ``sys.stdin.isatty()``. The fix ...
226
8,105
cs249r_book
tinytorch/tests/cli/test_live_submission.py
.py
""" Live E2E integration test for TinyTorch progress submission to Supabase. This test runs ONLY if TINYTORCH_TEST_EMAIL and TINYTORCH_TEST_PASSWORD are set in the environment or in a local.env file. It automates the entire flow: 1. Programmatic login to Supabase auth API using email/password + active Anon Key. 2. Te...
185
7,161
cs249r_book
tinytorch/tests/cli/test_cli_execution.py
.py
""" CLI Execution Tests - Smoke tests for each command This test suite ensures: 1. Each command can be executed without crashing (help mode) 2. Commands with subcommands show their subcommand help 3. Error messages are helpful when commands fail """ import pytest import subprocess import sys from pathlib import Path ...
203
6,706
cs249r_book
tinytorch/tests/cli/test_release_regressions.py
.py
""" Release regression tests for student-facing CLI and API correctness. """ import importlib.util import io import os import subprocess import sys from argparse import Namespace from pathlib import Path import numpy as np from rich.console import Console from tito.commands.export_utils import find_source_file_for_e...
196
5,984
cs249r_book
tinytorch/tests/cli/test_cli_help_consistency.py
.py
""" CLI Help Consistency Tests - Validate help text is consistent and complete This test suite ensures: 1. Help text uses consistent formatting and terminology 2. All commands document their purpose clearly 3. Examples are provided where helpful 4. No broken references or outdated commands in help text """ import pyt...
248
8,500
cs249r_book
tinytorch/tests/19_benchmarking/test_benchmark_core.py
.py
""" Module 19: Benchmarking Core Tests =================================== These tests verify that benchmarking tools work correctly. WHY THESE TESTS MATTER: ----------------------- Benchmarking is how we measure and compare model performance. If benchmarking is broken: - We can't measure throughput (tokens/second) -...
172
5,718
cs249r_book
tinytorch/tests/19_benchmarking/test_benchmarking_integration.py
.py
#!/usr/bin/env python3 """ Integration tests for Module 19: Benchmarking Tests MLPerf-style benchmarking and performance measurement """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) def test_benchmarking_integration(): """Test benchmarking system integration."""...
24
687
cs249r_book
tinytorch/tests/06_autograd/test_autograd_core.py
.py
""" Module 06: Autograd - Core Functionality Tests Tests automatic differentiation and computational graphs NOTE: These tests reference a Variable class that is not implemented in TinyTorch. TinyTorch enhances Tensor directly via enable_autograd(). These tests are retained as placeholders for future Variable API suppo...
407
12,869
cs249r_book
tinytorch/tests/06_autograd/test_autograd_gradient_flow.py
.py
""" Test gradient flow through all autograd operations. This test suite validates that all arithmetic operations and activations properly preserve gradient tracking and enable backpropagation. """ import numpy as np import pytest import sys from pathlib import Path # Add parent directory to path for imports sys.path...
166
5,323
cs249r_book
tinytorch/tests/06_autograd/test_batched_matmul_backward.py
.py
#!/usr/bin/env python3 """ Test batched matrix multiplication gradients in autograd. This test verifies that MatmulBackward correctly handles batched 3D+ tensors using np.matmul and np.swapaxes instead of np.dot and .T """ import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..')) impo...
152
4,920
cs249r_book
tinytorch/tests/06_autograd/__init__.py
.py
""" Autograd-specific edge case tests. These tests focus on the autograd module's internal behavior: - Broadcasting in gradients (common bug source) - Computation graph construction - Numerical stability in backward pass - Memory management in gradient accumulation - Edge cases students encounter Complements the inli...
14
391
cs249r_book
tinytorch/tests/06_autograd/test_06_autograd_progressive.py
.py
""" Module 06: Progressive Integration Tests Tests that Module 06 (Autograd) works correctly AND that prior modules (01โ†’05) still work. DEPENDENCY CHAIN: 01_tensor โ†’ 02_activations โ†’ 03_layers โ†’ 04_losses โ†’ 05_dataloader โ†’ 06_autograd โš ๏ธ IMPORTANT: This test ONLY uses modules 01-06. Future modules (07_optimizers, ...
571
20,496
cs249r_book
tinytorch/tests/06_autograd/test_gradient_correctness.py
.py
""" Module 06: Gradient Correctness Tests ====================================== Validates that every backward pass computes numerically correct gradients using finite differences as ground truth. The core idea: for any function f, the analytical gradient computed by backward() should match the numerical gradient: ...
405
12,549
cs249r_book
tinytorch/tests/16_compression/test_compressor_core.py
.py
""" Module 16: Compression Core Tests =================================== These tests verify that model compression (pruning) works correctly. WHY THESE TESTS MATTER: ----------------------- Pruning removes unnecessary weights, making models smaller and faster. If compression is broken: - Model doesn't get smaller (n...
230
7,568