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 | book/tools/scripts/quizzes/_legacy/quizzes_reference.py | .py | #!/usr/bin/env python3
"""
Quiz Generation and Management Tool for ML Systems Textbook
This script provides a comprehensive tool for generating, managing, and maintaining
quiz questions for a machine learning systems textbook. It supports multiple modes
of operation and integrates with Quarto markdown files.
OVERVIEW... | 6,577 | 286,349 |
cs249r_book | book/tools/scripts/audit/math_chapter_workflow.py | .py | #!/usr/bin/env python3
"""Build MLSysBook chapter packets for math-accuracy audit rounds.
The script uses the existing `book/binder` PDF build path. For each selected
unit it builds a standalone PDF, copies the generated PDF and keep-tex output
into a stable packet directory, and writes small-batch prompts for Codex a... | 682 | 25,654 |
cs249r_book | book/tools/scripts/audit/validate_concept_maps.py | .py | #!/usr/bin/env python3
"""Validate MLSysBook concept-map files and QMD frontmatter wiring."""
from __future__ import annotations
import argparse
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
import yaml
REPO_ROOT = Path(__file__).resolve().parents[4]
CONTENTS... | 190 | 6,833 |
cs249r_book | book/tools/scripts/audit/svg_audit.py | .py | #!/usr/bin/env python3
"""svg_audit.py v2 β batched, phase-based SVG quality audit for 238 figures.
Architecture (Approach C, iteration-based, holistic):
PHASE 1: BATCHED REVIEW (8 figures per Gemini call)
Input: rendered PNGs of N figures
Prompt: "For each figure answer design-sound + aesthetic-clean +
... | 1,017 | 45,119 |
cs249r_book | book/tools/scripts/content/fix_alt_text.py | .py | #!/usr/bin/env python3
"""Apply edited alt-text from copy editor JSON extraction.
Reads the alt_text_edits.json and updates fig-alt= attributes in QMD files.
Usage:
python3 fix_alt_text.py --edits data/alt_text_edits.json --dry-run book/quarto/contents/vol1/
python3 fix_alt_text.py --edits data/alt_text_edits... | 96 | 3,379 |
cs249r_book | book/tools/scripts/content/glossary_gap_review.py | .py | #!/usr/bin/env python3
"""Build review packets for curated glossary gap audits.
The packet output is deliberately an audit aid, not a glossary generator.
Concept maps are treated as candidate sources only; every missing candidate
still needs editorial classification before any glossary entry is added.
"""
from __futu... | 353 | 11,658 |
cs249r_book | book/tools/scripts/content/fix_bibliography.py | .py | #!/usr/bin/env python3
"""Enrich bibliography entries with missing publisher/journal fields.
Adds publisher fields to @inproceedings and journal fields to @article
entries based on known venue mappings.
Usage:
python3 fix_bibliography.py --dry-run book/quarto/contents/references.bib
python3 fix_bibliography.p... | 207 | 7,196 |
cs249r_book | book/tools/scripts/content/fix_numbers.py | .py | #!/usr/bin/env python3
"""Spell out single digits 1β9 in body prose per MIT Press style.
Replaces bare digits 1β9 with their spelled-out equivalents in body prose,
skipping protected contexts: code fences, YAML frontmatter, LaTeX math,
Python cells, table rows, HTML tags, figure/div attributes, index entries,
version ... | 458 | 16,964 |
cs249r_book | book/tools/scripts/content/format_div_spacing.py | .py | #!/usr/bin/env python3
"""
Script to ensure proper blank line spacing inside Quarto div blocks (callouts).
Problem: When content inside a div (like a callout) has a paragraph immediately
followed by a list without a blank line between them, Pandoc may render them
incorrectly in PDF output (content gets "mushed" togeth... | 362 | 12,529 |
cs249r_book | book/tools/scripts/content/fix_percent.py | .py | #!/usr/bin/env python3
"""Convert '%' to 'percent' in body prose per MIT Press style.
Handles three contexts:
1. Hard-coded: '94%' β '94 percent'
2. Inline Python followed by %: '`{python} x.pct_str`%' β '`{python} x.pct_str` percent'
3. Leaves alone: tables, code fences, LaTeX math, YAML, Python cells, fig-cap,... | 183 | 5,533 |
cs249r_book | book/tools/scripts/content/fix_abbreviations.py | .py | #!/usr/bin/env python3
"""Expand abbreviations on first use per chapter per MIT Press style.
For each chapter QMD file, finds the first occurrence of each abbreviation
in body prose and ensures it's expanded. Subsequent uses stay abbreviated.
Usage:
python3 fix_abbreviations.py --check book/quarto/contents/vol1/
... | 212 | 8,270 |
cs249r_book | book/tools/scripts/content/check_prose_spelling.py | .py | #!/usr/bin/env python3
r"""
Spell check prose content in QMD files using aspell.
Intelligently parses QMD file structure to only check actual prose text,
excluding YAML frontmatter, code blocks, TikZ diagrams, inline code, URLs, etc.
Usage:
python3 tools/scripts/content/check_prose_spelling.py [directory]
Requir... | 497 | 18,913 |
cs249r_book | book/tools/scripts/content/fix_emdash.py | .py | #!/usr/bin/env python3
"""Close up spaced em dashes per MIT Press style.
Replaces ' β ' (space-emdash-space) with 'β' (closed) in body prose,
skipping code fences, YAML frontmatter, LaTeX math blocks, Python cells,
and table separator lines.
Usage:
python3 fix_emdash.py --dry-run book/quarto/contents/vol1/
py... | 117 | 3,781 |
cs249r_book | book/tools/scripts/content/check_figure_div_syntax.py | .py | #!/usr/bin/env python3
"""
Check that figures use div syntax (fig-cap and fig-alt on the div), not old-style
markdown image or chunk options.
We standardize on:
::: {#fig-xxx fig-env="figure" fig-pos="htb" fig-cap="..." fig-alt="..."}
 OR ```{python} / ```{.tikz} block
:::
This script fails if it f... | 120 | 4,228 |
cs249r_book | book/tools/scripts/content/format_tables.py | .py | #!/usr/bin/env python3
"""
Production Table Formatter for MLSysBook
This script formats and validates grid tables in Quarto .qmd files.
Designed for use in CI/CD pipelines and pre-commit hooks.
Key Features:
- Smart column header bolding (always, including multiline headers)
- Intelligent first column bolding (based ... | 990 | 34,587 |
cs249r_book | book/tools/scripts/content/relocate_figures.py | .py | #!/usr/bin/env python3
"""
Element Relocator for Quarto Documents
Safely moves figures, tables, and listings closer to where they're first referenced,
respecting footnote definitions that must stay near their markers.
Usage:
python relocate_figures.py <file.qmd> # Preview mode (dry run)
python re... | 723 | 25,754 |
cs249r_book | book/tools/scripts/content/check_tikz_spelling.py | .py | #!/usr/bin/env python3
r"""
Spell check text content within TikZ diagrams.
Extracts and validates all visible text from TikZ diagrams in .qmd files,
including node labels, inline annotations, formatted text, and comments.
Usage:
python3 tools/scripts/content/check_tikz_spelling.py
Checks text in:
- Node comm... | 494 | 16,968 |
cs249r_book | book/tools/scripts/content/fix_capitalization.py | .py | #!/usr/bin/env python3
"""Lowercase concept terms per MIT Press style.
Handles specific terms the copy editor flagged, with careful context
awareness to avoid breaking:
- Sentence starts
- Bold definitions (**Term**)
- Triple bold definitions (***Term***)
- Section headers (## ...)
- Callout titles (title="...")
- Ind... | 231 | 7,621 |
cs249r_book | book/tools/scripts/content/section_splitter.py | .py | #!/usr/bin/env python3
"""
section_splitter.py
Splits .qmd chapter files into individual sections for processing.
Designed to support section-by-section editorial workflows where each
section needs to be processed independently (e.g., by stylist agent).
Key Features:
- Uses pypandoc JSON AST for robust parsing (handl... | 574 | 19,137 |
cs249r_book | book/tools/scripts/content/manage_captions.py | .py | #!/usr/bin/env python3
"""
Figure Caption Improvement Script
A streamlined tool for improving figure and table captions in Quarto-based textbooks
using LLM models with strong, educational language.
Supports local Ollama models (default) and cloud LLM providers via OpenAI-compatible
APIs (OpenAI, Groq, MiniMax, or any... | 4,325 | 190,159 |
cs249r_book | book/tools/scripts/content/format_python_in_qmd.py | .py | #!/usr/bin/env python3
"""Format Python code blocks in .qmd files using Black.
Also wraps long comments and docstrings that Black doesn't handle.
Two block profiles:
- Display blocks (```python / ```{.python}): Black at 70 chars + comment
wrapping β narrow snippets shown to the reader.
- Executable LEGO cells (```{... | 343 | 11,255 |
cs249r_book | book/tools/scripts/content/validate_tables.py | .py | #!/usr/bin/env python3
"""
Table Rendering Validator for MLSysBook
Catches rendering issues in Quarto grid tables that the structural
formatter (format_tables.py) misses. Designed to prevent broken PDF/HTML
output by detecting content-level problems BEFORE building.
Checks performed:
1. Bare pipe characters (|) ins... | 507 | 17,915 |
cs249r_book | book/tools/figures/__init__.py | .py | """Book-owned figure helpers used by MLSysBook production tooling."""
from .style import (
COLORS,
WEB_FIG_DPI,
bar_compare,
finalize_web_figure,
set_book_style,
setup_plot,
)
__all__ = [
"COLORS",
"WEB_FIG_DPI",
"bar_compare",
"finalize_web_figure",
"set_book_style",
"... | 20 | 335 |
cs249r_book | book/tools/figures/style.py | .py | """Publication plotting style for MLSysBook figures.
This module owns book-level matplotlib policy: palette, font stack, grid style,
and the small setup helper used by generated figure blocks. Simulator-aware
plots remain in ``mlsysim.viz``; book production style belongs here.
"""
from __future__ import annotations
... | 145 | 4,708 |
cs249r_book | book/tools/figures/margin/__init__.py | .py | """Margin-figure devices for MLSysBook production tooling."""
from .devices import * # noqa: F401,F403
| 4 | 105 |
cs249r_book | book/tools/figures/margin/devices.py | .py | #!/usr/bin/env python3
"""
devices.py - the canonical margin-figure renderers, in the locked visual
language (.claude/rules/figure-visual-language.md + margin-figures.md).
This is the single source of truth for HOW a margin device is drawn. Insertion
work imports these; do not re-implement device shapes elsewhere.
Ed... | 607 | 34,519 |
cs249r_book | book/tools/audit/book_check_lego_load_pint.py | .py | #!/usr/bin/env python3
"""Static lint: physical ``*_value`` assignments must not use bare floats.
Policy
------
In LEGO ``{python}`` cells, quantities with physical units should load from
``ureg``, ``Hardware.*``, ``Systems.*``, ``Infrastructure.*``, etc. β not
bare numeric literals.
Skip dimensionless names containi... | 148 | 4,849 |
cs249r_book | book/tools/audit/appendix_lineage.py | .py | """Book-side lineage gates for numbers that appear in assumption appendices."""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
from mlsysim.core.provenance import Provenance, Sourced
_REPO_ROOT = Path(__file__).resolve().parents[3]
APPENDIX_ASSUMPTIONS_QMD = (
_REPO... | 124 | 4,711 |
cs249r_book | book/tools/audit/emphasis_ap2map.py | .py | #!/usr/bin/env python3
"""
Volume-wide body-prose BOLD occurrence map -> AP2 candidates.
Phase 2 helper for the emphasis audit. Runs emphasis_extract.py over every chapter
of a volume IN CANONICAL ORDER (derived from the PDF config YAML), collects every
body-prose bold span, and reports any term bolded in >=2 distinct... | 72 | 3,107 |
cs249r_book | book/tools/audit/render_playwright_verify.py | .py | #!/usr/bin/env python3
"""Browser-level render verification for chapter HTML (MathJax + visible text)."""
from __future__ import annotations
import argparse
import json
import re
import sys
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().pare... | 227 | 8,260 |
cs249r_book | book/tools/audit/book_check_registry_sources.py | .py | #!/usr/bin/env python3
"""Scan chapter QMD LEGO cells for banned legacy registry/constant patterns."""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
CONTENTS = REPO_ROOT / "book" / "quarto" / "contents"
CELL_START = r... | 352 | 13,131 |
cs249r_book | book/tools/audit/fix_script_lane.py | .py | #!/usr/bin/env python3
"""Pass 15 script-lane fixer.
Reads an audit ledger and applies all issues marked `auto_fixable=True`,
grouped by file. Runs five safety checks per file before writing; files
that fail any safety check are rolled back to their pre-edit state and the
failing issues are marked failed-script-lane i... | 462 | 15,786 |
cs249r_book | book/tools/audit/book_check_lego_prose_literals.py | .py | #!/usr/bin/env python3
"""Compatibility wrapper for the Binder-native LEGO prose literals check."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
from book.cli.checks.lego_prose_literals import ( # noqa: E402,F401
... | 20 | 403 |
cs249r_book | book/tools/audit/check_registry_migration_build.py | .py | #!/usr/bin/env python3
"""Run end-to-end gates for the constants β registry migration build.
Canonical entry point: ``./binder check registry``
"""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
def main() -> int:
binder... | 24 | 517 |
cs249r_book | book/tools/audit/migrate_defaults.py | .py | #!/usr/bin/env python3
"""Replace ``defaults.*`` with domain registry paths in QMD and Python."""
from __future__ import annotations
import re
import sys
from pathlib import Path
_REPO = Path(__file__).resolve().parents[3]
# Longest symbols first to avoid partial replacements.
_SYMBOL_MAP: list[tuple[str, str]] = [... | 141 | 5,992 |
cs249r_book | book/tools/audit/audit_mlsysim_drift.py | .py | #!/usr/bin/env python3
"""
audit_mlsysim_drift.py β find hand-coded values in chapter QMDs that should
come from mlsysim's canonical constants.
Approach:
1. Build a registry of (canonical_name, numeric_value, magnitude_tolerance)
from mlsysim.core.units.
2. Walk every chapter QMD's Python cells. For each nume... | 239 | 13,347 |
cs249r_book | book/tools/audit/book_check_lego_scenario_inputs.py | .py | #!/usr/bin/env python3
"""Advisory audit for LEGO inputs that should move into MLSysIM.
This checker is intentionally advisory. It answers a different question from
the unit lints:
Does this LEGO LOAD-stage value define a book scenario, system, hardware
object, infrastructure fact, model, dataset, pricing poi... | 607 | 22,253 |
cs249r_book | book/tools/audit/pdf_build_verify.py | .py | #!/usr/bin/env python3
"""Thin CLI wrapper β canonical entry point is `./binder check pdf`."""
from __future__ import annotations
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(REPO_ROOT / "book"))
from cli.commands._pdf_checks import ( # noqa: E402
d... | 58 | 1,958 |
cs249r_book | book/tools/audit/audit_html.py | .py | #!/usr/bin/env python3
"""Backward-compat wrapper β use ``book/tools/audit/fmt/audit_html.py``."""
from __future__ import annotations
import runpy
import sys
from pathlib import Path
_TARGET = Path(__file__).resolve().parent / "fmt" / "audit_html.py"
sys.argv[0] = str(_TARGET)
runpy.run_path(str(_TARGET), run_name="... | 13 | 333 |
cs249r_book | book/tools/audit/chapter_html_verify.py | .py | #!/usr/bin/env python3
"""Build chapter HTML, audit raw output, and track pass/fail in a ledger.
Usage (repo root)::
python3 book/tools/audit/chapter_html_verify.py --list
python3 book/tools/audit/chapter_html_verify.py --vol1 introduction
python3 book/tools/audit/chapter_html_verify.py --vol1 --all
p... | 528 | 18,465 |
cs249r_book | book/tools/audit/snapshot_lego_baseline.py | .py | #!/usr/bin/env python3
"""Snapshot LEGO cell inventory and focal-verify status for migration baseline."""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
OUT_DIR = REPO_ROOT / "book" / "tools" / "audit" / "... | 101 | 3,281 |
cs249r_book | book/tools/audit/scan.py | .py | #!/usr/bin/env python3
"""Pass 15 audit scanner.
Walks a configurable content tree, runs every registered check function
against every .qmd file, and writes an audit-ledger.json.
Usage:
python3 book/tools/audit/scan.py --scope vol1
python3 book/tools/audit/scan.py --scope vol2 --categories vs-period,percent-s... | 409 | 15,180 |
cs249r_book | book/tools/audit/__init__.py | .py | """Audit-fix-verify loop for the MIT Press editorial standard.
Scans textbook content against the project's prose style guide (maintained
outside this repository), applies safe fixes under strict safety gates, and
verifies the result.
The five-stage cycle: SCAN -> PLAN -> FIX -> VERIFY -> REPORT.
Verification is the ... | 10 | 360 |
cs249r_book | book/tools/audit/lego_focal_verify.py | .py | #!/usr/bin/env python3
"""Verify LEGO focal-point coherence for one or more QMD chapters."""
from __future__ import annotations
import argparse
import re
import sys
from collections import defaultdict
from pathlib import Path
INLINE = re.compile(r"`\{python\}\s+([A-Za-z_][\w.]*)`")
CLASS = re.compile(r"^class\s+(\w+)... | 159 | 5,386 |
cs249r_book | book/tools/audit/sync_lego_journal.py | .py | #!/usr/bin/env python3
"""Regenerate JOURNAL.md chapter table from chapters/*.status.yaml (parallel-safe)."""
from __future__ import annotations
import re
from datetime import datetime, timezone
from pathlib import Path
try:
import yaml
except ImportError:
yaml = None # type: ignore
ROOT = Path(__file__).r... | 133 | 4,356 |
cs249r_book | book/tools/audit/emphasis_rollup.py | .py | #!/usr/bin/env python3
"""
Roll up per-chapter emphasis ledgers into a volume summary + fix-list.
Reads every .claude/_reviews/emphasis/<vol>/*.yml ledger (schema-tolerant: it finds
any dict carrying a 'recommendation' key, wherever the agent nested it) and prints
per-chapter counts, volume totals, and the full action... | 77 | 2,904 |
cs249r_book | book/tools/audit/run_registry_audit.py | .py | #!/usr/bin/env python3
"""Run registry-migration CI gates (book sources, appendix cells, provenance)."""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
MLSYSIM = REPO / "mlsysim"
def _run(cmd: list[str], *, cwd: Path | None = None... | 62 | 1,939 |
cs249r_book | book/tools/audit/spurious_zero.py | .py | """Backward-compat re-export β prefer ``book.tools.audit.fmt.spurious_zero``."""
from __future__ import annotations
import importlib.util
from pathlib import Path
_path = Path(__file__).resolve().parent / "fmt" / "spurious_zero.py"
_spec = importlib.util.spec_from_file_location("_fmt_spurious_zero", _path)
assert _s... | 23 | 700 |
cs249r_book | book/tools/audit/refresh_stale_defaults_refs.py | .py | #!/usr/bin/env python3
"""Rewrite stale ``mlsysim.core.defaults.*`` paths in audit YAML and tooling."""
from __future__ import annotations
from pathlib import Path
_REPO = Path(__file__).resolve().parents[3]
# Longest keys first.
_REPLACEMENTS: list[tuple[str, str]] = [
("mlsysim.core.defaults.CHINCHILLA_DATA_S... | 110 | 6,531 |
cs249r_book | book/tools/audit/verify.py | .py | #!/usr/bin/env python3
"""Pass 15 verifier.
Runs the VERIFY stage of the five-stage cycle. Three checks must all pass
before the orchestrator commits anything:
1. Re-run the scanner against the changed files. The expected outcome is
that the issue count for each fixed category drops by at least the
number of fi... | 391 | 14,173 |
cs249r_book | book/tools/audit/fix_fmt_precision.py | .py | #!/usr/bin/env python3
"""Backward-compat wrapper β use ``book/tools/audit/fmt/fix_precision.py``."""
from __future__ import annotations
import runpy
import sys
from pathlib import Path
_TARGET = Path(__file__).resolve().parent / "fmt" / "fix_precision.py"
sys.argv[0] = str(_TARGET)
runpy.run_path(str(_TARGET), run_... | 13 | 339 |
cs249r_book | book/tools/audit/fix_prose_spurious.py | .py | #!/usr/bin/env python3
"""Backward-compat wrapper β use ``book/tools/audit/fmt/fix_spurious_prose.py``."""
from __future__ import annotations
import runpy
import sys
from pathlib import Path
_TARGET = Path(__file__).resolve().parent / "fmt" / "fix_spurious_prose.py"
sys.argv[0] = str(_TARGET)
runpy.run_path(str(_TAR... | 13 | 349 |
cs249r_book | book/tools/audit/book_check_lego_prose_units.py | .py | #!/usr/bin/env python3
"""Compatibility wrapper for the Binder-native LEGO prose units check."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
from book.cli.checks.lego_prose_units import ( # noqa: E402,F401
check... | 20 | 397 |
cs249r_book | book/tools/audit/migrate_constants_to_registry.py | .py | #!/usr/bin/env python3
"""Replace legacy mlsysim.core.units hardware symbols with registry paths in QMD cells."""
from __future__ import annotations
import argparse
import importlib.util
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
MAP_PATH = REPO_ROOT / "scripts" / "... | 238 | 12,305 |
cs249r_book | book/tools/audit/repair_training_py_refs.py | .py | #!/usr/bin/env python3
"""Repair training.qmd {python} refs broken by over-aggressive Γ/unit stripping."""
from __future__ import annotations
import re
from pathlib import Path
QMD = Path(__file__).resolve().parents[3] / "book/quarto/contents/vol1/training/training.qmd"
# `{python} Class.field_str <word β missing c... | 41 | 1,050 |
cs249r_book | book/tools/audit/audit_prose_preview.py | .py | #!/usr/bin/env python3
"""Backward-compat wrapper β use ``book/tools/audit/fmt/audit_prose.py``."""
from __future__ import annotations
import runpy
import sys
from pathlib import Path
_TARGET = Path(__file__).resolve().parent / "fmt" / "audit_prose.py"
sys.argv[0] = str(_TARGET)
runpy.run_path(str(_TARGET), run_name... | 13 | 335 |
cs249r_book | book/tools/audit/chapter_pdf_verify.py | .py | #!/usr/bin/env python3
"""Build chapter PDF, audit TeX/PDF output, and track pass/fail in a ledger.
Usage (repo root)::
python3 book/tools/audit/chapter_pdf_verify.py --list
python3 book/tools/audit/chapter_pdf_verify.py --vol1 introduction
python3 book/tools/audit/chapter_pdf_verify.py --vol1 --all
p... | 511 | 17,655 |
cs249r_book | book/tools/audit/book_check_lego_equations.py | .py | #!/usr/bin/env python3
"""Verify prose ``A / B = C`` equations backed by ``{python}`` refs.
Finds walkthrough lines with three inline-python refs in division form::
`{python} Class.a_str` / `{python} Class.b_str` = `{python} Class.c_str`
Execs chapter cells (shared namespace), parses numeric values from resolved... | 260 | 8,311 |
cs249r_book | book/tools/audit/lego_prose_coherence.py | .py | #!/usr/bin/env python3
"""LLM coherence review for LEGO inline-python prose.
Extracts prose lines that reference ``{python} Class.field`` outputs (with
values substituted from cell exec), groups them by LEGO class, and asks an LLM
whether each snippet reads coherently in context.
Usage (repo root)::
PYTHONPATH=m... | 424 | 14,215 |
cs249r_book | book/tools/audit/refresh_mlsysim_constants_yamls.py | .py | #!/usr/bin/env python3
"""Refresh target_source fields in book/tools/audits/mlsysim_constants/*.yaml."""
from __future__ import annotations
import importlib.util
import re
import sys
from pathlib import Path
import yaml
REPO_ROOT = Path(__file__).resolve().parents[3]
YAML_DIR = REPO_ROOT / "book" / "tools" / "audit... | 132 | 4,913 |
cs249r_book | book/tools/audit/loop.py | .py | #!/usr/bin/env python3
"""Pass 15 orchestrator β the five-stage cycle.
Runs SCAN -> PLAN -> FIX -> VERIFY -> REPORT. Stops when any of the
five conditions in Pass 15 plan section 2.5 is met:
1. Zero open issues remaining in active categories -> exit success
2. No progress in last iteration -> exit "stuck", print ... | 435 | 13,845 |
cs249r_book | book/tools/audit/accept_list.py | .py | """Persistent accept-list for editorially-verified scanner false positives.
Pass 16 β Item A (the highest-leverage Pass 16 change).
Context
-------
The Pass 15 h3_titlecase scanner's multi-cap-token heuristic over-flags any
heading that contains two or more capitalized tokens, even when the capitals
are proper nouns,... | 308 | 11,091 |
cs249r_book | book/tools/audit/chapter_build_sequence.py | .py | #!/usr/bin/env python3
"""Build chapters one-at-a-time in PDF-config order."""
from __future__ import annotations
import argparse, json, subprocess, sys, time
from datetime import datetime, timezone
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
BOOK = REPO / "book" / "quarto"
BINDER = REPO / "boo... | 61 | 2,689 |
cs249r_book | book/tools/audit/book_check_lego_quantity_flow.py | .py | #!/usr/bin/env python3
"""Advisory audit for stronger LEGO quantity-flow/source discipline.
This is intentionally not wired as a blocking gate yet. It finds patterns that
the current unit linter allows but the hardening plan wants to burn down:
* avoidable scalar extraction and later unit reattachment;
* ``ureg.<unit... | 361 | 12,255 |
cs249r_book | book/tools/audit/protected_contexts.py | .py | r"""Protected-context detection for the audit scanner.
This module is the load-bearing safety layer of Pass 15. Every check function
asks this module: "is this position safe to flag/edit?" The answer must
mirror the rules in book-prose-merged.md sections 9 and 10.
Two layers of protection:
1. LINE-LEVEL state (`Line... | 658 | 28,127 |
cs249r_book | book/tools/audit/migrate_training_fmt_suffixes.py | .py | #!/usr/bin/env python3
"""Add fmt suffixes to training.qmd LEGO exports from naming conventions."""
from __future__ import annotations
import re
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
QMD = REPO / "book/quarto/contents/vol1/training/training.qmd"
SUFFIX_RULES: list[tuple[str,... | 194 | 5,579 |
cs249r_book | book/tools/audit/ledger.py | .py | """Audit ledger model and JSON serialization.
The ledger is the single source of truth for what the scanner found,
what the fixer applied, and what the verifier confirmed. Format per
Pass 15 plan section 3.
Issue lifecycle:
open - fresh from scanner, not yet acted on
fixed-script-lane - scrip... | 214 | 7,632 |
cs249r_book | book/tools/audit/audit_math_canonical.py | .py | #!/usr/bin/env python3
"""Standalone CLI for the math-canonical check.
Implementation lives in ``cli.checks.math_canonical``. Prefer::
./book/binder check math --scope canonical
This script remains for ad-hoc use and backward-compatible docs links.
"""
from __future__ import annotations
import sys
from pathlib... | 25 | 644 |
cs249r_book | book/tools/audit/run_render_guarantee.py | .py | #!/usr/bin/env python3
"""Run render-guarantee stack on binder debug HTML artifacts."""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
REPO = Path(__file__).resolve()... | 214 | 8,045 |
cs249r_book | book/tools/audit/margin_geometry.py | .py | #!/usr/bin/env python3
"""Compatibility wrapper for Binder-native margin geometry checks.
Core implementation lives in ``book/cli/checks/margin_geometry.py``. Keep this
script so older notes and shell history that call ``book/tools/audit`` still
work, but do not put Binder-critical check logic here.
"""
from __future... | 56 | 1,756 |
cs249r_book | book/tools/audit/migrate_lego_prose_units.py | .py | #!/usr/bin/env python3
"""Strip redundant unit tokens after ``{python} *_str`` refs when fmt suffix exists."""
from __future__ import annotations
import argparse
import re
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
CONTENTS = REPO_ROOT / "book" / "quarto" / "contents"
STRIP_AFTER_REF =... | 77 | 2,178 |
cs249r_book | book/tools/audit/generate_appendix_constants.py | .py | #!/usr/bin/env python3
"""Verify and regenerate appendix assumption-table LEGO cells from registries.
Appendix ``*Constants`` classes in vol1/vol2 ``appendix_assumptions.qmd`` should
source hardware/model/fabric values from typed registries (``Hardware.*``,
``Models.*``, ``Systems.*``, ``Literature.*``, ``Infrastructu... | 354 | 12,597 |
cs249r_book | book/tools/audit/check_fig_ai_performance_drift.py | .py | #!/usr/bin/env python3
"""Drift-guard for the @fig-ai-performance TikZ figure (hw_acceleration).
Why this exists
---------------
``@fig-ai-performance`` is a hand-authored TikZ/pgfplots figure. TikZ cannot
import mlsysim at render time, so its NVIDIA accelerator throughput numbers are
necessarily hardcoded literals in... | 132 | 4,968 |
cs249r_book | book/tools/audit/generate_registry_migration_manifest.py | .py | #!/usr/bin/env python3
"""Generate dead_constants_verified.json and registry_migration_manifest.json.
Scans mlsysim.core.units for defined symbols, counts repo-wide references,
and assigns migration targets using scripts/map_constants.py plus heuristics.
Usage:
python3 book/tools/audit/generate_registry_migration... | 336 | 11,852 |
cs249r_book | book/tools/audit/normalize_tbl_colwidths.py | .py | #!/usr/bin/env python3
"""Move tbl-colwidths from wrapper divs onto table caption lines."""
from __future__ import annotations
import re
import sys
from pathlib import Path
WRAPPER_RE = re.compile(r'^::: \{tbl-colwidths="(\[[^\]]+\])"\}\s*$')
CAPTION_RE = re.compile(r'^(: .* \{#tbl-[^\s\}]+)(.*\})\s*$')
def normali... | 76 | 2,121 |
cs249r_book | book/tools/audit/llm_chapter_signoff.py | .py | #!/usr/bin/env python3
"""Pre-commit chapter sign-off for registry-migrated QMD LEGO cells."""
from __future__ import annotations
import argparse
import re
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
CELL_START = re.compile(r"^```\{python\}")
CELL_END = re.co... | 80 | 2,431 |
cs249r_book | book/tools/audit/patch_training_suffixes.py | .py | #!/usr/bin/env python3
"""Add missing fmt suffixes in training.qmd (idempotent)."""
import re
from pathlib import Path
QMD = Path(__file__).resolve().parents[3] / "book/quarto/contents/vol1/training/training.qmd"
RULES = [
(r"(\w+_gb_str)\s*=\s*fmt\(([^)]*)\)", " GB"),
(r"(\w+_mb_str)\s*=\s*fmt\(([^)]*)\)", "... | 58 | 2,222 |
cs249r_book | book/tools/audit/split_multi_class_cells.py | .py | #!/usr/bin/env python3
"""Split python cells that define more than one LEGO class into separate cells."""
from __future__ import annotations
import re
import sys
from pathlib import Path
CLASS = re.compile(r"^class\s+(\w+)", re.M)
CELL_START = re.compile(r"^```\{python\}")
CELL_END = re.compile(r"^```\s*$")
INLINE = ... | 223 | 7,749 |
cs249r_book | book/tools/audit/check_purpose_overflow.py | .py | #!/usr/bin/env python3
"""Purpose-overflow check: every chapter's Purpose must fit on its opener page.
A teaching chapter opens with a cover image + the Purpose section (italic hook +
exactly one paragraph), then a forced \\newpage to the Learning Objectives. The
Purpose must NOT spill past the opener page (a 1-2 line... | 87 | 3,947 |
cs249r_book | book/tools/audit/emphasis_extract.py | .py | #!/usr/bin/env python3
"""
Body-prose emphasis extractor (READ-ONLY candidate generator).
Emits every **bold** and *italic* span that lives in BODY PROSE, deterministically
skipping anything the body-prose emphasis rules do not own:
- YAML frontmatter
- fenced code blocks (``` ... ``` and ~~~ ... ~~~ , incl. ... | 129 | 5,889 |
cs249r_book | book/tools/audit/fmt/run_time_lane.py | .py | #!/usr/bin/env python3
"""
run_time_lane.py β migrate exact time suffixes to fmt_time.
This lane handles the mechanically provable shapes:
fmt(x, ..., suffix=" ms") -> fmt_time(x, "millisecond", ...)
fmt(x, ..., suffix=" seconds") -> fmt_time(x, "second", ..., style="word")
fmt_int(x, suffix=" hour... | 73 | 2,598 |
cs249r_book | book/tools/audit/fmt/audit_lego_html.py | .py | #!/usr/bin/env python3
"""Verify archived chapter HTML contains values from inline-python LEGO outputs.
For each QMD chapter with archived HTML under ``html-audit/<vol>/``:
1. Exec python cells (shared namespace).
2. Group ``{python} Class.attr`` refs by class (LEGO focal point).
3. Resolve each output from Python.
4... | 316 | 11,306 |
cs249r_book | book/tools/audit/fmt/run_multiplier_lane.py | .py | #!/usr/bin/env python3
"""
run_multiplier_lane.py β retired pre-Design-B multiplier migration helper.
This script used the old convention where ``fmt_multiple`` returned a bare
number and prose supplied ``$\\times$``. That convention is obsolete: Design B
makes ``fmt_multiple`` / ``fmt_multiple_range`` own the glyph a... | 182 | 7,194 |
cs249r_book | book/tools/audit/fmt/run_scale_style_lane.py | .py | #!/usr/bin/env python3
"""
run_scale_style_lane.py β apply the approved no-space K/M/B/T count style.
This lane resolves the deferred scale queue after the house-style decision that
scaled counts render as ``70K`` / ``5.3M`` / ``7B``. It rewrites queued
``fmt(..., suffix=" B")`` / ``fmt(..., suffix="k")`` patterns to
... | 149 | 5,394 |
cs249r_book | book/tools/audit/fmt/audit_prose.py | .py | #!/usr/bin/env python3
"""
audit_prose.py
==============
Exec a chapter's Python cells, substitute ``{python} Class.var_str`` inline
refs with rendered values, and print prose previews β without a full HTML build.
Use this while tuning fmt precision: read the sentence aloud, then confirm
with ``./book/binder build <c... | 232 | 6,793 |
cs249r_book | book/tools/audit/fmt/audit_html.py | .py | #!/usr/bin/env python3
"""
audit_html.py
=============
Scan rendered Quarto HTML for spurious ``*.0`` in narrative prose (final check).
Strips code cells and Quarto chrome, then flags numbers like ``739,726.0`` or
``153.0 percent`` that should have been formatted as integers. Uses the same
false-positive filters as `... | 111 | 2,979 |
cs249r_book | book/tools/audit/fmt/run_scale_lane.py | .py | #!/usr/bin/env python3
"""
run_scale_lane.py β move ``fmt(x / MILLION, suffix='M')`` into the guarded
``fmt_count`` formatter with the same BYTE-IDENTICAL gate as the percent lane.
cell: X = fmt(x / MILLION, β¦, suffix='M') β X = fmt_count(x, scale='M', β¦)
The scale division and the glyph were two facts a reader... | 81 | 2,979 |
cs249r_book | book/tools/audit/fmt/audit_lego_rendered_prose.py | .py | #!/usr/bin/env python3
"""Verify every LEGO inline ref against rendered HTML prose context.
For each ``{python} Class.field`` reference in a chapter:
1. Exec cells and resolve the export value (same namespace as Quarto).
2. Locate that value in archived chapter HTML narrative text.
3. Extract the surrounding sentence... | 441 | 16,515 |
cs249r_book | book/tools/audit/fmt/assess_equiv.py | .py | #!/usr/bin/env python3
"""
assess_equiv.py β Before/after EQUIVALENCE diff for the fmt migration.
This is the migration's value-equivalence gate. It does NOT reimplement cell
execution β it reuses the existing audit stack:
* ``cell_exec.py`` β headless shared-namespace exec (matplotlib-safe)
* ``audit_prose.... | 229 | 8,908 |
cs249r_book | book/tools/audit/fmt/audit_lego_cells.py | .py | #!/usr/bin/env python3
"""Verify every LEGO cell in archived chapters: exec, outputs, HTML refs.
For each ``{python}`` cell marked by a LEGO header or output section:
1. Exec all chapter cells in order (shared namespace β matches Quarto render).
2. List every ``*_str`` / ``*_math`` / ``*_eq`` / ``*_frac`` output on t... | 344 | 11,600 |
cs249r_book | book/tools/audit/fmt/visible_text.py | .py | #!/usr/bin/env python3
"""
visible_text.py β render a prose line to the *characters a reader sees*.
Used by the fmt migration's equivalence check (ASSESSMENT.md Β§0a, Regime 2):
a multiplier migration moves the glyph from the string into the prose
(`"6Γ"` β `"6"` + prose `$\\times$`), so comparing raw strings is the wr... | 78 | 3,009 |
cs249r_book | book/tools/audit/fmt/fmt_prose_contract.py | .py | #!/usr/bin/env python3
"""Compatibility wrapper for the Binder-native fmt prose contract check."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
sys.path.insert(0, str(ROOT))
from book.cli.checks.fmt_prose_contract import ( # noqa: E402,F401
V... | 24 | 496 |
cs249r_book | book/tools/audit/fmt/inventory_design_b_rates.py | .py | #!/usr/bin/env python3
"""Inventory Design B multiplier and rate-name migration targets.
This is a coverage tool, not an edit tool. It freezes the exact export/ref
scope for the fmt_multiple Design B migration and the rate-name normalization
pass so manual review can work from a complete list instead of sampling.
"""
... | 263 | 9,130 |
cs249r_book | book/tools/audit/fmt/spurious_zero.py | .py | """Shared detection of spurious trailing ``.0`` in narrative numbers.
Used by ``audit_prose.py`` (substituted QMD prose) and ``audit_html.py``
(rendered HTML). Filters encode known false positives: product version strings
(PCIe 4.0), unit specs (1.0 KFLOPs), LaTeX walkthrough literals, etc.
"""
from __future__ import... | 87 | 3,280 |
cs249r_book | book/tools/audit/fmt/cell_exec.py | .py | """Headless execution helpers for audit scripts that eval Quarto python cells."""
from __future__ import annotations
import os
from typing import Any
def setup_headless_matplotlib() -> None:
os.environ["MPLBACKEND"] = "Agg"
try:
import matplotlib
matplotlib.use("Agg", force=True)
import... | 45 | 1,447 |
cs249r_book | book/tools/audit/fmt/run_rate_lane.py | .py | #!/usr/bin/env python3
"""
run_rate_lane.py β migrate exact service-rate suffixes to fmt_rate.
This lane covers counted service throughputs such as ``tokens/s``, ``img/s``,
``req/s``, ``samples/s``, ``images/s``, and ``FPS``. Physical rates such as
``GB/s`` and ``TFLOP/s`` remain ``fmt_qty`` work.
"""
from __future__ ... | 67 | 2,294 |
cs249r_book | book/tools/audit/fmt/audit_fmt_usage.py | .py | #!/usr/bin/env python3
"""
audit_fmt_usage.py β Ground-truth inventory of every fmt-family call site.
Parses the ```{python}``` code cells of every chapter, AST-walks each cell, and
classifies every call to the fmt-family helpers by the *semantic kind* of value
it formats and by any
"abuse" pattern that the typed-form... | 347 | 12,869 |
cs249r_book | book/tools/audit/fmt/fix_precision.py | .py | #!/usr/bin/env python3
"""Fix fmt() precision errors using exec traceback line numbers.
See ``fmt/README.md`` for the full chapter workflow.
"""
from __future__ import annotations
import re
import sys
import traceback
from pathlib import Path
CELL_START = re.compile(r"^```\{python\}")
CELL_END = re.compile(r"^```\s... | 248 | 9,099 |
cs249r_book | book/tools/audit/fmt/prototype_typed_fmt.py | .py | #!/usr/bin/env python3
"""
prototype_typed_fmt.py β Proof-of-concept for the typed, *guarded* formatter
family. NOT wired into the book yet; this is the demonstration that the design
(a) makes illegal values impossible to render and (b) is mechanically
migratable. Run directly: python3 book/tools/audit/fmt/prototype_t... | 159 | 6,450 |
cs249r_book | book/tools/audit/fmt/codemod_fmt.py | .py | #!/usr/bin/env python3
"""
codemod_fmt.py β paired (cell + prose) rewrites for the typed-fmt migration.
Two strictly separated lanes (PLAN.md Β§6 WS1, ASSESSMENT.md Β§0a):
RETIRED (pre-Design-B) β the old multiplier relocation lane
cell: ``X = fmt(f, ..., suffix='Γ')`` β ``X = fmt_multiple(f, ...)``
prose: ... | 1,185 | 48,033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.