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/tests/16_compression/test_compression_integration.py
.py
#!/usr/bin/env python3 """ Integration tests for Module 16: Compression Tests pruning, knowledge distillation, and model compression """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) def test_compression_integration(): """Test compression system integration.""" ...
24
697
cs249r_book
tinytorch/tests/09_convolutions/test_convolutions_gradient_flow.py
.py
""" Test gradient flow through spatial operations (Conv2d, MaxPool2d). These tests ensure that: 1. Conv2dBackward is properly attached to Conv2d outputs 2. MaxPool2dBackward is properly attached to MaxPool2d outputs 3. Gradients flow correctly to all parameters (weight, bias) 4. Integration with autograd system works ...
301
10,077
cs249r_book
tinytorch/tests/09_convolutions/test_convolutions_core.py
.py
""" Module 09: Convolutions - Core Functionality Tests =================================================== These tests verify convolutional layers work correctly for computer vision. WHY CONVOLUTIONS MATTER: ----------------------- Convolutions are the foundation of computer vision: - Image classification (ImageNet, ...
363
12,495
cs249r_book
tinytorch/tests/09_convolutions/test_09_convolutions_progressive.py
.py
""" Module 09: Progressive Integration Tests Tests that Module 09 (Convolutions/Spatial) works correctly AND that prior modules (01→08) still work. DEPENDENCY CHAIN: 01_tensor → 02_activations → 03_layers → 04_losses → 05_dataloader → 06_autograd → 07_optimizers → 08_training → 09_convolutions ⚠️ IMPORTANT: This test...
493
17,261
cs249r_book
tinytorch/tests/e2e/test_user_journey.py
.py
""" End-to-End User Journey Tests for TinyTorch These tests simulate the complete student experience: 1. Fresh start (setup) 2. Module workflow (start → work → complete) 3. Progress tracking 4. Milestone unlocking Run with: pytest tests/e2e/test_user_journey.py -v Categories: -k quick # Fast CLI veri...
432
15,971
cs249r_book
tinytorch/tests/e2e/conftest.py
.py
""" E2E Test Configuration Registers pytest markers for categorizing tests by speed and purpose. """ import pytest def pytest_configure(config): """Register custom markers for E2E tests.""" config.addinivalue_line("markers", "quick: Quick verification tests (~30s total)") config.addinivalue_line("marker...
18
694
cs249r_book
tinytorch/tests/05_dataloader/test_05_dataloader_progressive.py
.py
""" Module 05: Progressive Integration Tests Tests that Module 05 (DataLoader) works correctly AND that Foundation tier (01→04) still works. DEPENDENCY CHAIN: 01_tensor → 02_activations → 03_layers → 04_losses → 05_dataloader 🎯 WHAT THIS TESTS: - Module 05: Dataset abstraction, batching, shuffling, data pipelines - ...
471
16,839
cs249r_book
tinytorch/tests/05_dataloader/test_dataloader_core.py
.py
""" Module 05: DataLoader - Core Functionality Tests ================================================= WHY DATALOADER MATTERS: ---------------------- Real datasets don't fit in memory. DataLoader: - Loads data in batches - Shuffles for better training - Enables parallel loading WHAT STUDENTS LEARN: ------------------...
121
4,176
cs249r_book
tinytorch/paper/scripts/benchmark_quick.py
.py
#!/usr/bin/env python3 """ Quick benchmark for Table 3 - uses reasonable approximations for slow operations """ import time import numpy as np import torch def time_op(func, warmup=2, runs=5): """Time an operation""" for _ in range(warmup): func() times = [] for _ in range(runs): start...
135
4,705
cs249r_book
tinytorch/src/04_losses/04_losses.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 04: Losses ...
1,729
63,399
cs249r_book
tinytorch/src/07_optimizers/07_optimizers.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.19.2 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 07: Optimiz...
2,025
71,803
cs249r_book
tinytorch/src/10_tokenization/10_tokenization.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 10: Tokeniz...
2,026
79,209
cs249r_book
tinytorch/src/15_quantization/15_quantization.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- #| default_exp perf.quantization # %% [...
2,399
103,571
cs249r_book
tinytorch/src/18_memoization/18_memoization.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 18: Memoiza...
2,062
81,781
cs249r_book
tinytorch/src/02_activations/02_activations.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 02: Activat...
1,184
38,208
cs249r_book
tinytorch/src/03_layers/03_layers.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 03: Layers ...
1,468
57,672
cs249r_book
tinytorch/src/11_embeddings/11_embeddings.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 11: Embeddi...
2,008
88,246
cs249r_book
tinytorch/src/14_profiling/14_profiling.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 14: Profili...
2,506
101,229
cs249r_book
tinytorch/src/20_capstone/20_capstone.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 20: Capston...
2,185
92,313
cs249r_book
tinytorch/src/13_transformers/13_transformers.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- #| default_exp core.transformers #| expo...
2,035
87,730
cs249r_book
tinytorch/src/08_training/08_training.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 08: Trainin...
2,049
73,221
cs249r_book
tinytorch/src/12_attention/12_attention.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- #| default_exp core.attention #| export ...
1,551
61,780
cs249r_book
tinytorch/src/17_acceleration/17_acceleration.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- #| default_exp perf.acceleration #| expo...
1,526
61,596
cs249r_book
tinytorch/src/01_tensor/01_tensor.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 01: Tensor ...
2,002
79,813
cs249r_book
tinytorch/src/19_benchmarking/19_benchmarking.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 19: Benchma...
4,120
155,862
cs249r_book
tinytorch/src/06_autograd/06_autograd.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 06: Autogra...
3,498
125,647
cs249r_book
tinytorch/src/16_compression/16_compression.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 16: Compres...
1,971
79,358
cs249r_book
tinytorch/src/09_convolutions/09_convolutions.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] """ # Module 09: Convolu...
3,243
124,446
cs249r_book
tinytorch/src/05_dataloader/05_dataloader.py
.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.17.1 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- #| default_exp core.dataloader #| export...
2,350
87,662
cs249r_book
slides/scripts/pdf2pptx.py
.py
#!/usr/bin/env python3 """Convert PDF slide decks to PowerPoint (PPTX) using high-resolution images. Each PDF page is rendered at 300 DPI via pdftoppm (poppler) and placed as a full-bleed image on a 16:9 PowerPoint slide. The result is visually identical to the PDF — suitable for presenting in PowerPoint/Keynote with ...
125
4,280
cs249r_book
mlsysim/generate_appendix.py
.py
# generate_appendix.py """ mlsysim Appendix Generator ========================== Generates Quarto-compatible Markdown tables for the textbook's backmatter. Extracts live data from the mlsysim Hardware and Model registries. """ from mlsysim.core.units import Q_ from mlsysim.hardware.registry import Hardware from mlsysi...
53
1,956
cs249r_book
mlsysim/mlsysim/solvers.py
.py
""" mlsysim.solvers — Convenience re-export of all solver classes. This is the stable public import path for solvers: from mlsysim.solvers import ServingModel, TailLatencyModel, ... The export list is derived mechanically from ``mlsysim.engine.solvers.__all__`` (the canonical list), so every name here is ``is``-...
18
601
cs249r_book
mlsysim/mlsysim/__main__.py
.py
"""Entry point for `python -m mlsysim`.""" try: from mlsysim.cli.main import app except ImportError: import sys print( "Unable to import the mlsysim CLI.\n" "Install or repair the package with: pip install mlsysim", file=sys.stderr, ) sys.exit(1) if __name__ == "__main__": ...
16
330
cs249r_book
mlsysim/mlsysim/__init__.py
.py
# mlsysim/__init__.py """ mlsysim: Machine Learning Systems Infrastructure and Modeling Platform """ __version__ = "0.1.2" from . import core from . import engine from . import hardware from . import models from . import platforms from . import infrastructure from . import systems from . import sim from . import phys...
75
2,631
cs249r_book
mlsysim/mlsysim/fmt.py
.py
""" fmt.py Formatting + presentation helpers for Markdown/Quarto output. Keep science in mlsysim/physics/; keep display here. """ from .core.units import ureg class MarkdownStr(str): """A string that ALSO renders as raw Markdown when consumed by Quarto/Jupyter. Quarto's inline ``{python} x`` substitution es...
3,131
107,302
cs249r_book
mlsysim/mlsysim/show.py
.py
""" show.py — Tutorial display helpers for MLSys·im. Replaces verbose print(f"...") patterns with clean, aligned output. Two primitives: info() for key-value blocks, table() for tabular data. Usage in tutorials: from mlsysim.show import info, table, banner info("Phase Analysis", TTFT=result.ttft.to(...
154
4,502
cs249r_book
mlsysim/mlsysim/systems/types.py
.py
from pydantic import BaseModel, ConfigDict, Field, field_validator from typing import Any, Optional from ..hardware.types import HardwareNode from ..infrastructure.types import Datacenter, GridProfile from ..core.units import ureg from ..core.types import ( Quantity, Metadata, require_dimensionality, re...
242
8,265
cs249r_book
mlsysim/mlsysim/systems/reliability.py
.py
"""Component MTTF and recovery assumptions (fleet reliability appendix).""" from pydantic import BaseModel, ConfigDict, field_validator from ..core.provenance import Sourced, sourced, fleet_mttf_hours from ..core.registry import Registry from ..core import provenance_catalog as pc class ReliabilityComponent(BaseMod...
148
6,020
cs249r_book
mlsysim/mlsysim/systems/registry.py
.py
from .types import ( CheckpointStoragePath, Fleet, NetworkFabric, Node, NodeStorageConfig, PodEnvelope, RackProfile, StorageSubsystem, ) from .reliability import Reliability from .orchestration import Orchestration as OrchestrationProfile from ..core.units import ureg, Q_, Gbps, GB, TB, ...
432
17,585
cs249r_book
mlsysim/mlsysim/systems/orchestration.py
.py
"""Fleet orchestration scenario parameters (queueing, utilization).""" from pydantic import BaseModel, ConfigDict, Field from ..core.types import Metadata class Orchestration(BaseModel): """Shared cluster scheduling assumptions for scenario calculations.""" model_config = ConfigDict(arbitrary_types_allowed...
16
525
cs249r_book
mlsysim/mlsysim/physics/transformer.py
.py
"""Transformer FLOP accounting identities.""" from __future__ import annotations from mlsysim.core.units import ureg from mlsysim.literature.registry import Literature from ._units import _ensure_unit def calc_transformer_training_flops(n_params, n_tokens): """Training FLOPs for a Transformer (6PD rule, Kaplan...
30
1,253
cs249r_book
mlsysim/mlsysim/physics/reliability.py
.py
"""Reliability, checkpointing, and availability models.""" from __future__ import annotations import math from mlsysim.core.units import ureg from mlsysim.core._validation import ( validate_positive, validate_nonnegative, validate_range, validate_at_least, ) from ._units import _ensure_unit def ca...
171
6,069
cs249r_book
mlsysim/mlsysim/physics/_units.py
.py
"""Shared unit helpers for physics formulas.""" from __future__ import annotations import pint from mlsysim.core.units import ureg def _ensure_unit(val, expected_unit, param_name="Value"): """ Attach a unit if val is a raw number; verify dimensional correctness AND convert to ``expected_unit`` if it is...
36
1,272
cs249r_book
mlsysim/mlsysim/physics/__init__.py
.py
""" Canonical physics and accounting formulas for ML systems. Domain modules: networking, performance, economics, memory, communication, reliability, transformer, serving, statistics """ from ._units import _ensure_unit from .constants import SPEED_OF_LIGHT_FIBER_KM_S from .networking import calc_network_latency_...
126
3,632
cs249r_book
mlsysim/mlsysim/physics/constants.py
.py
"""Universal physical constants (the physics layer's ground truth). These are genuine constants of nature / physical media — not hardware specs, model specs, or tunable knobs — so they live with the laws in ``physics/`` rather than in ``core/constants.py`` (which is now units-only). See the project MLSysIM rules -> Ca...
14
670
cs249r_book
mlsysim/mlsysim/physics/quantities.py
.py
"""Quantity-first formula helpers for LEGO cells — return Pint quantities, never strings.""" from __future__ import annotations import pint from mlsysim.core.units import ( Bparam, byte, count, gram, hour, joule, kilogram, kWh, param, second, ureg, watt, ) __all__ = [...
112
3,843
cs249r_book
mlsysim/mlsysim/physics/networking.py
.py
"""Network latency and distance physics.""" from __future__ import annotations from mlsysim.core.units import ureg from .constants import SPEED_OF_LIGHT_FIBER_KM_S from ._units import _ensure_unit def calc_network_latency_ms(distance_km): """Physical round-trip latency floor for a fiber link. Models only ...
34
1,105
cs249r_book
mlsysim/mlsysim/physics/communication.py
.py
"""Collective communication time models (α–β). All collectives here are pure communication models: the local reduction compute term (γ in Thakur et al. 2005) is deliberately omitted, matching the book's α–β pedagogical treatment. """ from __future__ import annotations import math from mlsysim.core.units import ureg...
421
15,588
cs249r_book
mlsysim/mlsysim/physics/economics.py
.py
"""Fleet economics and cloud cost models.""" from __future__ import annotations from mlsysim.core.units import ureg, DAYS_PER_YEAR from mlsysim.core._validation import validate_nonnegative, validate_positive from ._units import _ensure_unit def calc_monthly_egress_cost(bytes_per_sec, cost_per_gb): """ Calc...
90
3,373
cs249r_book
mlsysim/mlsysim/physics/statistics.py
.py
"""Statistical and workflow propagation helpers.""" from __future__ import annotations import math def calc_population_stability_index(expected, actual, epsilon=1e-12): """Population Stability Index (PSI) between two aligned distributions. Measures distribution drift between a reference ("expected") and an...
91
3,471
cs249r_book
mlsysim/mlsysim/physics/memory.py
.py
"""Model and activation memory accounting.""" from __future__ import annotations import math import pint from mlsysim.core.units import ureg, MB from mlsysim.core._validation import validate_at_least, validate_nonnegative from ._units import _ensure_unit def model_memory(params, bytes_per_param, unit=MB): """...
276
9,606
cs249r_book
mlsysim/mlsysim/physics/performance.py
.py
"""Training time, scaling, roofline, and pipeline performance.""" from __future__ import annotations from mlsysim.core.units import ureg from mlsysim.core._validation import validate_positive, validate_at_least, validate_range def dTime(total_ops, num_devices, peak_flops_per_device, efficiency_eta): """ Cor...
232
8,481
cs249r_book
mlsysim/mlsysim/physics/serving.py
.py
"""Inference serving and queueing models.""" from __future__ import annotations import math from mlsysim.core.units import ureg from ._units import _ensure_unit def calc_queue_latency_mmc(arrival_rate_hz, service_rate_hz, num_servers): """ M/M/c queueing model for inference tail latency (Erlang C). C...
88
4,125
cs249r_book
mlsysim/mlsysim/tools/audit_provenance.py
.py
#!/usr/bin/env python3 """Report missing or weak provenance on registry entries.""" from __future__ import annotations import argparse import sys from datetime import date from typing import Any, Iterable from mlsysim.core.provenance import Provenance, ProvenanceKind, Sourced from mlsysim.datasets.registry import Da...
361
12,439
cs249r_book
mlsysim/mlsysim/engine/pipeline.py
.py
"""Pipeline composer for chaining mlsysim analytical models and solvers. Layer C of the composition architecture: a transparent Pipeline that chains resolvers (models and solvers), validates compatibility, and shows students the full Demand → Supply → Consequence data flow. The Pipeline is NOT a black box — it is an...
175
6,779
cs249r_book
mlsysim/mlsysim/engine/evaluation.py
.py
from pydantic import BaseModel, ConfigDict from typing import Optional, Dict, Any class EvaluationLevel(BaseModel): """A single tier in the Hierarchy of Constraints.""" level_name: str status: str = "PASS" # PASS, FAIL, WARNING summary: str metrics: Dict[str, Any] = {} class SystemEvaluation(BaseM...
242
9,952
cs249r_book
mlsysim/mlsysim/engine/empirical.py
.py
"""Domain-reviewed empirical anchors for MLSysIM sanity checks. These anchors are not solver defaults and do not define model or hardware facts. They bind canonical ``Models.*`` and ``Hardware.*`` entries to sourced ``Literature.Benchmarks`` values so tests can catch formula or registry drift without duplicating the u...
191
7,068
cs249r_book
mlsysim/mlsysim/engine/walls.py
.py
"""The 22 ML Systems Walls — canonical taxonomy. This module is the single source of truth for the wall classification used throughout MLSysIM analyses, papers, and notebooks. Every wall represents a physical or logical constraint that bounds system performance; each is resolved by a dedicated solver. The walls are o...
396
13,570
cs249r_book
mlsysim/mlsysim/engine/calibration.py
.py
"""Parameters for analytical solvers and the roofline engine. These values tune ``mlsysim.engine.solvers`` models and ``mlsysim.engine.engine.Engine`` when callers omit explicit arguments. Use ``Literature.*``, ``Systems.*``, and ``Infrastructure.*`` for sourced domain reference values. """ from ..core.provenance imp...
73
3,404
cs249r_book
mlsysim/mlsysim/engine/scenarios.py
.py
from pydantic import BaseModel, ConfigDict from typing import Optional, Union from ..core.units import Q_ from ..core.types import Quantity from ..models.types import Workload from ..hardware.types import HardwareNode from ..systems.types import Fleet from ..core.exceptions import OOMError, SLAViolation from .evaluatio...
273
10,619
cs249r_book
mlsysim/mlsysim/engine/engine.py
.py
from pydantic import BaseModel, ConfigDict, Field from typing import Optional, List from ..core.units import ureg, Q_, resolve_precision from . import calibration as cal from ..physics import calc_bottleneck from ..core.exceptions import OOMError from ..core._validation import validate_range, validate_at_least from ..m...
401
19,107
cs249r_book
mlsysim/mlsysim/engine/resolver_factory.py
.py
import logging from typing import Type, Dict from .solvers import BaseResolver logger = logging.getLogger(__name__) class ResolverFactory: """ Factory for creating and retrieving Solvers/Models. This acts as the entry point for the Pluggable Solvers interface. It automatically discovers all built...
81
3,024
cs249r_book
mlsysim/mlsysim/engine/explainers.py
.py
import logging from typing import Any logger = logging.getLogger(__name__) class DifferentialExplainer: """ Automates the 'Why did this happen?' analysis by comparing two solver results. It identifies the binding constraints and mathematically explains the performance delta. """ @staticmethod...
68
3,747
cs249r_book
mlsysim/mlsysim/engine/config.py
.py
from pydantic import BaseModel, ConfigDict, Field, model_validator from typing import Dict, Any from ..models.registry import Models from ..hardware.registry import Hardware class SimulationConfig(BaseModel): """ Standard schema for an ML systems analytical modeling run. Can be loaded from YAML, JSON, or P...
56
2,022
cs249r_book
mlsysim/mlsysim/engine/dse.py
.py
from typing import Dict, Any, List, Optional, Callable from pydantic import BaseModel, Field import logging import itertools logger = logging.getLogger(__name__) class SearchSpace(BaseModel): """ Defines the dimensions and discrete bounds of the design space. Example: {"tp": [1, 2, 4, 8], "pp": [1, 2, 4],...
165
6,706
cs249r_book
mlsysim/mlsysim/engine/results.py
.py
"""Typed result models for all mlsysim models and solvers. Layer A of the composition architecture: every resolver returns a typed Pydantic model instead of Dict[str, Any]. This gives students autocomplete, documentation, and type safety when composing analytical models and analysis solvers. """ from __future__ imp...
413
12,758
cs249r_book
mlsysim/mlsysim/engine/solvers/reliability.py
.py
"""Reliability and checkpoint-interval solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations from ..results import ( ReliabilityResult, ) from ...physics...
101
4,076
cs249r_book
mlsysim/mlsysim/engine/solvers/utils.py
.py
from __future__ import annotations from ...systems.types import NetworkFabric, Node def _intra_node_latency(node: Node): """Resolve the per-hop latency for intra-node (NVLink) communication. Implements the instance -> tech-class fallback: prefer the latency on the accelerator's own NVLink spec (instance...
57
1,827
cs249r_book
mlsysim/mlsysim/engine/solvers/distributed.py
.py
"""Distributed training, routing, topology, and parallelism search solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations import math from typing import Option...
711
32,639
cs249r_book
mlsysim/mlsysim/engine/solvers/__init__.py
.py
"""Domain-oriented MLSysIM solver implementations.""" from .base import BaseOptimizer, BaseResolver, BaseSolver, ForwardModel from .compression import CompressionModel from .data import DataModel, TransformationModel from .distributed import DistributedModel, MoERoutingModel, ParallelismOptimizer, TopologyModel from ....
56
1,690
cs249r_book
mlsysim/mlsysim/engine/solvers/training.py
.py
"""Training memory, checkpointing, and scaling-law solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations import math from typing import Optional from ..resul...
357
16,165
cs249r_book
mlsysim/mlsysim/engine/solvers/data.py
.py
"""Data-ingestion and preprocessing pipeline solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations from ..results import ( DataResult, Transformation...
150
6,072
cs249r_book
mlsysim/mlsysim/engine/solvers/orchestration.py
.py
"""Cluster orchestration and queueing solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations from ..results import ( OrchestrationResult, ) from ...core.u...
83
3,014
cs249r_book
mlsysim/mlsysim/engine/solvers/compression.py
.py
"""Model compression trade-off solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations import math from typing import Any, Dict, List, Optional from ..results ...
387
16,915
cs249r_book
mlsysim/mlsysim/engine/solvers/economics.py
.py
"""Sustainability, economics, responsible-engineering, and placement solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations from typing import Any, List, Optio...
425
18,721
cs249r_book
mlsysim/mlsysim/engine/solvers/base.py
.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import Any, Dict, Optional, Type from ..results import SolverResult class BaseResolver(ABC): """Base class for all mlsysim analytical components (Models, Solvers, Optimizers). Each resolver declares its input requirements and...
88
2,953
cs249r_book
mlsysim/mlsysim/engine/solvers/performance.py
.py
"""Single-node, network-roofline, efficiency, and inverse-design solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations from ..engine import Engine, Performan...
457
20,418
cs249r_book
mlsysim/mlsysim/engine/solvers/serving.py
.py
"""LLM serving, batching, tail-latency, and inference-scaling solvers. Domain implementations behind ``mlsysim.solvers`` (the public import path, derived from ``engine.solvers.__init__``); kept per-domain so the logic stays reviewable. """ from __future__ import annotations import math from typing import Optional f...
1,011
49,940
cs249r_book
mlsysim/mlsysim/datasets/types.py
.py
from pydantic import BaseModel, ConfigDict, Field, field_validator from typing import Optional from ..core.units import ureg from ..core.types import Metadata, Quantity, require_dimensionality, require_unit_family class DatasetProfile(BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True, extra="for...
45
1,827
cs249r_book
mlsysim/mlsysim/datasets/__init__.py
.py
"""Dataset zoo — canonical data corpus profiles.""" from .registry import Datasets from .types import DatasetProfile __all__ = ["Datasets", "DatasetProfile"]
7
162
cs249r_book
mlsysim/mlsysim/datasets/registry.py
.py
"""Dataset registry — dataset profiles. Leaf reference data (example counts, image dimensions, class counts) lives as YAML under ``datasets/data/<Dataset>.yaml`` and is loaded + validated against the ``DatasetProfile`` schema at import (see ``core/loader.py`` and the project MLSysIM rules → *Storage format*). """ from...
19
577
cs249r_book
mlsysim/mlsysim/platforms/types.py
.py
from pydantic import BaseModel, ConfigDict, Field, field_validator from ..core.units import ureg from ..core.types import Metadata, Quantity, require_dimensionality, require_unit_family class PlatformEnvelope(BaseModel): """Abstract deployment envelope (RAM, storage, latency budget).""" model_config = Confi...
58
1,948
cs249r_book
mlsysim/mlsysim/platforms/__init__.py
.py
"""Platform deployment envelopes.""" from .registry import Platforms from .types import PlatformEnvelope __all__ = ["Platforms", "PlatformEnvelope"]
7
151
cs249r_book
mlsysim/mlsysim/platforms/registry.py
.py
"""Deployment paradigm envelopes (Cloud, Edge, Mobile, TinyML).""" from ..core.units import ( GB, GiB, KiB, MB, PFLOP, TB, TFLOPs, TOPS, milliwatt, second, ureg, ) from ..core.registry import Registry from ..core.types import Metadata from ..core import provenance_catalog as...
86
2,561
cs249r_book
mlsysim/mlsysim/viz/plots.py
.py
# viz/plots.py # Simulator-aware plotters for generated MLSysIM figures. # Book publication style is owned by book.tools.figures.style; this module keeps # a local fallback so standalone mlsysim installs do not depend on the book tree. import os try: import numpy as np except ImportError: np = None try: ...
492
15,117
cs249r_book
mlsysim/mlsysim/core/types.py
.py
from typing import Any, Annotated, Optional from pydantic import AfterValidator, PlainSerializer, BaseModel, ConfigDict from .units import Q_ from .provenance import Provenance def validate_quantity(v: Any) -> Q_: if isinstance(v, Q_): return v if isinstance(v, (int, float, str)): try: ...
119
4,269
cs249r_book
mlsysim/mlsysim/core/exceptions.py
.py
# Exceptions for the MLSys Simulator class MLSysError(Exception): """Base exception for all mlsysim simulation errors.""" pass class OOMError(MLSysError): """Raised when a workload's memory footprint exceeds the hardware capacity.""" def __init__(self, message, required_bytes=None, available_bytes=Non...
21
723
cs249r_book
mlsysim/mlsysim/core/_validation.py
.py
"""Input validation helpers for mlsysim formulas and solvers. These guards catch common student mistakes (zero bandwidth, negative efficiency, n_gpus=0) before they produce confusing inf/nan results or crash with unhelpful error messages. """ def validate_positive(val, name: str): """Ensure a numeric value is st...
35
1,163
cs249r_book
mlsysim/mlsysim/core/provenance.py
.py
"""Provenance types for registry entries and public sourced scalars.""" from __future__ import annotations from datetime import date from enum import Enum from typing import Optional, Union from pydantic import BaseModel, ConfigDict, Field, model_validator Scalar = Union[int, float] class ProvenanceKind(str, Enum...
199
7,232
cs249r_book
mlsysim/mlsysim/core/loader.py
.py
"""YAML data-layer loader. Leaf reference data (hardware chips, models, datasets, …) lives as YAML and is loaded + validated against a pydantic schema at import, then assembled into a ``Registry`` subclass whose consumer API is identical to the former hand-written Python registry (``Hardware.Cloud.H100.memory.bandwidt...
214
9,000
cs249r_book
mlsysim/mlsysim/core/units.py
.py
# units.py # Measurement infrastructure for the ML Systems simulator. # This module owns the pint unit registry and defines all unit aliases. # It contains ONLY measurement plumbing — no domain knowledge or tuneable defaults. from pathlib import Path import pint __all__ = [ # Registry and Quantity constructor ...
275
8,303
cs249r_book
mlsysim/mlsysim/core/provenance_catalog.py
.py
"""Shared provenance records (stable ids, single definition).""" from __future__ import annotations from .provenance import Provenance, ProvenanceKind def _ds( id: str, ref: str, url: str, *, verified: str = "2026-03-06", notes: str | None = None, ) -> Provenance: """Creates a Provenance...
961
35,739
cs249r_book
mlsysim/mlsysim/core/registry/plugin_manager.py
.py
import logging from typing import Dict, Any, TypeVar import importlib.metadata logger = logging.getLogger(__name__) T = TypeVar('T') class Registry: """ A generic plugin registry that dynamically discovers and loads classes or constants from Python entry_points, allowing third parties to inject custom ha...
61
2,180
cs249r_book
mlsysim/mlsysim/core/registry/__init__.py
.py
from typing import ClassVar, List, Any, Optional from .plugin_manager import hardware_registry, model_registry, constants_registry from .plugin_manager import Registry as PluginRegistry class Registry: """ Base class for registries that provides a coherent way to list and sort items. Used by Hardware, Mo...
75
2,462
cs249r_book
mlsysim/mlsysim/core/optimization/__init__.py
.py
from .protocol import OptimizerProtocol, OptimizationResult __all__ = [ "OptimizerProtocol", "OptimizationResult", "OptimizationRegistry", ] def __getattr__(name): if name == "OptimizationRegistry": from .registry import OptimizationRegistry return OptimizationRegistry raise Attri...
15
380
cs249r_book
mlsysim/mlsysim/core/optimization/scipy_backend.py
.py
import time from typing import Any, Callable, Optional, Tuple import scipy.optimize from .protocol import OptimizerProtocol, OptimizationResult class ScipyBackend(OptimizerProtocol): """ A continuous optimization backend using SciPy. Best suited for finding optimal continuous system variables (like co...
74
2,974
cs249r_book
mlsysim/mlsysim/core/optimization/registry.py
.py
from .protocol import OptimizerProtocol def _load_scipy_backend(): """Lazy-loads the SciPy optimization backend.""" try: from .scipy_backend import ScipyBackend return ScipyBackend except ImportError: raise ImportError( "SciPy is required for continuous optimization. " ...
61
2,101
cs249r_book
mlsysim/mlsysim/core/optimization/protocol.py
.py
from typing import Protocol, Any, Dict from pydantic import BaseModel class OptimizationResult(BaseModel): """Standardized output from any solver backend (SciPy, OR-Tools, etc.)""" feasible: bool optimal_value: float best_configuration: Dict[str, Any] metrics: Dict[str, Any] solver_name: str ...
23
742
cs249r_book
mlsysim/mlsysim/core/optimization/exhaustive_backend.py
.py
import time from typing import Any, Callable, List, Tuple import numpy as np from .protocol import OptimizerProtocol, OptimizationResult class ExhaustiveBackend(OptimizerProtocol): """ A brute-force grid search backend using only NumPy. Evaluates the objective at every point on a uniform grid and returns...
77
3,019
cs249r_book
mlsysim/mlsysim/core/optimization/ortools_backend.py
.py
import time from typing import Any, Callable, Dict from ortools.sat.python import cp_model from .protocol import OptimizerProtocol, OptimizationResult class ORToolsDiscreteBackend(OptimizerProtocol): """ A discrete optimization backend using Google OR-Tools CP-SAT. Best suited for finding optimal integer c...
78
3,250