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 | mlsysim/mlsysim/labs/state.py | .py | # mlsysim/labs/state.py
# Persistent state management for the MLSys Design Ledger.
# Handles CLI (Local File) and Web (Browser IndexedDB) persistence.
import json
import sys
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import Optional, Dict, Any
@dataclass
class LedgerState:
... | 426 | 13,079 |
cs249r_book | mlsysim/mlsysim/labs/__init__.py | .py | # mlsysim/labs/__init__.py
"""
Lab UI toolkit for the MLSys Co-Labs curriculum.
Provides the Design Ledger (persistent student state), visual style system,
and reusable UI components. Every Marimo lab notebook imports from here.
"""
from .state import DesignLedger, LedgerState
from .style import (
COLORS,
LAB... | 51 | 1,021 |
cs249r_book | mlsysim/mlsysim/labs/components.py | .py | # labs/core/components.py
import marimo as mo
from .style import COLORS, apply_plotly_theme
def Card(title, content):
return mo.Html(f"""
<div class="lab-card">
<h3>{title}</h3>
<div style="flex-grow: 1;">{content}</div>
</div>
""")
def MetricRow(label, value, sub_value=""):
return... | 371 | 14,511 |
cs249r_book | mlsysim/mlsysim/labs/style.py | .py | # mlsysim/labs/style.py
# MLSys Labs β Unified Design System
#
# USAGE:
# from mlsysim.labs.style import COLORS, LAB_CSS, progress_bar, concept_header
# Always inject LAB_CSS once at the top of every lab (in the header cell).
# Use CSS class names from this file β never write inline style= for structural elements... | 665 | 22,075 |
cs249r_book | mlsysim/mlsysim/ops/monitoring.py | .py | """MLOps monitoring thresholds (drift, stability)."""
from ..core.provenance import sourced
from ..core.registry import Registry
from ..core import provenance_catalog as pc
class Monitoring(Registry):
MemoryBitErrorRatePerBit = sourced(
1e-17,
pc.MEMORY_SOFT_ERROR_RATE,
name="Memory soft-... | 39 | 1,283 |
cs249r_book | mlsysim/mlsysim/ops/runtime.py | .py | """Software runtime and framework overhead assumptions."""
from ..core import provenance_catalog as pc
from ..core.provenance import sourced, sourced_qty
from ..core.registry import Registry
from ..core.units import ureg
class RuntimeOverheads(Registry):
"""Reusable software-runtime latency anchors for framework... | 47 | 1,643 |
cs249r_book | mlsysim/mlsysim/ops/__init__.py | .py | from .registry import Ops
__all__ = ["Ops"]
| 4 | 45 |
cs249r_book | mlsysim/mlsysim/ops/training.py | .py | """Operational training-run profiles and overhead assumptions."""
from ..core.provenance import sourced
from ..core.registry import Registry
from ..core import provenance_catalog as pc
class TrainingRunOverheads(Registry):
"""Reusable goodput-loss fractions for large distributed training runs."""
PipelineBu... | 35 | 1,099 |
cs249r_book | mlsysim/mlsysim/ops/registry.py | .py | """MLOps assumption registries (monitoring thresholds, drift detection)."""
from ..core.registry import Registry
from .monitoring import Monitoring
from .runtime import MemoryProtection, RuntimeOverheads
from .training import TrainingRunOverheads
class Ops(Registry):
"""Registry namespace for Ops."""
Monitor... | 15 | 465 |
cs249r_book | mlsysim/mlsysim/cli/interviewer.py | .py | import json
import random
from pathlib import Path
from typing import Optional
from pydantic import BaseModel
class Question(BaseModel):
id: str
track: str
scope: str
level: str
title: str
topic: str
scenario: str
details: dict
class InterviewCorpus:
def __init__(self, corpus_path:... | 80 | 2,330 |
cs249r_book | mlsysim/mlsysim/cli/main.py | .py | import typer
from mlsysim.cli.commands.zoo import zoo_main
from mlsysim.cli.commands.eval import evaluate_main
from mlsysim.cli.commands.serve import serve_main
from mlsysim.cli.commands.schema import schema_main
from mlsysim.cli.commands.optimize import optimize_app
from mlsysim.cli.commands.audit import audit_main
f... | 43 | 1,779 |
cs249r_book | mlsysim/mlsysim/cli/exceptions.py | .py | from enum import IntEnum
import sys
from contextlib import contextmanager
class ExitCode(IntEnum):
"""Semantic exit codes for CLI automation."""
SUCCESS = 0
BAD_INPUT = 1 # Syntax Error, Typo, Validation Failure
PHYSICS_FAIL = 2 # Out of Memory, Pipeline Starved (Hardware Limitation)
SLA_FAI... | 44 | 1,741 |
cs249r_book | mlsysim/mlsysim/cli/context.py | .py | """Shared CLI context helpers."""
from __future__ import annotations
from typing import Optional
import typer
SUPPORTED_OUTPUT_FORMATS = ("text", "json", "markdown", "html")
OUTPUT_FORMAT_HELP = "Output format (text, json, markdown; html where supported)"
def validate_output_format(value: Optional[str], supporte... | 47 | 1,581 |
cs249r_book | mlsysim/mlsysim/cli/schemas.py | .py | from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator, model_validator
from typing import Optional, Any, List
import yaml
from pathlib import Path
from mlsysim.core.units import Q_, ureg
from mlsysim.core.types import Quantity, require_unit_family
from mlsysim.core.units import normalize_prec... | 249 | 9,801 |
cs249r_book | mlsysim/mlsysim/cli/renderers.py | .py | import json
from typing import Any
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
# Strict I/O Purity (Guideline 1)
console_err = Console(stderr=True) # All diagnostics, warnings, UI go to stderr
console_out = Console() # stdout is reserved for the final payload
... | 293 | 13,879 |
cs249r_book | mlsysim/mlsysim/cli/commands/audit.py | .py | import typer
import platform
import subprocess
import shutil
from typing import Optional
from mlsysim.cli.context import OUTPUT_FORMAT_HELP, resolve_output_format
from mlsysim.cli.exceptions import error_shield
from mlsysim.cli.schemas import _resolve_model
from mlsysim.cli.renderers import print_json
from mlsysim.show... | 141 | 5,881 |
cs249r_book | mlsysim/mlsysim/cli/commands/optimize.py | .py | import typer
from pathlib import Path
from typing import Optional
import yaml
from mlsysim.cli.context import OUTPUT_FORMAT_HELP, resolve_output_format
from mlsysim.cli.schemas import MlsysPlanSchema
from mlsysim.cli.exceptions import ExitCode, exit_with_code, error_shield
from mlsysim.cli.renderers import render_optim... | 123 | 5,077 |
cs249r_book | mlsysim/mlsysim/cli/commands/schema.py | .py | import typer
import json
from typing import Optional
from mlsysim.cli.context import OUTPUT_FORMAT_HELP, resolve_output_format
from mlsysim.cli.schemas import MlsysPlanSchema
from mlsysim.hardware.types import HardwareNode
from mlsysim.models.types import Workload
from mlsysim.cli.exceptions import ExitCode, error_shie... | 33 | 1,441 |
cs249r_book | mlsysim/mlsysim/cli/commands/zoo.py | .py | import typer
from typing import Optional
from mlsysim.cli.context import OUTPUT_FORMAT_HELP, resolve_output_format
from mlsysim.cli.exceptions import ExitCode, exit_with_code, error_shield
from mlsysim.cli.renderers import render_zoo_table
from mlsysim.hardware.registry import Hardware
from mlsysim.models.registry impo... | 37 | 1,727 |
cs249r_book | mlsysim/mlsysim/cli/commands/eval.py | .py | import typer
from pathlib import Path
import yaml
from typing import Any, Optional
from mlsysim.cli.context import OUTPUT_FORMAT_HELP, resolve_output_format
from mlsysim.cli.schemas import EvalNodeSchema, MlsysPlanSchema
from mlsysim.cli.exceptions import ExitCode, exit_with_code, error_shield
from mlsysim.cli.renderer... | 158 | 7,710 |
cs249r_book | mlsysim/mlsysim/cli/commands/serve.py | .py | import typer
from typing import Optional
from mlsysim.cli.context import OUTPUT_FORMAT_HELP, resolve_output_format
from mlsysim.cli.schemas import _resolve_model, _resolve_hardware
from mlsysim.cli.exceptions import error_shield, ExitCode, exit_with_code
from mlsysim.cli.renderers import print_json
from mlsysim.models.... | 127 | 6,216 |
cs249r_book | mlsysim/mlsysim/infrastructure/types.py | .py | from typing import Any, Optional
from pydantic import BaseModel, ConfigDict, Field
from ..core.types import Metadata
class GridProfile(BaseModel):
"""
Layer C (Infrastructure Context): Represents a regional power grid.
A GridProfile defines the environmental constraints of a physical location,
s... | 89 | 3,009 |
cs249r_book | mlsysim/mlsysim/infrastructure/registry.py | .py | from pathlib import Path
from .types import GridProfile, RackProfile, Datacenter, CoolingProfile
from ..core.provenance import sourced
from ..core.registry import Registry
from ..core.loader import load_collection
from ..core.types import Metadata
from ..core import provenance_catalog as pc
# --- Facility cooling tie... | 119 | 5,834 |
cs249r_book | mlsysim/mlsysim/infrastructure/capacity.py | .py | """Datacenter and grid build-out lead times."""
from ..core.provenance import sourced
from ..core.registry import Registry
from ..core import provenance_catalog as pc
class Capacity(Registry):
GpuLeadTimeMonths = sourced(6, pc.CAPACITY_LEAD_TIMES, name="GPU lead time (months)", description="Typical GPU procureme... | 12 | 672 |
cs249r_book | mlsysim/mlsysim/infrastructure/pricing.py | .py | """Cloud, storage, labeling, and fleet economics (2024 illustrative baselines)."""
from ..core.units import USD, ureg, GB, TB, hour
from ..core.registry import Registry
from ..core.types import Metadata
from ..core import provenance_catalog as pc
from .types import PricePoint
_CLOUD = Metadata(provenance=pc.CLOUD_PRI... | 192 | 5,982 |
cs249r_book | mlsysim/mlsysim/literature/__init__.py | .py | from .registry import Literature
__all__ = ["Literature"]
| 4 | 59 |
cs249r_book | mlsysim/mlsysim/literature/registry.py | .py | """Published literature anchors used by MLSysIM (MFU, Chinchilla, benchmarks, ...).
Each anchor is a provenance-carrying scalar; the values live as YAML under
``literature/data/<category>.yaml`` and are loaded via ``load_sourced_registry``
(provenance referenced by catalog key). See the project MLSysIM rules β
*Storag... | 179 | 7,655 |
cs249r_book | mlsysim/mlsysim/sim/simulations.py | .py | # simulations.py
"""
MLSys Analytical Simulations
============================
This module provides domain-specific analytical solvers for lab simulations.
Each simulation class implements the 'Physics' of a specific engineering domain.
"""
from dataclasses import dataclass
from typing import Dict, Any
from ..core.uni... | 129 | 5,770 |
cs249r_book | mlsysim/mlsysim/sim/__init__.py | .py | # mlsysim.sim β The ML Systems Simulator Sub-package
from .personas import Persona, Personas
from .simulations import BaseSimulation, ResourceSimulation
from .ledger import (
SystemLedger,
PerformanceMetrics,
SustainabilityMetrics,
EconomicMetrics,
ReliabilityMetrics
)
| 12 | 297 |
cs249r_book | mlsysim/mlsysim/sim/personas.py | .py | # personas.py
"""
MLSys Personas
==============
Defines the Persona Archetypes (the rows of the lab matrix).
Each persona defines the scale multiplier and the primary engineering constraint
for a specific real-world deployment tier.
"""
from dataclasses import dataclass
@dataclass(frozen=True)
class Persona:
"""
... | 92 | 3,001 |
cs249r_book | mlsysim/mlsysim/sim/ledger.py | .py | # ledger.py
"""
MLSys Scorecard Module
======================
The multi-dimensional 'Scorecard' for MLSys simulations.
It tracks metrics across four primary engineering axes:
Performance, Sustainability, Economics, and Reliability.
"""
from dataclasses import dataclass
from typing import Dict, Any
from ..core.units i... | 85 | 2,671 |
cs249r_book | mlsysim/mlsysim/models/types.py | .py | from pydantic import BaseModel, ConfigDict, Field, field_validator
from typing import Optional
from ..core.units import ureg, BYTES_FP16
from ..core.types import (
Quantity,
Metadata,
require_dimensionality,
require_unit_family,
require_unit_families,
)
class ComputationGraph(BaseModel):
"""
... | 400 | 17,413 |
cs249r_book | mlsysim/mlsysim/models/registry.py | .py | """Model registry β workload (model) specs.
Per-category data (params, FLOPs, training figures) lives as YAML under
``models/data/<category>.yaml`` and is loaded + validated against the
``Workload`` family at import (see ``core/loader.py``). Each entry carries a
``__type__`` selecting the concrete workload class (Tran... | 50 | 1,902 |
cs249r_book | mlsysim/mlsysim/models/importer.py | .py | import json
import urllib.request
import urllib.error
import time
import warnings
from typing import Optional
import logging
from .types import TransformerWorkload
from ..core.units import ureg
logger = logging.getLogger(__name__)
def fetch_hf_config(model_id: str, max_retries: int = 3, timeout: int = 10) -> dict:
... | 130 | 5,789 |
cs249r_book | mlsysim/mlsysim/reference_stats/__init__.py | .py | from .registry import ReferenceStats
__all__ = ["ReferenceStats"]
| 4 | 67 |
cs249r_book | mlsysim/mlsysim/reference_stats/registry.py | .py | """Reference statistics for real-world scenarios and case studies.
This registry is the home for reusable real-world reference figures:
illustrative scale anchors (Gmail volume, Waymo sensor rate) and case-study model
metrics (the TinyML anomaly detector). Every value carries sourced() provenance.
Note: *evaluatable*... | 731 | 30,949 |
cs249r_book | mlsysim/mlsysim/hardware/types.py | .py | from pydantic import BaseModel, ConfigDict, Field, field_validator
from typing import Optional, Dict, Literal
from ..core.units import Q_, ureg
from ..core.types import Quantity, Metadata, require_dimensionality, require_unit_family
class ComputeCore(BaseModel):
"""
Represents the processing units of a hardwar... | 242 | 10,486 |
cs249r_book | mlsysim/mlsysim/hardware/tech.py | .py | """Hardware technology-class reference facts (exposed as ``Hardware.Tech``).
Technology-CLASS properties β access latency, per-operation/per-byte energy, and generic
component bandwidth β that are ~constant across parts of a generation. This is the
counterpart to the per-instance specs on the Hardware.Cloud/Edge/Mobil... | 174 | 6,670 |
cs249r_book | mlsysim/mlsysim/hardware/registry.py | .py | """Hardware registry β accelerator/device instances.
Per-instance specs (capacity, bandwidth, TDP, price, counts) live as YAML data
under ``hardware/data/<tier>/<Chip>.yaml`` and are loaded + validated against the
``HardwareNode`` schema at import (see ``core/loader.py`` and
the project MLSysIM rules β *Canonical orga... | 53 | 2,049 |
cs249r_book | mlsysim/tests/test_scipy_backend.py | .py | import pytest
pytest.importorskip("scipy", reason="scipy not installed (optional dependency)")
from mlsysim.core.optimization.scipy_backend import ScipyBackend
def test_scipy_continuous_optimization():
"""
Test that the SciPy backend can analytically find the optimal batch size
to maximize throughput (a ... | 60 | 2,164 |
cs249r_book | mlsysim/tests/test_ops_registry.py | .py | from __future__ import annotations
import pytest
from mlsysim import Ops
def test_runtime_overhead_latency_profiles():
assert Ops.RuntimeOverheads.PythonDispatch.to("microsecond").magnitude == pytest.approx(10)
assert Ops.RuntimeOverheads.KernelLaunch.to("microsecond").magnitude == pytest.approx(5)
asse... | 18 | 672 |
cs249r_book | mlsysim/tests/test_evaluation_contract.py | .py | import pytest
import subprocess
import sys
from pathlib import Path
from mlsysim.engine.evaluation import SystemEvaluator
from mlsysim.hardware.registry import Hardware
from mlsysim.models.registry import Models
from mlsysim import Q_, Scenarios, plot_evaluation_scorecard
from mlsysim.systems.registry import Systems
... | 110 | 3,390 |
cs249r_book | mlsysim/tests/test_provenance_audit.py | .py | import unittest
from mlsysim.tools.audit_provenance import (
audit_datasets,
audit_hardware_tech,
audit_infra_capacity,
audit_infra_facilities,
audit_infra_grids,
audit_infra_pricing,
audit_literature_sourced,
audit_ops_sourced,
audit_platforms,
audit_reference_stats,
audit_... | 79 | 2,616 |
cs249r_book | mlsysim/tests/test_provenance.py | .py | import unittest
from pydantic import ValidationError
from mlsysim.core.provenance import Provenance, ProvenanceKind, Sourced
from mlsysim.hardware.registry import Hardware
from mlsysim.infrastructure.registry import Infrastructure
from mlsysim.systems.reliability import Reliability
class TestProvenance(unittest.Test... | 72 | 2,486 |
cs249r_book | mlsysim/tests/test_lego_unit_invariants.py | .py | """Golden invariants for LEGO unit discipline."""
from __future__ import annotations
import pytest
from mlsysim.core.units import (
Bparam,
GB,
GiB,
Q_,
TB,
TFLOP,
byte,
hour,
kWh,
metric_ton,
MWh,
second,
watt,
)
from mlsysim.hardware.registry import Hardware
from... | 66 | 1,636 |
cs249r_book | mlsysim/tests/test_golden_regressions.py | .py | import pytest
import mlsysim
from mlsysim.core.units import Q_
from mlsysim.engine.solvers import (
DistributedModel,
EconomicsModel,
ServingModel,
SingleNodeModel,
SustainabilityModel,
TrainingMemoryModel,
)
from mlsysim.physics import calc_bottleneck
def test_golden_roofline_resnet50_a100_b... | 188 | 8,278 |
cs249r_book | mlsysim/tests/test_exhaustive_backend.py | .py | import pytest
from mlsysim.core.optimization.registry import OptimizationRegistry
def test_exhaustive_backend():
backend = OptimizationRegistry.get_backend("exhaustive")
# A function that hits a "wall" at x=42 and goes to infinity
def objective(x_array):
x = x_array[0]
if x < 42:
... | 35 | 1,175 |
cs249r_book | mlsysim/tests/test_standalone_taxonomy.py | .py | from __future__ import annotations
from pathlib import Path
PACKAGE_ROOT = Path(__file__).resolve().parents[1] / "mlsysim"
def test_package_provenance_ids_do_not_use_book_namespace():
"""MLSysIM package data should name provenance by domain, not by consumer."""
offenders: list[str] = []
for path in PAC... | 23 | 697 |
cs249r_book | mlsysim/tests/test_engine.py | .py | # tests/test_engine.py
# Engine-level tests β covers the core Engine.solve() API.
#
# Note: Comprehensive solver tests are in test_solver_suite.py (TestSingleNodeModel).
# This file tests Engine-specific behavior not covered there.
import pytest
from mlsysim.engine.engine import Engine
from mlsysim.hardware.registry i... | 122 | 5,749 |
cs249r_book | mlsysim/tests/test_registry_loader_contract.py | .py | from __future__ import annotations
import pickle
import pytest
from pydantic import BaseModel, ConfigDict, ValidationError
import mlsysim
from mlsysim import Hardware, Models
from mlsysim.core.loader import load_collection, load_registry
from mlsysim.hardware.types import HardwareNode
class _Entry(BaseModel):
... | 112 | 3,618 |
cs249r_book | mlsysim/tests/test_sota.py | .py | import pytest
from mlsysim.models.types import TransformerWorkload
from mlsysim.hardware.registry import Hardware
from mlsysim.systems.registry import Systems
from mlsysim.engine.solvers import DistributedModel, ServingModel
from mlsysim.core.units import Q_
# Cross-solver integration tests combining multiple features... | 80 | 2,655 |
cs249r_book | mlsysim/tests/test_schema_units.py | .py | import pytest
from pydantic import ValidationError
from mlsysim.core.units import Q_, ureg
from mlsysim.hardware.types import ComputeCore, MemoryHierarchy
from mlsysim.models.types import TransformerWorkload
from mlsysim.systems.types import NetworkFabric
def test_memory_capacity_requires_storage_units():
with p... | 62 | 2,096 |
cs249r_book | mlsysim/tests/test_constants_allowlist.py | .py | """CI gate: core/constants.py stays DELETED β units live in core/units.py only.
History: the taxonomy refactor (2026-05) reduced this module to a units-only
re-export; the no-backward-compat sweep (2026-06-06) deleted it outright and
migrated every consumer (package, tests, book LEGO cells, docs, tools) to
``mlsysim.c... | 37 | 1,526 |
cs249r_book | mlsysim/tests/test_compression_candidates.py | .py | from __future__ import annotations
import pytest
from mlsysim.engine.results import CompressionCandidate, CompressionSweepResult
from mlsysim.hardware.registry import Hardware
from mlsysim.models.registry import Models
from mlsysim.solvers import CompressionModel
def test_candidate_records_feasible_source_traced_in... | 73 | 2,643 |
cs249r_book | mlsysim/tests/test_registry_no_duplicate_specs.py | .py | """CI gate: registry entries must not duplicate hardware interconnect specs."""
from __future__ import annotations
from mlsysim.hardware.registry import Hardware
from mlsysim.systems.registry import Systems
def _qty_equal(a, b) -> bool:
return abs(a.m_as("byte/second") - b.m_as("byte/second")) < 1e-6
def test... | 53 | 2,133 |
cs249r_book | mlsysim/tests/test_doc_registry_paths.py | .py | """CI gate: website docs must use canonical registry paths and valid top-level imports."""
from __future__ import annotations
import ast
import re
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
MLSYSIM_ROOT = REPO_ROOT / "mlsysim"
SCAN_ROOTS = (
MLSYSIM_ROOT / "docs",
MLSYSIM_ROOT ... | 144 | 4,394 |
cs249r_book | mlsysim/tests/test_hardware.py | .py | import pytest
from pydantic import ValidationError
from mlsysim.hardware import Hardware, HardwareNode
from mlsysim.core.units import Q_, ureg
def test_hardware_registry():
a100 = Hardware.Cloud.A100
assert a100.name == "NVIDIA A100"
assert a100.release_year == 2020
assert a100.compute.peak_flops.magni... | 179 | 8,002 |
cs249r_book | mlsysim/tests/test_solver_suite.py | .py | """
Comprehensive solver test suite for mlsysim.
Tests physics-level correctness of all solvers: SingleNode, Serving,
Sustainability, Data, Scaling, Orchestration, Compression, and
verifies constants module backward compatibility.
"""
import math
import pytest
# All tests in this file are solver-level correctness te... | 1,762 | 78,951 |
cs249r_book | mlsysim/tests/test_units_registry.py | .py | """Characterization tests for MLSysIM Pint registry and unit aliases."""
from __future__ import annotations
import pytest
from mlsysim.core.units import (
Bparam,
GB,
GFLOPs,
GW,
GiB,
KiB,
Gbps,
Kparam,
L,
MB,
Mparam,
MJ,
MS,
NS,
PFLOP,
Q_,
TB,
... | 299 | 11,217 |
cs249r_book | mlsysim/tests/test_walls.py | .py | """
Unit tests for mlsysim.engine.walls β the 22 ML Systems Wall taxonomy.
Validates registry completeness, lookup helpers, and data integrity.
"""
import pytest
from mlsysim.engine.walls import (
ALL_WALLS,
COMPUTE,
Domain,
Wall,
taxonomy,
wall,
walls_for_resolver,
walls_in_domain,
)... | 106 | 2,894 |
cs249r_book | mlsysim/tests/test_solver_module_exports.py | .py | import importlib
import pytest
import mlsysim
import mlsysim.ops as ops
import mlsysim.solvers as public_solvers
import mlsysim.engine.solvers as engine_solvers
def test_engine_solver_shim_stays_deleted():
# 2026-06-06 no-backward-compat policy: the middle re-export module
# (mlsysim.engine.solver) was remo... | 57 | 2,193 |
cs249r_book | mlsysim/tests/test_pipeline.py | .py | """
Unit tests for mlsysim.engine.pipeline β the Pipeline composer.
Tests construction, validation, explain(), run(), and repr.
"""
import pytest
from mlsysim.engine.pipeline import Pipeline, CompositionError
from mlsysim.engine.solvers import SingleNodeModel
from mlsysim.hardware.registry import Hardware
from mlsys... | 77 | 2,459 |
cs249r_book | mlsysim/tests/test_quantity_formulas.py | .py | """Tests for quantity-first physics helpers."""
from __future__ import annotations
import pytest
import pint
from mlsysim.core.units import (
Bparam,
GB,
Q_,
TB,
TFLOP,
byte,
count,
gram,
hour,
kWh,
metric_ton,
MWh,
param,
second,
ureg,
watt,
)
from mls... | 73 | 1,794 |
cs249r_book | mlsysim/tests/test_datasets.py | .py | import pytest
from mlsysim import Datasets
from mlsysim.core.units import byte, second
def test_mswc_audio_encoding_is_registry_backed():
mswc = Datasets.MSWC
assert mswc.sample_duration.to(second).magnitude == pytest.approx(1.0)
assert mswc.sample_rate.to(1 / second).magnitude == pytest.approx(16_000.0... | 13 | 392 |
cs249r_book | mlsysim/tests/test_ortools_backend.py | .py | import pytest
ortools = pytest.importorskip("ortools", reason="ortools not installed (optional dependency)")
from mlsysim.core.optimization.ortools_backend import ORToolsDiscreteBackend
from ortools.sat.python import cp_model
def test_ortools_parallelism_split():
"""
Test that the OR-Tools backend can instant... | 65 | 2,503 |
cs249r_book | mlsysim/tests/test_infrastructure_registry.py | .py | import pytest
from mlsysim import Infrastructure
def test_facility_cooling_pue_profiles():
assert Infrastructure.FacilityCooling.Legacy.pue == pytest.approx(1.58)
assert Infrastructure.FacilityCooling.StateOfArt.pue == pytest.approx(1.10)
assert Infrastructure.FacilityCooling.SimpleAir.pue == pytest.appr... | 15 | 562 |
cs249r_book | mlsysim/tests/test_formulas.py | .py | """
Unit tests for mlsysim.physics β known-answer tests for every formula.
Each test uses hand-computed expected values and pytest.approx for
floating-point comparisons.
"""
import math
import pytest
import pint
from mlsysim.physics import (
_ensure_unit,
calc_network_latency_ms,
calc_alpha_beta_crossove... | 985 | 39,640 |
cs249r_book | mlsysim/tests/test_system_registry.py | .py | from __future__ import annotations
import pytest
from mlsysim import Systems
from mlsysim.core.units import GB, MW, TB, bit, kilowatt, pJ, second
def test_reference_25k_h100_cluster_totals():
fleet = Systems.Clusters.Reference_25K_H100
assert fleet.count == 3125
assert fleet.node.accelerators_per_node ... | 116 | 4,972 |
cs249r_book | mlsysim/tests/test_solver_invariants.py | .py | import pytest
import mlsysim
from mlsysim.core.units import Q_
from mlsysim.engine.solvers import (
DistributedModel,
EconomicsModel,
ServingModel,
SustainabilityModel,
TrainingMemoryModel,
)
def test_precision_memory_is_monotonic_for_model_weights():
model = mlsysim.Models.Language.Llama3_8B... | 135 | 4,126 |
cs249r_book | mlsysim/tests/test_infrastructure_pricing.py | .py | from __future__ import annotations
import pytest
from mlsysim import Infrastructure
from mlsysim.core.units import GB, USD, ureg
def test_storage_pricing_round_number_anchors():
s3_low = Infrastructure.Pricing.Storage.S3StandardLowPerTbMonth.rate
glacier = Infrastructure.Pricing.Storage.GlacierStandardPerTb... | 23 | 861 |
cs249r_book | mlsysim/tests/test_fmt.py | .py | """Tests for mlsysim.fmt formatting guards."""
import pytest
from mlsysim.core.units import ureg
from mlsysim.core.units import GB, J, K, MB, TB, USD, hour, kg, kWh, second
import math
from mlsysim.fmt import (
MarkdownStr,
fmt,
fmt_arithmetic_intensity,
fmt_area,
fmt_count,
fmt_count_range,
... | 1,383 | 54,893 |
cs249r_book | mlsysim/tests/test_physics_bounds.py | .py | """
Automated Physics Verification Suite
------------------------------------
This test suite "bulletproofs" the mlsysim Silicon Zoo.
It iterates over every registered hardware node and ensures that its
specifications obey known laws of physics and sensible bounds.
This prevents contributors from accidentally adding a... | 174 | 8,050 |
cs249r_book | mlsysim/tests/test_state.py | .py | """Tests for DesignLedger persistence (mlsysim/labs/state.py).
Covers the WASM background-save failure path fixed in #1985: previously
`save()` used `asyncio.create_task(...)` fire-and-forget, so IndexedDB
failures inside `save_async()` were silently swallowed and never surfaced
to the caller. See:
https://github.com/... | 125 | 4,150 |
cs249r_book | mlsysim/tests/test_empirical.py | .py | # tests/test_empirical.py
# Empirical Validation Suite for mlsysim
# Validates first-principles analytical results against real-world benchmarks.
#
# Philosophy: These tests compare analytical model OUTPUT against EXTERNAL
# benchmark data (MLPerf, NVIDIA published numbers). The targets are NOT
# derived from the model... | 154 | 6,679 |
cs249r_book | mlsysim/tests/test_cli_contract.py | .py | import json
from pathlib import Path
import pytest
from pydantic import ValidationError
from typer.testing import CliRunner
from mlsysim.cli.main import app
from mlsysim.cli.schemas import MlsysPlanSchema
ROOT = Path(__file__).resolve().parents[1]
runner = CliRunner()
def test_eval_json_sla_failure_is_single_json... | 251 | 7,834 |
cs249r_book | mlsysim/tests/conftest.py | .py | """Shared fixtures for mlsysim test suite.
All hardware, model, fleet, and solver fixtures are defined here.
Pytest discovers this file automatically β no imports needed in test files.
"""
import pytest
from mlsysim.core.units import Q_
from mlsysim.engine.solvers import (
CheckpointModel,
ContinuousBatching... | 225 | 4,970 |
cs249r_book | mlsysim/examples/06_multi_objective_pareto.py | .py | """
Example 06: Multi-Objective Optimization (Pareto Fronts)
--------------------------------------------------------
This script demonstrates how to construct a Pareto front of trade-offs
between Throughput (maximize) and P99 Latency (minimize) by sweeping
batch sizes through ``ServingModel`` and ``TailLatencyModel``.... | 93 | 3,237 |
cs249r_book | mlsysim/examples/manual_sweep.py | .py | """
Tutorial: The Manual Sweep Pattern
==================================
This tutorial teaches students how to "think like a systems engineer"
by manually sweeping a parameter (Batch Size) to find the "Cliff."
"""
import mlsysim
import pandas as pd # Optional, but common for students
def main():
print("Scenario... | 68 | 2,549 |
cs249r_book | mlsysim/examples/sustainability_lab.py | .py | """
Sustainability Lab: Carbon-Aware Fleet Design
=============================================
This lab teaches students how to model the 'Hierarchy of Environment'
by comparing the same GPU fleet across different regional grids.
"""
import mlsysim
from mlsysim.infrastructure.types import Datacenter
from mlsysim.solv... | 60 | 2,174 |
cs249r_book | mlsysim/examples/custom_design.py | .py | """
Example: Custom System Design
=============================
This script demonstrates how to build a hypothetical system from scratch
without using the vetted registries. This is how researchers can use
mlsysim to model unreleased or generic hardware.
"""
import mlsysim
from mlsysim.hardware.types import HardwareNo... | 68 | 2,273 |
cs249r_book | mlsysim/examples/03_heterogeneous_cluster.py | .py | """
Example 03: Cluster Modeling
Demonstrates how to model a multi-node GPU cluster and evaluate
distributed training performance + economics.
"""
from mlsysim.systems.types import Fleet, Node, NetworkFabric
from mlsysim.hardware.registry import Hardware
from mlsysim.models.registry import Models
from mlsysim.solvers i... | 69 | 2,153 |
cs249r_book | mlsysim/examples/01_basic_roofline.py | .py | #!/usr/bin/env python3
"""
Example 1: The Roofline Model
-----------------------------
This script demonstrates the absolute core of the MLSysΒ·im framework:
evaluating a workload against a specific piece of hardware to find the bottleneck.
"""
import mlsysim
def main():
print("Evaluating Llama-3 8B on an NVIDIA A1... | 76 | 2,046 |
cs249r_book | mlsysim/examples/05_huggingface_import.py | .py | """
Example 05: Hugging Face Integration
------------------------------------
This script demonstrates how to dynamically import a model architecture
directly from the Hugging Face Hub, without needing to download the weights
or install heavy dependencies like `transformers` or `torch`.
"""
import mlsysim
from mlsysim.... | 51 | 1,956 |
cs249r_book | mlsysim/examples/02_carbon_geography.py | .py | #!/usr/bin/env python3
"""
Example 2: The Carbon Impact of Geography
-----------------------------------------
This script demonstrates the "Macro" capabilities of the framework,
showing how the physical location of a datacenter radically alters
the environmental impact of training a model.
"""
import mlsysim
from mls... | 58 | 1,924 |
cs249r_book | mlsysim/examples/04_data_wall.py | .py | """
Example 04: The Data Wall
-------------------------
This script demonstrates the "Data Wall" concept from Volume 2, Lab 4.
It shows how faster GPUs can actually result in lower utilization if the
storage bandwidth cannot keep up with the compute demand.
"""
import mlsysim
from mlsysim.core.units import Q_
def mai... | 82 | 3,122 |
cs249r_book | mlsysim/examples/hardware_comparison.py | .py | """
Tutorial: Comparing Concrete Hardware
====================================
Models the Smart Doorbell across different real-world microcontrollers.
"""
import mlsysim
def main():
scenario = mlsysim.Scenarios.SmartDoorbell
devices = [
mlsysim.Hardware.Tiny.nRF52840,
mlsysim.Hardware.Tin... | 70 | 2,544 |
cs249r_book | mlsysim/examples/hello_world.py | .py | """
Hello World: Your First mlsysim Analysis
=========================================
The simplest possible mlsysim workflow: load a model and hardware,
run the Roofline engine, and see where the bottleneck is.
python3 examples/hello_world.py
"""
import mlsysim
# 1. Pick a model and hardware from the built-in r... | 52 | 1,648 |
cs249r_book | mlsysim/paper/scripts/validate_anchors.py | .py | #!/usr/bin/env python3
"""
Validation check for the mlsysim paper.
Runs all 7 empirical anchors through mlsysim solvers and compares
the output against the values hardcoded in paper.tex. Flags any
mismatches so you can update the paper or recalibrate the solver.
Usage:
python3 validate_anchors.py
"""
import sys
... | 340 | 10,646 |
cs249r_book | mlsysim/paper/figures/fix_anatomy.py | .py | import re
with open("system-anatomy.svg", "r") as f:
content = f.read()
# Remove the text about 161 lines
content = re.sub(r'<text x="12" y="300"[^>]+>.*?</text>\n', '', content)
# Remove the Backward-compat shim block
shim_block = r'''\s*<!-- Backward-compat shim -->\n\s*<rect x="12" y="312"[^>]+/>\n\s*<text x=... | 15 | 496 |
cs249r_book | mlsysim/paper/figures/fix_svg.py | .py | import re
import sys
import glob
def make_sharp(m):
path_d = m.group(1)
if 'C' not in path_d:
return m.group(0)
# Extract all numbers from the path
numbers = [float(x) for x in re.findall(r'-?\d+\.?\d*', path_d)]
if not numbers:
return m.group(0)
xmin = min(numbers[::2... | 31 | 747 |
cs249r_book | design-grammar/paper/scripts/generate_primitive_catalog.py | .py | #!/usr/bin/env python3
"""
Generate a crisp vector SVG of the ML Systems Design Grammar primitive catalog
from the canonical YAML source of truth (design-grammar/grammar.yml).
The SVG follows the paper's typographic conventions:
* Helvetica neue / Arial sans family
* Role colors taken directly from the YAML (match... | 252 | 9,665 |
cs249r_book | tools/validate_playbook.py | .py | import re
import sys
from pathlib import Path
# Strict Schema Components
PATTERNS = {
"Level/Badge": r'<summary><b><img src=".*?" alt="Level.*?" align="center">',
"Realistic Solution": r'\*\*Realistic Solution:\*\*',
"Deep Dive": r'π\s*\*\*Deep Dive:\*\*\s*\[.*?\]\(.*?\)'
}
FLASHCARD_PATTERNS = {
"In... | 111 | 3,796 |
cs249r_book | tools/audit/audit_pdf_spot_check.py | .py | #!/usr/bin/env python3
"""
For each saved PDF in audit-pdf-output/, locate the page that contains
the specific math content we fixed and emit a navigation manifest.
"""
import re
import subprocess
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
OUT = REPO / "audit-pdf-output"
# (volume, chapter, f... | 123 | 4,359 |
cs249r_book | tools/audit/audit_math_pdf.py | .py | #!/usr/bin/env python3
"""
PDF math-rendering audit for MLSysBook chapters.
For each chapter:
1. Builds a PDF via `./book/binder build pdf <vol>/<chap>`.
A build failure is itself a strong signal of a math-rendering bug
(raw \\command outside math mode causes LaTeX to error out).
2. Extracts text via `pd... | 354 | 12,916 |
cs249r_book | tools/audit/audit_math_rendering.py | .py | #!/usr/bin/env python3
"""
Math-rendering audit for MLSysBook HTML output.
For each chapter, builds the HTML (via `./book/binder build html <chap>`),
then scans the rendered HTML for raw LaTeX leakage that escaped MathJax.
A "leak" is a LaTeX command or pattern that appears in user-visible prose
(outside <script>, <s... | 303 | 11,045 |
cs249r_book | shared/scripts/build-redirects.py | .py | #!/usr/bin/env python3
"""Generate redirect HTML stubs (and a Netlify _redirects file) from the
shared redirect-map.
Why this script exists
----------------------
GitHub Pages doesn't honor server-side redirects. To preserve SEO juice
from the legacy mlsysbook.ai URLs after the staged rollout, we emit one
tiny HTML fi... | 205 | 6,696 |
cs249r_book | shared/scripts/check-internal-links.py | .py | #!/usr/bin/env python3
"""Tier 1 link checker: validate internal Markdown / Quarto links offline.
Scope on purpose:
- Validate ONLY relative-path links and same-file anchor links inside
`.md` / `.qmd` files.
- DO NOT touch external URLs (http/https/mailto/tel/...). External
reachability is Lychee's job in ... | 498 | 18,215 |
cs249r_book | shared/scripts/build-sitemap.py | .py | #!/usr/bin/env python3
"""Aggregate per-subsite sitemap.xml files into a single root-level
sitemap-index.xml at mlsysbook.ai/sitemap.xml.
Why aggregate instead of one-sitemap-per-subsite?
-------------------------------------------------
Each subsite (Vol I, Vol II, TinyTorch, labs, β¦) emits its own
`sitemap.xml` at `... | 173 | 6,063 |
cs249r_book | shared/scripts/find-duplicates.py | .py | #!/usr/bin/env python3
"""find-duplicates.py β surface near-duplicate files across subsites.
Why this exists
---------------
The MLSysBook ecosystem keeps real-file copies of certain shared assets
per subsite (Quarto's resource-copy step preserves symlinks instead of
dereferencing them). Those known mirrors live in
`s... | 236 | 8,839 |
cs249r_book | labs/bootstrap.py | .py | """Native-only bootstrap for Marimo co-labs (not part of the mlsysim wheel).
WASM bootstrap (micropip.install) is handled inline in each lab's Cell 0
because marimo's html-wasm export bundles only the notebook .py file β
bootstrap.py is not available in the Pyodide virtual filesystem.
"""
from __future__ import annot... | 34 | 1,139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.