Module contents
Lesson 23 of 24Core 75 min

Anatomy of a research project and git for research

Organize a research project with an installable package, separation of exploration and reliable code, data and results outside git, automated quality and a lab notebook. Use commits, branches, tags and git bisect as scientific tools.

After this lesson you can

  • Structure a project with src layout, configurations, scripts, notebooks, tests and ignored data and run directories.
  • Configure pre-commit with ruff, type checking, nbstripout, quick tests and large-file blocking.
  • Use commits, branches, tags and worktrees to record decisions and research lines.
  • Find the commit introducing a metric regression with git bisect run, including noisy evaluations.
  • Maintain a lab notebook linked to commits and runs.

Before you start

Motivation: which script generated figure 3?

Three months into a project, a reviewer makes a reasonable request: repeat figure 3 with another seed and the corrected validation set. You open the folder and find fig3_final_DEFINITIVA.png, four notebooks named like analisis_v3 (copia).ipynb, two versions of entrenar.py, a 300 MB datos.csv someone edited by hand and an undated checkpoint. None says where it came from. The notebook apparently generating the figure has cells executed in an order different from the page, and its cargar_datos function does not match the other notebook used for table 2. Recreating the figure means, at best, an afternoon of archaeology; at worst, discovering the paper’s result cannot be reproduced.

This is not an intelligence failure but an instrumentation failure. A computational research project is a scientific instrument and, like any instrument, needs structure making common mistakes impossible (or at least noisy). This lesson builds that structure in four small, automatic layers:

  • A folder anatomy separating reliable code from exploration, source from derived and what goes to git from what does not.
  • Automated quality with pre-commit: every commit passes a linter, formatter, type checker, quick tests and a notebook and large-file filter.
  • Git as notebook: commits as experiment units, branches by hypothesis, tags by result and worktrees for two versions at once. And git bisect run to find the commit degrading a metric among hundreds, even when the metric is noisy.
  • A lab notebook recording expectations, outcomes and decisions, linked to commits and runs.

Git bisect involves real mathematics: an exact lower bound, an invariant and a formula for the probability of identifying the wrong culprit when each evaluation can lie. The rest are conventions, but conventions with reasons: almost all come from Wilson and colleagues’ “Good enough practices in scientific computing” (2017), and experience in templates such as Cookiecutter Data Science.

Anatomy of a research project

The project skeleton already exists from the environments lesson: an installable package with pyproject.toml, atlas_lab, in src/ layout, installed editable with uv sync. Everything around it remains. The course’s complete structure is:

atlas-lab/
├── pyproject.toml          # paquete, dependencias y configuración de las herramientas
├── uv.lock                 # resolución exacta del entorno
├── README.md               # cómo instalar y cómo reproducir cada resultado
├── .gitignore  .pre-commit-config.yaml  .env.example
├── src/atlas_lab/          # el paquete: todo el código que produce resultados, con tests
├── tests/                  # pytest, fuera del paquete
├── configs/                # configuraciones declarativas (base.yaml y variantes)
├── scripts/                # puntos de entrada finos: entrenar.py, evaluar.py, tabla2.py
├── notebooks/              # exploración; importan de atlas_lab; se versionan sin salidas
├── docs/cuaderno.md        # cuaderno de laboratorio y registro de decisiones
├── reports/figures/        # figuras del informe, generadas por scripts
├── data/                   # README.md y MANIFEST.sha256 versionados; el resto no
│   ├── raw/                #   datos originales, inmutables          (ignorado)
│   └── processed/          #   derivados, regenerables               (ignorado)
└── runs/                   # una carpeta por ejecución               (ignorado)

Each folder has different change rate and standards. src/ changes slowly with tests; notebooks/ changes quickly without guarantees; configs/ changes each experiment but is small declarative text, so git diff between configurations states exactly how two runs differ. scripts/ is deliberately thin: read configuration, call package functions and write to runs/. If a script grows its own logic, move that logic to the package.

The next interactive starts from the motivation’s chaotic folder. Placing each file requires deciding what it is (source or derived, reliable or exploratory) and the tool checks consequences.

InteractiveOrganize a messy project
Unsorted project folder (17)
precios_2019_2024.parquet 340 MB
Original data, downloaded once.
Select a folder to place it.
Versioned in git
./project and environment description
.gitignore
src/atlas_lab/the package: tested code
scripts/thin entry points
configs/experiment configurations
notebooks/exploration, without outputs
tests/pytest
docs/notebook and decisions
reports/figures/report figures
Outside git
data/raw/immutable, with manifest
data/processed/regenerable
runs/one folder per run
Deletegit already stores old versions
Resulting tree
atlas-lab/
├── pyproject.toml
├── uv.lock
├── README.md
├── .gitignore
└── tests/
└── test_modelo.py
Generated .gitignore
# environment and caches
.venv/
__pycache__/
.ipynb_checkpoints/
# secrets: version .env.example
.env
Placed4 of 21
In a good location4 of 21
Size entering git317 kB
Outside git (ignored)0 kB
Problems detected0
Drag each file to its folder, or click it and then the folder. The selected file card explains what it is and, once placed, whether it is a good location. Readouts count megabytes entering git and the panel flags three issues of content rather than placement: duplicated divergent function across two notebooks, circular import between utils.py and modelo.py (appearing once both are in the package) and entrenar.py's absolute path. Each has a fix. Start with the 340 MB parquet: what happens if left in root? Then enable nbstripout and inspect notebook size. Below, the resulting tree and .gitignore.

Three issues detected by the tool deserve comment because moving files does not fix them.

Duplicated code diverges. The two copies of cargar_datos began identical. A week later one notebook added fillna(0) and the other dropna(). The versions produce different tables, making results incomparable without warning. The only defense is one definition.

Circular imports. If utils imports Modelo from modelo and modelo imports normalizar from utils, the result depends on order: executing import atlas_lab.utils, Python begins utils, reaches from atlas_lab.modelo import Modelo, starts modelo, which requests normalizar from utils while it is only partially executed. It fails with ImportError: cannot import name 'normalizar' from partially initialized module. Importing in the opposite order may work, which is worse: failure appears in one script and not another. The fix is structural: package import graph must be acyclic, with layers depending only on those below (data, then model, training, evaluation). A utils module depending on everything and depended on by everything is almost always the cycle’s cause.

Absolute paths. C:/Users/rafa/Desktop/datos/precios.parquet works on one machine in one folder. The path should come from configuration with an environment-variable override per machine: prior lesson’s configuration management applied to paths.

The golden rule: notebooks import from the package

A notebook is a good place to think and a poor place to store code results depend on. This is not taste: a notebook has hidden state (execution order is not page order), cannot be imported elsewhere without tricks, its diffs are unreadable and nobody writes tests for a cell. The rule solving this fits on one line:

Code producing a result lives in a package module with a test; notebooks import it.

In practice, explore in notebooks/01-exploracion.ipynb. When a function is used twice or a cell produces something destined for a report, move it to src/atlas_lab/ and write a test. The notebook imports it:

%load_ext autoreload
%autoreload 2
from atlas_lab.datos import cargar_datos      # una sola definición, con tests
from atlas_lab.config import ruta_datos

df = cargar_datos(ruta_datos() / "raw" / "precios.parquet")

Because the package is installed editable, autoreload picks up module changes without restarting the kernel. And when exploratory analysis becomes a paper figure, do not run the notebook “one last time”: write reports/make_fig3.py, reading an identified run from runs/ and saving reports/figures/fig3.pdf. The notebook remains a record of how you got there.

Data and artifacts: what stays out of the repository

Git is designed for text changing incrementally. A large binary modified over time stores a new complete copy each version, and what enters history does not leave: git rm --cached datos.csv stops tracking the file from that commit onward, but 300 MB remains in every clone, in all prior commits. Purging requires rewriting history (with git filter-repo) and everyone cloning again. Apply the rule before the first commit:

  • Not in git: raw and processed data, checkpoints and weights, run and tracking-tool folders (runs/, wandb/), notebook outputs, environments and caches (.venv/, __pycache__/), and all secrets (.env, API keys).
  • In git: code, tests, configurations, pyproject.toml and uv.lock, documentation, notebooks without outputs, data/README.md (how to obtain data) and data/MANIFEST.sha256 (how to verify it).

The .gitignore enforcing this is short:

.venv/
__pycache__/
.ipynb_checkpoints/
.env
/data/raw/
/data/processed/
/runs/
wandb/
*.pt

Notice data/raw/ and data/processed/ are ignored, not data/. If you ignored data/, you could not version data/README.md even with an exception rule: git documentation explicitly says a file cannot be re-included if a parent directory is excluded, because git does not enter it. When unsure why a file is ignored or not, git check-ignore -v ruta prints the exact responsible .gitignore line.

Data outside git is not uncontrolled. Two mechanisms replace version control:

  • Configurable paths. Code never contains an absolute path; it obtains one from a function like ruta_datos(), reading environment variable ATLAS_DATA_DIR or, if absent, the configs/base.yaml value.
  • Checksums. data/MANIFEST.sha256 contains one line per file with its SHA-256 sum. If someone “corrects” a price by hand, the sum changes even if size does not. The entire manifest’s sum also identifies the dataset for saving with each run.
[ ]A SHA-256 checksum manifestBrowser
import hashlib, tempfile
from pathlib import Path
import numpy as np

def sha256(ruta, bloque=1 << 20):
    """Suma SHA-256 de un fichero, leído por bloques de 1 MiB (sirve para ficheros de cualquier tamaño)."""
    h = hashlib.sha256()
    with open(ruta, "rb") as f:
        while trozo := f.read(bloque):
            h.update(trozo)
    return h.hexdigest()

def escribir_manifiesto(raiz):
    """Una línea «suma  ruta» por fichero, el mismo formato que sha256sum (sha256sum -c lo verifica)."""
    raiz = Path(raiz)
    lineas = [f"{sha256(p)}  {p.relative_to(raiz).as_posix()}"
              for p in sorted(raiz.rglob("*")) if p.is_file() and p.name != "MANIFEST.sha256"]
    (raiz / "MANIFEST.sha256").write_text("\n".join(lineas) + "\n", encoding="utf-8")
    return lineas

def verificar(raiz):
    raiz = Path(raiz)
    problemas = []
    for linea in (raiz / "MANIFEST.sha256").read_text(encoding="utf-8").splitlines():
        esperada, nombre = linea.split("  ", 1)
        p = raiz / nombre
        if not p.is_file():
            problemas.append(f"falta {nombre}")
        elif sha256(p) != esperada:
            problemas.append(f"ha cambiado {nombre}")
    return problemas

with tempfile.TemporaryDirectory() as tmp:
    datos = Path(tmp) / "data"
    (datos / "raw").mkdir(parents=True)
    rng = np.random.default_rng(0)
    precios = 100 * np.exp(np.cumsum(rng.normal(0, 0.01, 50_000)))
    np.savetxt(datos / "raw" / "precios.csv", precios, fmt="%.6f", header="precio", comments="")
    (datos / "raw" / "LEEME.txt").write_text("Descargado el 2026-02-05 de la fuente X.\n", encoding="utf-8")

    for linea in escribir_manifiesto(datos):
        print(linea[:16] + "…" + linea[64:])
    print("verificación:", verificar(datos) or "todo coincide")

    # alguien «corrige» un precio a mano: el tamaño no cambia, la suma sí
    ruta = datos / "raw" / "precios.csv"
    texto = ruta.read_text(encoding="utf-8")
    i = texto.index("\n", 1000) + 1
    viejo = texto[i]
    nuevo = "1" if viejo != "1" else "2"
    ruta.write_text(texto[:i] + nuevo + texto[i + 1:], encoding="utf-8")
    print(f"tras cambiar un carácter ({viejo} → {nuevo}) en {ruta.stat().st_size} bytes:", verificar(datos))

For changing datasets that must be shared, tools generalize this idea: git LFS stores a pointer in the repository and content on another server, while DVC versions small .dvc files with each artifact’s checksum and syncs content to remote storage. For a personal project with a few unchanging raw files, a manifest suffices.

Automated quality with pre-commit

Structure degrades if it depends on discipline. The remedy is to have the machine check what is easy to forget at each commit. Git provides the mechanism: before creating a commit it runs .git/hooks/pre-commit, if present, and aborts if it exits nonzero. Writing these programs manually is tedious and they are not versioned (.git/ does not travel with the repository), so use the pre-commit framework, declaring them in a versioned file.

The course configuration:

# .pre-commit-config.yaml
default_install_hook_types: [pre-commit, pre-push]
default_stages: [pre-commit]       # sin esto, cada gancho correría también en pre-push
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0                    # rev de ejemplo: «pre-commit autoupdate» la sube a la última etiqueta
    hooks:
      - id: check-added-large-files
        args: ["--maxkb=500"]
      - id: check-merge-conflict
      - id: detect-private-key
  - repo: https://github.com/kynan/nbstripout
    rev: 0.8.1
    hooks:
      - id: nbstripout             # vacía salidas y contadores de ejecución de los .ipynb
  - repo: local                    # herramientas del propio entorno: versiones fijadas en uv.lock
    hooks:
      - id: ruff-check
        name: ruff check
        entry: uv run ruff check --fix
        language: system
        types_or: [python, jupyter]
      - id: ruff-format
        name: ruff format
        entry: uv run ruff format
        language: system
        types_or: [python, jupyter]
      - id: mypy
        name: mypy
        entry: uv run mypy
        language: system
        types: [python]
        pass_filenames: false      # mypy revisa el paquete entero, no solo los ficheros cambiados
      - id: pytest-rapido
        name: pytest (rápidos)
        entry: uv run pytest -m "not slow" -q -x
        language: system
        pass_filenames: false
        always_run: true
      - id: pytest-completo
        name: pytest (todos)
        entry: uv run pytest -q
        language: system
        pass_filenames: false
        always_run: true
        stages: [pre-push]         # los lentos, solo antes de subir

And the part of pyproject.toml configuring the tools:

[tool.ruff]
line-length = 110

[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "NPY"]

[tool.mypy]
files = ["src"]
warn_unused_ignores = true

[tool.pytest.ini_options]
testpaths = ["tests"]
markers = ["slow: tests largos, fuera del gancho de pre-commit"]

Each hook has a reason:

  • ruff check detects real errors (undefined names, unused imports, mutable default arguments with rule B006) and sorts imports (I). Family NPY includes NPY002, prohibiting np.random.seed and legacy global generator functions, the cause of half a reproducibility lesson. ruff format ends formatting debates and keeps diffs limited to content changes.
  • mypy performs static type checking on the package. It runs over all src because a module signature change breaks callers not among modified files.
  • nbstripout clears notebook outputs and execution counters. An embedded figure makes a notebook megabytes of base64, every run changes it throughout and its diff is unreadable; without outputs it is kilobytes and its diff shows changed code.
  • check-added-large-files rejects new files over 500 kB, the last barrier against parquet at root. detect-private-key searches for private keys.
  • quick pytest runs tests without the slow marker. It is lesson testing’s tests with fixtures and parametrization, excluding those actually training, which move to pre-push and CI.

Add tools once with uv add --dev pre-commit ruff mypy nbstripout, install hooks in each clone with uv run pre-commit install, and uv run pre-commit run --all-files runs them on the whole repository (the first thing to do when adding it to an existing project). Two operation details avoid surprises. pre-commit passes each hook only staged files and temporarily sets aside unstaged changes, so exactly what enters is checked. A hook that modifies files (ruff with --fix, formatter, nbstripout) fails the commit: review changes, stage with git add and retry.

Time budget matters more than the list. If a hook takes a minute you will eventually use git commit --no-verify, defeating it. Aim for pre-commit to take seconds: hence slow tests are marked and moved to pre-push.

To see there is no magic, here is a toy pre-commit with four hooks applied to a commit with the usual problems. It imitates real messages and semantics: a hook modifying files fails even if it fixed them.

[ ]A toy pre-commitBrowser
import json, re

MAX_KB = 500
RUTA_ABSOLUTA = re.compile(r"""["'](?:[A-Za-z]:[\\/]|/home/|/Users/)""")

def grandes(ficheros):
    """Como check-added-large-files: nada por encima de MAX_KB."""
    malos = [f"{r}: {len(b) // 1024} KB" for r, b in ficheros.items() if len(b) > MAX_KB * 1024]
    return not malos, malos, ficheros

def sin_salidas(ficheros):
    """Como nbstripout: vacía salidas y contadores de los notebooks y reescribe el fichero."""
    nuevos, cambios = dict(ficheros), []
    for r, b in ficheros.items():
        if not r.endswith(".ipynb"):
            continue
        nb = json.loads(b)
        sucio = False
        for celda in nb["cells"]:
            if celda["cell_type"] == "code" and (celda["outputs"] or celda["execution_count"] is not None):
                celda["outputs"], celda["execution_count"], sucio = [], None, True
        if sucio:
            nuevos[r] = (json.dumps(nb, indent=1, ensure_ascii=False) + "\n").encode()
            cambios.append(f"{r}: {len(b) // 1024} KB → {len(nuevos[r])} bytes")
    return not cambios, cambios, nuevos

def rutas_absolutas(ficheros):
    malos = [f"{r}:{n}: {linea.strip()}"
             for r, b in ficheros.items() if r.endswith(".py")
             for n, linea in enumerate(b.decode().splitlines(), 1) if RUTA_ABSOLUTA.search(linea)]
    return not malos, malos, ficheros

def claves_privadas(ficheros):
    malos = [r for r, b in ficheros.items() if b"PRIVATE KEY-----" in b or b"API_KEY=" in b]
    return not malos, malos, ficheros

GANCHOS = [("check for added large files", grandes), ("nbstripout", sin_salidas),
           ("rutas absolutas en el código", rutas_absolutas), ("detect private key", claves_privadas)]

def pre_commit(preparados):
    """Ejecuta los ganchos sobre los ficheros preparados (staged). Devuelve el código de salida
    y los ficheros tal como quedan en el directorio de trabajo (los ganchos pueden modificarlos)."""
    codigo = 0
    for nombre, gancho in GANCHOS:
        ok, detalles, preparados = gancho(preparados)
        print(f"{nombre:.<56}{'Passed' if ok else 'Failed'}")
        for d in detalles:
            print("    " + d)
        codigo |= not ok
    return codigo, preparados

figura = "iVBORw0KGgo" + "A" * 400_000            # un PNG en base64 dentro de una salida
nb = {"cells": [{"cell_type": "code", "execution_count": 7, "metadata": {}, "source": ["plt.plot(x)"],
                 "outputs": [{"output_type": "display_data", "data": {"image/png": figura}}]}],
      "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
preparados = {
    "notebooks/exploracion.ipynb": json.dumps(nb).encode(),
    "scripts/entrenar.py": b'import pandas as pd\ndf = pd.read_parquet("C:/Users/rafa/Desktop/precios.parquet")\n',
    "runs/ckpt.pt": bytes(2_000_000),
    "src/atlas_lab/datos.py": b"def cargar(ruta):\n    ...\n",
}
codigo, arbol = pre_commit(preparados)
print("código de salida:", codigo, "(el commit no se hace)\n")

# se arregla lo que el gancho no arregla solo, se quita el checkpoint y se vuelve a preparar
arbol["scripts/entrenar.py"] = b'import pandas as pd\nfrom atlas_lab.config import ruta_datos\ndf = pd.read_parquet(ruta_datos() / "precios.parquet")\n'
del arbol["runs/ckpt.pt"]
codigo, _ = pre_commit(arbol)
print("código de salida:", codigo)

The second pass is clean because nbstripout already stripped the notebook on the first: exactly what real pre-commit shows, a failed first attempt leaving files fixed and a second passing.

Git as a lab notebook

In software projects, git records code evolution. In research it can record something more valuable: what was tried, in what order and with what result. Four mechanisms used with specific intent suffice.

Small intentional commits

A commit is git’s minimum unit to compare, revert and bisect. If one mixes a normalization change, new optimizer and notebook cleanup, there is no way to know which moved the metric or undo one without the others. Few rules:

  • One change per commit, with a message saying what and why: warmup: pico de lr 3e-4 (configs/lr3e-4.yaml); reduce la pérdida inicial. git add -p stages only part of a file when two things changed at once.
  • No important run from a dirty tree. A run identifier should include commit and whether there were uncommitted changes: git describe --always --dirty returns something like res/tabla2-v1-3-ged923b6-dirty (three commits after the tag, at commit ed923b6, with local changes). This is central to run provenance: if -dirty appears, the commit does not describe the executed code and the result cannot be reconstructed.
  • Commit before launch, not after. Launching six-hour training and committing “when it finishes” is the commonest way to lose correspondence between code and result.

Branches by hypothesis

Each hypothesis requiring code changes is tested on its branch: git switch -c hip/warmup-largo. If confirmed (with seeds and comparison required by multi-seed evaluation), merge with git merge --no-ff hip/warmup-largo, creating a merge commit even when fast-forward is possible: the branch remains visible in history as one unit. git log --first-parent main then shows main as a sequence of decisions, one per merge.

If a hypothesis is discarded, do not simply delete the branch. A commit unreachable from any branch or tag is eventually removed by git gc when reflog expires; a discarded hypothesis is a result (negative, but a result) worth retaining. Convention is tag then delete branch: git tag -a archivo/label-smoothing -m "descartada: ECE mejor, precisión igual; ver cuaderno 11 feb" and git branch -D hip/label-smoothing. Branch list remains short and history complete.

Tags by result

An annotated tag (git tag -a) is an object with name, author, date and message pointing to a commit. Use one per published or shared result: git tag -a res/tabla2-v1 -m "Tabla 2 del borrador 1: base.yaml, semillas 0-4, datos 9c2e41b". Tags do not push themselves: git push origin res/tabla2-v1. With them, “reproduce table 2” means git switch --detach res/tabla2-v1 and run the script specified in README. git describe also uses them as reference points to name later commits.

Worktrees: two versions at once

A recurring case: long training runs on branch hip/mixer while you want to keep working on main. Switching branch in the same directory would change files beneath the running process. A worktree is another working directory of the same repository:

git worktree add ../atlas-mixer hip/mixer     # nuevo directorio con hip/mixer, mismo .git
cd ../atlas-mixer && uv sync                  # su propio .venv, con atlas_lab apuntando a ESTE src/
uv run python scripts/entrenar.py --config configs/mixer.yaml
git worktree list                             # cuántos hay y en qué commit está cada uno
git worktree remove ../atlas-mixer            # al terminar

Both directories share history, branches and tags but not files, and git prevents the same branch being in two worktrees simultaneously. The biting detail is environment: editable installation points to one particular directory’s src/. If from ../atlas-mixer you run Python from the main directory’s .venv, you silently import main’s code. Each worktree needs its own uv sync.

The following interactive shows a month of a project run this way. It is simulated, but each piece is as just described.

InteractiveBranches as research lines
mainhip/warmup-largohip/label-smoothinghip/mixerruns/2026-02-07_1412/ · 88.1 ± 0.2runs/2026-02-07_1412/ · 88.1 ± 0.2runs/2026-02-07_1412/ · 88.1 ± 0.2runs/2026-02-07_1412/ · 88.1 ± 0.2runs/2026-02-07_1412/ · 88.1 ± 0.2runs/2026-02-10_0930/ · 89.2runs/2026-02-13_1805/ · 89.4 ± 0.2runs/2026-02-13_1805/ · 89.4 ± 0.2runs/2026-02-13_1805/ · 89.4 ± 0.2runs/2026-02-13_1805/ · 89.4 ± 0.2runs/2026-02-13_1805/ · 89.4 ± 0.2runs/2026-02-11_1120/ · 88.0 ± 0.3, ECE 1.4runs/2026-02-11_1120/ · 88.0 ± 0.3, ECE 1.4runs/2026-02-11_1120/ · 88.0 ± 0.3, ECE 1.4runs/2026-02-11_1120/ · 88.0 ± 0.3, ECE 1.4runs/2026-02-11_1120/ · 88.0 ± 0.3, ECE 1.4runs/2026-02-18_1540/ · 89.5 ± 0.2runs/2026-02-18_1540/ · 89.5 ± 0.2runs/2026-02-18_1540/ · 89.5 ± 0.2runs/2026-02-18_1540/ · 89.5 ± 0.2runs/2026-02-18_1540/ · 89.5 ± 0.2runs/2026-02-19_2210/ · 86.2 (2 diverge)runs/2026-02-19_2210/ · 86.2 (2 diverge)runs/2026-02-19_2210/ · 86.2 (2 diverge)runs/2026-02-19_2210/ · 86.2 (2 diverge)runs/2026-02-19_2210/ · 86.2 (2 diverge)runs/2026-02-21_0815/ · 87.9 ± 0.6runs/2026-02-21_0815/ · 87.9 ± 0.6runs/2026-02-21_0815/ · 87.9 ± 0.6runs/2026-02-21_0815/ · 87.9 ± 0.6runs/2026-02-21_0815/ · 87.9 ± 0.6runs/2026-02-24_1610/ · 89.5 ± 0.1runs/2026-02-24_1610/ · 89.5 ± 0.1runs/2026-02-24_1610/ · 89.5 ± 0.1runs/2026-02-28_2345/ · 89.7b571bf2 start: atlas_lab package, configs and testsdc4c8f0 data: SHA-256 manifest of prices 2019–202405b2255 baseline: reference model and training loop4d6a172 hypothesis: linear warmup of 2000 steps1bff528 hypothesis: label smoothing 0.15914bad warmup: peak lr 3e-4 (configs/lr3e-4.yaml)29c862a merge hip/warmup-largo: +1.3 points with 5 seedsd9a9d6d eval: per-seed metrics in runs/<id>/metricas.json1838129 table 2: 5-seed sweep with base.yaml5fc0be5 hypothesis: mixer block instead of MLP518d2f3 mixer: normalization before block11ce7a5 fig3: reports/make_fig3.py59bb1af refactor: datos.py with cargar_datos testsed923b6 docs: README with reproduction instructionsHEADres/tabla2-v1res/fig3archivo/label-smoothingarchivo/mixerTable 2Figure 3Figure 5Figure A1report artifacts03 Feb11 Feb18 Feb28 Feb
  • commit (hollow: merge)
  • abandoned branch
  • run, one mark per seed
  • run with dirty tree
  • result tag
Provenance of Figure 3
reports/figures/fig3.pdf
← reports/make_fig3.py
← runs/2026-02-24_1610/ (3 seeds: 89.5 ± 0.1)
commit 11ce7a5 on main, tag res/fig3; config configs/base.yaml
data 9c2e41b (hash from data/MANIFEST.sha256)
Complete chain: with the commit, configuration and data hash, git worktree add and the script reproduce the artifact.
Select a commit in the graph to read its message, runs and notebook entry.
Commit graph of a simulated four-week project: main, a hypothesis branch merged and two discarded and archived with tags. Squares under each commit are runs, one per seed; below are four report artifacts. Start following figure 3: its chain reaches a tagged commit without gaps. Switch to figure 5: where does it break and why? Figure A1 contains negative results: follow its runs to abandoned branches and click commits to read notebook expectations and decisions. Enable worktrees to see what ran simultaneously.

Notice what the graph allows that a folder of dated files would not: figure 3 is reconstructed with four automatically saved pieces (commit, configuration, data checksum, seeds); figure 5 is marked unreproducible when generated, not three months later; and both discarded hypotheses remain accessible with reasons even though no branch names them anymore.

git bisect: binary search in history

On Monday you discover HEAD validation accuracy is 91.4, while three Fridays ago at tag res/tabla2-v1 it was 92.0. There are 200 commits between them. Reviewing one by one is impractical and guessing worse. But if you can evaluate any commit and decide “good” or “bad”, the problem has a known optimal solution: binary search applied to history. This is the same idea as lesson debugging’s systematic bug bisection, splitting data or configuration; here what is split is time.

There are nn candidates for first bad commit, c1,…,cnc_1, \dots, c_n (c0c_0 is good by assumption). The algorithm maintains two indices, bb and mm, with an invariant, and each evaluation halves candidate count.

Proof

(2) Invariant “B(cb)B(c_b) is false and B(cm)B(c_m) is true” holds initially by assumption and is preserved each step, because kk is assigned to mm only when B(ck)B(c_k) is true and to bb when false. Also b<k<mb < k < m while m−b≥2m - b \ge 2, so interval strictly shrinks. At termination m−b=1m - b = 1 and the invariant states exactly that (cm−1,cm)(c_{m-1}, c_m) is a transition.

(1) Let L=m−bL = m - b be candidate count. With k=⌊(b+m)/2⌋k = \lfloor (b + m)/2 \rfloor, the new LL is k−b=⌊L/2⌋k - b = \lfloor L/2 \rfloor or m−k=⌈L/2⌉m - k = \lceil L/2 \rceil; both at most ⌈L/2⌉\lceil L/2 \rceil. By induction, after tt evaluations Lt≤⌈n/2t⌉L_t \le \lceil n/2^t \rceil, using ⌈⌈x⌉/2⌉=⌈x/2⌉\lceil \lceil x \rceil / 2 \rceil = \lceil x/2 \rceil for real xx. The algorithm stops once Lt=1L_t = 1, guaranteed if n/2t≤1n/2^t \le 1, that is, t≥log⁡2nt \ge \log_2 n.

(3) If BB is monotone, B(ci)B(c_i) is false for i<i⋆i < i^\star and true for i≥i⋆i \ge i^\star, and the only transition is at i⋆i^\star.

∎

With 1000 commits, ten evaluations; with a million, twenty. The bound is also best possible: no strategy, however clever, guarantees finding the culprit in fewer than ⌈log⁡2n⌉\lceil \log_2 n \rceil evaluations in the worst case. The argument is the decision-tree bound: any strategy is a binary tree whose leaves are answers, must have at least nn distinct leaves, and a binary tree of depth dd has at most 2d2^d leaves. You will reconstruct it step by step in the exercises.

Theorem point (2) has an important practical reading: without monotonicity, bisect finds a transition, not necessarily the one sought. If a failure appeared in c20c_{20}, was fixed in c40c_{40} and reappeared in c50c_{50}, bisect from c0c_0 may point to c20c_{20}, a failure no longer present in HEAD. Defense is choosing a recent known-good commit (the last where you know the metric was fine), not the oldest one imaginable.

[ ]Bisection from scratchBrowser
import math

def bisect(n, es_malo, bueno=0):
    """Historial lineal c0 ... c_{n-1}; c_bueno es bueno y c_{n-1} (HEAD) es malo.
    Devuelve (primer commit malo encontrado, evaluaciones)."""
    malo = n - 1
    evaluaciones = 0
    # invariante: es_malo(bueno) es falso y es_malo(malo) es cierto
    while malo - bueno > 1:
        medio = (bueno + malo) // 2
        evaluaciones += 1
        if es_malo(medio):
            malo = medio
        else:
            bueno = medio
    return malo, evaluaciones

# 1. Corrección y peor caso: probamos todos los culpables posibles
for n in [64, 65, 1001]:
    peor = 0
    for culpable in range(1, n):
        hallado, k = bisect(n, lambda i: i >= culpable)
        assert hallado == culpable
        peor = max(peor, k)
    N = n - 1
    print(f"{N:5d} candidatos: peor caso {peor:2d} evaluaciones, ceil(log2 N) = {math.ceil(math.log2(N))}")

# 2. Predicado no monótono: un fallo que apareció en c20, se arregló en c40 y volvió en c50
def es_malo(i):
    return 20 <= i < 40 or i >= 50

print("\nbisect desde c0:  ", bisect(64, es_malo))
print("bisect desde c45: ", bisect(64, es_malo, bueno=45))

git bisect in practice

A manual session has four commands. git bisect start <malo> <bueno> fixes endpoints and checks out the middle commit; after evaluating it, git bisect good or git bisect bad classify it and git jumps to the next; git bisect skip omits it if unevaluable; and git bisect reset returns everything to its previous position. When the interval reduces to one commit, git prints <hash> is the first bad commit with message and files.

git bisect start HEAD res/tabla2-v1               # malo, bueno
git bisect run python ../bisect_eval.py 91.7      # automatiza todas las evaluaciones
git bisect log > bisect.log                       # registro de decisiones (git bisect replay lo repite)
git bisect reset

git bisect run executes the script on each commit and reads its exit code:

Exit codeMeaning for bisect
0commit is good
1 through 127, except 125commit is bad
125commit cannot be evaluated: skipped, like skip
anything elseabort bisection

Three options save work. git bisect start --term-old=rapido --term-new=lento changes state names when searching for a change rather than failure (commit slowing training, improving a metric). --first-parent traverses mainline only and treats each merge as a unit, desirable if hypothesis branches have unevaluable intermediate commits. And paths at the end, git bisect start HEAD v1 -- src/ configs/, restrict candidates to commits touching those paths.

The script is delicate, and almost all its mistakes silently point to the wrong commit:

  • It must live outside the repository (or at least outside tracked files), because bisect changes the working directory to old commits where the script did not exist or differed.
  • It must distinguish “bad” from “unevaluable”. A commit missing a module, with syntax error or without configs/base.yaml yet says nothing about the metric: exit 125. An uncaught exception makes Python exit 1, which bisect interprets as bad.
  • The metric must be stable. Next section: fixed seeds, calibrated threshold and repetition if needed.
  • It must be fast. It runs ⌈log⁡2n⌉\lceil \log_2 n \rceil times (plus skips), so evaluate with a data subset and short training as long as regression remains visible in the reduced version. Check this at both endpoints first.
Interactivegit bisect on a metric
91.0091.2591.5091.7592.0092.2592.50validation accuracy (%)τ = 91.7063 candidatesc0 · 9d30395c1 · d846681c2 · 5a08d0fc3 · 803a385c4 · 2f701b0c5 · 3a85735c6 · 807b107c7 · 83d4f50c8 · f967d17c9 · b80bbcfc10 · 1200843c11 · 34321aac12 · 080309fc13 · 5ada9cbc14 · 45fd203c15 · 9ea6afbc16 · 6eeaba6c17 · f4fd899c18 · 284b7bcc19 · 0daeefec20 · 37958f0c21 · 826c193c22 · 96e4ff4c23 · 8ffd24ac24 · 55aacf3c25 · e0b7321c26 · 5ad5355c27 · f25d37ac28 · 30ab6acc29 · e83d6d2c30 · dd3b934c31 · ba821e6c32 · 6eb89acc33 · 196a51bc34 · 3ba27edc35 · afc5615c36 · 6d2c874c37 · 0a918ecc38 · 2578837c39 · c737427c40 · 81a998ac41 · a2ece45c42 · 36c642dc43 · 7b2ab1fc44 · 7908911c45 · 9612dcdc46 · 964ee24c47 · d311b52c48 · 278bb5ec49 · 4750b09c50 · c0d1d83c51 · 41653bdc52 · 612b742c53 · 5629aafc54 · a453babc55 · c568058c56 · 80d4422c57 · e5d54c8c58 · 4ec0b37c59 · 0bca35ac60 · e8cea54c61 · c06a079c62 · 87c74ffc63 · 0517952c0c8c16c24c32c40c48c56c63
  • good (measured or inferred)
  • bad (measured or inferred)
  • commit being evaluated
  • script threshold

Model: the regression costs 0.6 points. An evaluation is the metric plus Gaussian noise of standard deviation σ; with “Fixed seed”, fraction ρ of noise is shared by all commits, the rest is specific, and repetition returns the same number. Select a commit in the interval to evaluate it instead of bisect’s proposal.

Evaluation per commit
0.30
1
0.80
91.70
Candidates for first bad commit63 (c1 to c63)
Bisect evaluations0 (bound: ⌈log₂ 63⌉ = 6)
Script runs0
Effective threshold τ\tau91.70
Simulated success (2000 histories)100.0 %
Theoretical success100.0 %
A history of 64 commits: c0 is last known good and c63 (HEAD) first known bad; at an unknown commit accuracy drops 0.6 points. Above, measurements of each evaluated commit versus script threshold; below, commit strip with candidate interval. Start with exact evaluations: press ‘Evaluate’, compare to threshold and mark the commit, watching the interval halve until the culprit in 6 steps. Then switch to ‘Random seed’ with σ=0.3\sigma = 0.3 and run git bisect run repeatedly with ‘New history’: how many succeed? Raise repetitions rr and compare simulation to theory. Try ‘Fixed seed’ and press ‘Repeat in this history’: each commit gives the same number and bisect reaches the same place, but does it succeed more? Enable threshold calibrated with the same seeds and raise ρ\rho. Finally enable commits that do not compile.

Noisy evaluations: threshold, seeds and repetitions

With a training metric, “good” and “bad” are not directly observable. What is observed is a noisy measurement. A minimal but faithful model: commit cic_i‘s metric is

Mi=μi+σε,μi={μgi<i⋆μg−Δi≥i⋆,ε∼N(0,1),M_i = \mu_i + \sigma\varepsilon, \qquad \mu_i = \begin{cases} \mu_g & i < i^\star \\ \mu_g - \Delta & i \ge i^\star \end{cases}, \qquad \varepsilon \sim \Normal(0, 1),

where Δ>0\Delta > 0 is regression size and σ\sigma the standard deviation of an evaluation (variation across seeds, splits, nondeterministic runs). The script decides “good” if Mi≥τM_i \ge \tau. With threshold at midpoint, τ=μg−Δ/2\tau = \mu_g - \Delta/2, one evaluation is wrong with probability

p=P(σε<−Δ/2)=Φ ⁣(−Δ2σ),p = \Pr\big(\sigma\varepsilon < -\Delta/2\big) = \Phi\!\Big(-\frac{\Delta}{2\sigma}\Big),

with Φ\Phi the standard normal distribution function, and the same probability for a bad commit appearing good. The next result describes what this does to bisection.

Proof

The key is that one error is irreversible. Call a step correct if it classifies the evaluated commit correctly. While all steps are correct, the culprit is in candidate interval (b,m](b, m] and bisection follows precisely the error-free path k1,k2,…k_1, k_2, \dots. If step jj is the first error, there are two cases: if kj≥i⋆k_j \ge i^\star (bad) is classified good, new bb is kj≥i⋆k_j \ge i^\star and culprit is outside the interval; if kj<i⋆k_j < i^\star (good) is classified bad, new mm is kj<i⋆k_j < i^\star and culprit is also outside. Later steps only narrow the interval, so the answer inside it is not c⋆c^\star. Success therefore equals all dd steps on the error-free path being correct, and by independence its probability is the product. If n=2dn = 2^d, every path has exactly dd steps, all with success probability 1−p1 - p.

∎

The number is worse than it looks. With Δ=0.6\Delta = 0.6 points and σ=0.3\sigma = 0.3 (regression of only two standard deviations), p=Φ(−1)=0.159p = \Phi(-1) = 0.159, and in the figure’s history (64 commits, 63 candidates: all but one path have six steps) bisection succeeds with probability ≈(1−0.159)6≈0.355\approx (1 - 0.159)^6 \approx 0.355 (exact 0.356 averaging over culprit position): twice in three times it names an innocent commit with the same apparent confidence as the culprit. You will see it with “Random seed” and r=1r = 1. There are four remedies, each worth understanding.

Average rr independent evaluations. The mean of rr measurements has standard deviation σ/r\sigma/\sqrt{r}, so per-step error falls to pr=Φ(−r Δ/(2σ))p_r = \Phi(-\sqrt{r}\,\Delta/(2\sigma)). To guarantee success at least 1−δ1 - \delta, the union bound says d pr≤δd\,p_r \le \delta suffices:

r≥(2σ zδ/dΔ)2,zq=Φ−1(1−q).r \ge \Big(\frac{2\sigma\, z_{\delta/d}}{\Delta}\Big)^2, \qquad z_q = \Phi^{-1}(1 - q).

With the previous numbers, δ=0.05\delta = 0.05 and d=6d = 6, z0.0083=2.39z_{0.0083} = 2.39 and r≥5.73r \ge 5.73: six evaluations per commit give success 0.9580.958 at six times the cost. Total cost is d rd\,r evaluations, growing with the logarithm of commit count and square of σ/Δ\sigma/\Delta: a regression half as large costs four times as much to find.

Vote when only pass or fail is available. If the test is binary (an occasionally failing test, a threshold outside your control), repeat rr times (odd) and decide by majority. Majority is wrong if more than half the tests err, a binomial tail which by Hoeffding’s inequality satisfies pmay≤exp⁡(−2r(1/2−p)2)p_{\text{may}} \le \exp(-2r(1/2 - p)^2) when p<1/2p < 1/2: it decreases exponentially with rr. The bound is conservative (with p=0.2p = 0.2, reducing below 0.01 requests r≥26r \ge 26 and 13 suffices), but says the essential thing: any test right more than half the time can be amplified. Voting wastes information if the continuous metric is available: with Gaussian noise, averaging beats voting at equal evaluation count from r=3r = 3 (the mean is the sufficient statistic, and comparing mean with midpoint is the likelihood-ratio test), as the next cell shows.

Fix the seed. With a fixed seed, evaluating the same commit twice gives the same number, essential for reproducible bisect decisions: git bisect replay repeats the session and a commit does not change sides between runs. But a fixed seed does not eliminate error; it freezes it: if seed 0 makes commit c40c_{40}, true value 91.4, measure 91.57, it will always measure 91.57: 0.17 points of error are frozen and repetition is useless. Fixed seeds do correlate noise between commits. If a change does not alter random-generator consumption, commits evaluated with the same seed see the same split and initialization, and much noise is common. Write noise as σ(ρ us+1−ρ2 vi,s)\sigma(\rho\, u_s + \sqrt{1 - \rho^2}\, v_{i,s}), with usu_s common to all commits evaluated with seed ss and vi,sv_{i,s} specific to each. With an absolute threshold, the common part shifts all measurements together and can place all on the same side. But if threshold is calibrated with the same seeds, as midpoint of both known endpoint measurements, common noise cancels in comparison and only individual noise remains: each measurement’s standard deviation σ1−ρ2\sigma\sqrt{1 - \rho^2}, and the threshold’s own noise, inherited from both endpoints (standard deviation σ1−ρ2/2\sigma\sqrt{1 - \rho^2}/\sqrt{2}) and shared by all comparisons. This is common random numbers, also making comparison of two models evaluated with the same seeds more precise (seeding strategy).

Several fixed seeds, calibrated threshold. The combination of three ideas is used in practice: a fixed seed list, for example [0, 1, 2, 3, 4], the same on all commits; mean metric over that list; and threshold at the midpoint of endpoint means. It is deterministic, averages individual noise and cancels common noise.

A refinement we will not use but worth knowing: if decisions can be undone (reevaluate an old commit when new measurements contradict them), binary search with noisy answers can use O(log⁡(n/δ))\bigO(\log(n/\delta)) total evaluations for error δ\delta, instead of O(log⁡n⋅log⁡(log⁡n/δ))\bigO(\log n \cdot \log(\log n/\delta)) for repeating each step. This is Feige, Raghavan, Peleg and Upfal’s (1994) result, starting point of noisy binary-search literature.

The first cell implements bisection with majority voting and measures success probability by simulation against the theorem formula; the second compares seed strategies.

[ ]Bisection with noisy testsBrowser
import math, random
from math import comb
from statistics import NormalDist

def bisect_ruidoso(n, prueba, reps=1):
    """Bisección con voto mayoritario: cada commit se prueba reps veces (reps impar)."""
    bueno, malo, llamadas = 0, n - 1, 0
    while malo - bueno > 1:
        medio = (bueno + malo) // 2
        votos = sum(prueba(medio) for _ in range(reps))   # cuántas veces salió «malo»
        llamadas += reps
        if 2 * votos > reps:
            malo = medio
        else:
            bueno = medio
    return malo, llamadas

def p_mayoria(p, r):
    """Probabilidad de que la mayoría de r pruebas independientes con error p se equivoque."""
    return sum(comb(r, k) * p**k * (1 - p) ** (r - k) for k in range(r // 2 + 1, r + 1))

def pasos(n, c):
    """Commits que visita la bisección correcta cuando el culpable es c."""
    bueno, malo, k = 0, n - 1, 0
    while malo - bueno > 1:
        m = (bueno + malo) // 2
        k += 1
        bueno, malo = (bueno, m) if m >= c else (m, malo)
    return k

n, p, ensayos = 64, 0.2, 4000
rng = random.Random(0)
print(f"{n} commits, cada prueba se equivoca con probabilidad p = {p}")
print(" reps   acierto simulado   teoría   pruebas por bisección")
for reps in [1, 3, 5, 9]:
    aciertos = llamadas = 0
    for _ in range(ensayos):
        c = rng.randint(1, n - 1)
        prueba = lambda i: (i >= c) != (rng.random() < p)   # la verdad, invertida con probabilidad p
        hallado, ll = bisect_ruidoso(n, prueba, reps)
        aciertos += hallado == c
        llamadas += ll
    pr = p_mayoria(p, reps)
    teoria = sum((1 - pr) ** pasos(n, c) for c in range(1, n)) / (n - 1)
    print(f"{reps:5d}   {aciertos / ensayos:16.3f}   {teoria:6.3f}   {llamadas / ensayos:10.1f}")

# Ruido gaussiano: promediar r medidas frente a votar con r medidas
Phi = NormalDist().cdf
print("\nRuido gaussiano con Δ/σ = 1 y el umbral en el punto medio")
print("  r   error por paso (media)   error por paso (mayoría)   acierto con 6 pasos (media)")
for r in [1, 3, 9, 25]:
    media = Phi(-math.sqrt(r) / 2)
    mayoria = p_mayoria(Phi(-1 / 2), r)
    print(f"{r:3d}   {media:22.4f}   {mayoria:24.4f}   {(1 - media) ** 6:27.3f}")

Simulation reproduces the theorem formula (theory averages culprit position because with 63 candidates one path has 5 steps and the others 6), and the Gaussian table shows voting’s price: with nine evaluations, averaging leaves per-step error 0.067 and voting 0.110.

[ ]Fixed seed: noise that does not average outBrowser
import math, random

MU, DELTA, SIGMA, RHO, N = 92.0, 0.6, 0.3, 0.8, 64

class Proyecto:
    """Un historial con un culpable y el ruido de evaluación descompuesto por semilla:
    una parte común a todos los commits evaluados con esa semilla y una parte propia de cada commit."""
    def __init__(self, rng):
        self.rng, self.c = rng, rng.randint(1, N - 1)
        self.comun, self.propio = {}, {}

    def metrica(self, i, semilla):
        if semilla not in self.comun:
            self.comun[semilla] = self.rng.gauss(0, 1)
        if (i, semilla) not in self.propio:
            self.propio[(i, semilla)] = self.rng.gauss(0, 1)
        ruido = RHO * self.comun[semilla] + math.sqrt(1 - RHO**2) * self.propio[(i, semilla)]
        return (MU - DELTA if i >= self.c else MU) + SIGMA * ruido

def bisect_metrica(medir, umbral):
    bueno, malo = 0, N - 1
    while malo - bueno > 1:
        m = (bueno + malo) // 2
        bueno, malo = (m, malo) if medir(m) >= umbral else (bueno, m)
    return malo

def estrategia(nombre, rng, ensayos=2000):
    aciertos = 0
    for _ in range(ensayos):
        pr = Proyecto(rng)
        if nombre == "semilla aleatoria, umbral fijo":
            nuevas = iter(range(10**6))                    # una semilla nueva en cada evaluación
            medir, umbral = (lambda i: pr.metrica(i, next(nuevas))), MU - DELTA / 2
        elif nombre == "semilla fija, umbral fijo":
            medir, umbral = (lambda i: pr.metrica(i, 0)), MU - DELTA / 2
        else:
            k = 1 if nombre == "semilla fija, umbral calibrado" else 5
            medir = lambda i: sum(pr.metrica(i, s) for s in range(k)) / k
            umbral = (medir(0) + medir(N - 1)) / 2         # calibrado con las mismas semillas
        aciertos += bisect_metrica(medir, umbral) == pr.c
    return aciertos / ensayos

rng = random.Random(1)
print(f"Δ = {DELTA}, σ = {SIGMA}, ρ = {RHO}: probabilidad de señalar al culpable")
for nombre in ["semilla aleatoria, umbral fijo", "semilla fija, umbral fijo",
               "semilla fija, umbral calibrado", "5 semillas fijas, umbral calibrado"]:
    print(f"  {nombre:36s} {estrategia(nombre, rng):.3f}")

pr = Proyecto(random.Random(7))
print("\nsemilla fija: el mismo commit da siempre lo mismo:", [round(pr.metrica(40, 0), 4) for _ in range(3)])

Fixed seed alone improves little over random: it makes decisions reproducible, not correct. The jump comes from calibrating threshold with the same seeds (common noise cancels; if threshold were exact, individual noise of σ1−ρ2=0.18\sigma\sqrt{1-\rho^2} = 0.18 would give success 0.75, and the gap between that 0.75 and measured 0.61 is threshold error shared by all steps) and, above all, averaging five fixed seeds, succeeding over 99% of the time with five evaluations per commit. Note the model assumes intermediate commits do not change generator consumption. A commit adding a layer or changing initialization order breaks correlation (ρ\rho falls), leaving only averaging as defense.

Local lab: finding the regression

This lab creates a 50-commit practice repository in a temporary folder. One commit introduces a one-element preprocessing error (drops the last feature), and another leaves code uncompilable until the next commit. The evaluation script lives outside the repository, trains with five fixed seeds in one process, exits 125 if a commit cannot be evaluated and compares mean with an endpoint-calibrated threshold. Git must be installed; it does not touch global configuration because identity is passed in each command.

[ ]Finding the regression with git bisect runLocal GPU
import json, os, re, subprocess, sys, tempfile
from pathlib import Path

def git(*args, cwd, check=True):
    # identidad local de usar y tirar: no toca tu configuración global
    r = subprocess.run(["git", "-c", "user.name=Atlas lab", "-c", "[email protected]", *args],
                       cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace")
    if check and r.returncode != 0:
        raise RuntimeError(r.stderr)
    return r.stdout

MODELO = '''\
import numpy as np

N_CARACTERISTICAS = 8

def preparar(X):
    """Estandariza cada columna."""
    Z = (X - X.mean(axis=0)) / X.std(axis=0)
    return Z[:, :N_CARACTERISTICAS]

def entrenar(X, y, semilla, pasos=400, lr=0.5):
    """Regresión logística por descenso de gradiente."""
    rng = np.random.default_rng(semilla)
    w, b = rng.normal(0, 0.01, X.shape[1]), 0.0
    for _ in range(pasos):
        g = 1 / (1 + np.exp(-(X @ w + b))) - y
        w -= lr * X.T @ g / len(y)
        b -= lr * g.mean()
    return w, b

def precision(w, b, X, y):
    return float(((X @ w + b > 0) == y).mean())
'''

EVALUAR = '''import argparse, json
import numpy as np
from atlas_lab.modelo import preparar, entrenar, precision

p = argparse.ArgumentParser()
p.add_argument("--semillas", type=int, nargs="+", default=[0])
a = p.parse_args()

datos = np.random.default_rng(12345)                       # el conjunto de datos es fijo
X = datos.normal(size=(1200, 8))
w_real = np.array([1.2, -1.0, 0.8, 0.6, -0.5, 0.4, 0.3, 0.7])
y = (X @ w_real + datos.normal(0, 0.8, 1200) > 0).astype(float)
Z = preparar(X)

resultados = []
for s in a.semillas:                                       # la semilla decide partición e inicialización
    idx = np.random.default_rng(s).permutation(len(y))
    tr, va = idx[:900], idx[900:]
    w, b = entrenar(Z[tr], y[tr], s)
    resultados.append(precision(w, b, Z[va], y[va]))
print(json.dumps({"precision": float(np.mean(resultados)), "por_semilla": resultados}))
'''

def editar(ruta, viejo, nuevo):
    ruta.write_text(ruta.read_text(encoding="utf-8").replace(viejo, nuevo), encoding="utf-8")

def construir_repo(raiz, n=50, culpable=31, roto=24):
    """Repositorio de práctica: n commits; en `culpable` entra un error de un elemento en preparar()
    y en `roto` un error de sintaxis que se arregla en el siguiente."""
    (raiz / "src" / "atlas_lab").mkdir(parents=True)
    (raiz / "scripts").mkdir()
    (raiz / "src" / "atlas_lab" / "__init__.py").write_text("", encoding="utf-8")
    (raiz / "src" / "atlas_lab" / "modelo.py").write_text(MODELO, encoding="utf-8")
    (raiz / "scripts" / "evaluar.py").write_text(EVALUAR, encoding="utf-8")
    (raiz / "NOTAS.md").write_text("# Notas\n", encoding="utf-8")
    git("init", "-q", "-b", "main", cwd=raiz)
    git("add", ".", cwd=raiz)
    git("commit", "-q", "-m", "c0: modelo y evaluación", cwd=raiz)
    modelo = raiz / "src" / "atlas_lab" / "modelo.py"
    for k in range(1, n):
        if k == culpable:
            editar(modelo, "Z[:, :N_CARACTERISTICAS]", "Z[:, :N_CARACTERISTICAS - 1]")
            msg = f"c{k}: refactor de preparar()"
        elif k == roto:
            editar(modelo, "def entrenar(X, y, semilla,", "def entrenar(X, y, semilla")
            msg = f"c{k}: firma de entrenar() con pasos por defecto"
        elif k == roto + 1:
            editar(modelo, "def entrenar(X, y, semilla pasos", "def entrenar(X, y, semilla, pasos")
            msg = f"c{k}: arregla la coma que faltaba"
        else:
            with open(raiz / "NOTAS.md", "a", encoding="utf-8") as f:
                f.write(f"- nota {k}\n")
            msg = f"c{k}: notas del día {k}"
        git("commit", "-q", "-am", msg, cwd=raiz)
    return git("rev-list", "--reverse", "HEAD", cwd=raiz).split()

SCRIPT_BISECT = '''import json, os, subprocess, sys
SEMILLAS = ["0", "1", "2", "3", "4"]           # fijas: la misma lista en todos los commits
umbral = float(sys.argv[1])
entorno = {**os.environ, "PYTHONPATH": "src"}  # en tu proyecto: uv run python scripts/evaluar.py
r = subprocess.run([sys.executable, "scripts/evaluar.py", "--semillas", *SEMILLAS],
                   capture_output=True, text=True, env=entorno)
if r.returncode != 0:
    no_evaluable = any(e in r.stderr for e in ("SyntaxError", "ImportError", "ModuleNotFoundError"))
    print("no se puede evaluar" if no_evaluable else "la evaluación falla")
    sys.exit(125 if no_evaluable else 1)
media = json.loads(r.stdout)["precision"]
print(f"precisión media {media:.4f} frente al umbral {umbral:.4f}")
sys.exit(0 if media >= umbral else 1)
'''

with tempfile.TemporaryDirectory() as tmp:
    tmp = Path(tmp)
    repo = tmp / "practica"
    repo.mkdir()
    commits = construir_repo(repo)
    script = tmp / "bisect_eval.py"            # fuera del repositorio: bisect no lo cambia al saltar de commit
    script.write_text(SCRIPT_BISECT, encoding="utf-8")

    def medir(commit):
        git("checkout", "-q", commit, cwd=repo)
        r = subprocess.run([sys.executable, str(script), "nan"], cwd=repo, capture_output=True, text=True)
        git("checkout", "-q", "main", cwd=repo)
        return float(re.search(r"media ([\d.]+)", r.stdout).group(1))

    bueno, malo = medir(commits[0]), medir(commits[-1])
    umbral = (bueno + malo) / 2
    print(f"{len(commits)} commits. Precisión media (5 semillas): c0 = {bueno:.4f}, HEAD = {malo:.4f}; umbral {umbral:.4f}")

    git("bisect", "start", "HEAD", commits[0], cwd=repo)
    salida = git("bisect", "run", sys.executable, str(script), f"{umbral:.6f}", cwd=repo)
    hallado = re.search(r"([0-9a-f]{40}) is the first bad commit", salida).group(1)
    indice = {h: f"c{i}" for i, h in enumerate(commits)}
    print(f"git bisect run señala {indice[hallado]}: «{git('show', '-s', '--format=%s', hallado, cwd=repo).strip()}»")
    for linea in git("show", "--format=", "-U0", hallado, cwd=repo).splitlines():
        if linea[:1] in "+-" and linea[:3] not in ("+++", "---"):
            print("    " + linea)
    print("Registro (git bisect log):")
    for linea in git("bisect", "log", cwd=repo).splitlines():
        if linea.startswith(("git bisect good", "git bisect bad", "git bisect skip")):
            orden, h = linea.rsplit(" ", 1)
            print(f"    {orden:16s} {indice[h]}")
    git("bisect", "reset", cwd=repo)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The log shows the script’s three possible answers: bisect’s first proposed commit is exactly the one that does not compile, the script exits 125 and bisect chooses another candidate; a few more decisions reach c31, whose diff is the culprit line. The regression, about four points, is large relative to five-seed mean noise, so one pass suffices. To practice, change the script to use one random seed per evaluation (np.random.default_rng() without argument in evaluar.py) and run the lab repeatedly: sooner or later it will name an innocent commit.

The lab notebook

The commit graph says what changed and runs say what happened. Missing is what no tool records automatically: why it was tried, what was expected and what was decided. Without this, a project’s history is a list of experiments without an argument, and three months later you will not know whether hip/mixer was abandoned because it failed or time ran out.

In this course it lives in docs/cuaderno.md in the repository: versioned with code, readable in any editor and its commit and run links remain intact. An entry looks like:

## 2026-02-11 · hip/label-smoothing

**Pregunta.** ¿Mejora label smoothing 0.1 la calibración sin coste en precisión?
**Predicción (antes de ejecutar).** ECE de 2.1 a menos de 1.5; precisión igual (±0.2).
**Qué se hizo.** commit 1bff528 (hip/label-smoothing), configs/ls01.yaml, semillas 0-4,
  runs/2026-02-11_1120/. Línea base: runs/2026-02-07_1412/ (mismas semillas).
**Resultado.** ECE 1.4 ± 0.1 frente a 2.1 ± 0.1. Precisión 88.0 ± 0.3 frente a 88.1 ± 0.2.
**Interpretación.** La predicción se cumple. La calibración no es objetivo del artículo.
**Decisión.** Descartar por ahora. Etiqueta archivo/label-smoothing; rama borrada.
**Siguiente.** Si el revisor pregunta por calibración, la ejecución está lista.

Three details distinguish a useful notebook from a diary. Prediction written before results protects against reinterpreting hypothesis after seeing data; a lightweight form of preregistration. Two-way links: entry cites commit and run, and merge-commit message or tag annotation cites entry. And uncertainty on every number: “88.0” does not permit a decision; “88.0 ± 0.3 with 5 seeds versus 88.1 ± 0.2 with the same seeds” does. The notebook does not replace experiment tracking, which stores curves and metrics for thousands of runs; it stores the reasoning connecting a few to a decision.

Local lab: the course project template

This lab generates the complete template in a temporary folder, creates the repository, shows what enters the first commit and which rule ignores each item that should not enter, and checks that a clean clone, containing only versioned material, passes quick tests. No network needed: tests run with lab pytest and package in PYTHONPATH. With uv, complete verification on your machine is git clone, uv sync and uv run pytest -m "not slow".

[ ]Course project templateLocal GPU
import os, subprocess, sys, tempfile, textwrap
from pathlib import Path

PLANTILLA = {
    "pyproject.toml": '''
        [project]
        name = "atlas-lab"
        version = "0.1.0"
        requires-python = ">=3.12"
        dependencies = ["numpy>=2.0", "pyyaml>=6"]

        [dependency-groups]
        dev = ["pytest>=8", "ruff", "mypy", "pre-commit", "nbstripout"]

        [build-system]
        requires = ["uv_build>=0.10.11,<0.11.0"]
        build-backend = "uv_build"

        [tool.ruff]
        line-length = 110

        [tool.ruff.lint]
        select = ["E", "F", "I", "B", "UP", "NPY"]

        [tool.mypy]
        files = ["src"]
        warn_unused_ignores = true

        [tool.pytest.ini_options]
        testpaths = ["tests"]
        markers = ["slow: tests largos, fuera del gancho de pre-commit"]
    ''',
    ".gitignore": '''
        .venv/
        __pycache__/
        .ipynb_checkpoints/
        .env
        /data/raw/
        /data/processed/
        /runs/
        wandb/
        *.pt
    ''',
    "src/atlas_lab/__init__.py": "",
    "src/atlas_lab/config.py": '''
        import os
        from pathlib import Path

        def ruta_datos(cfg: dict | None = None) -> Path:
            """Carpeta de datos: la variable ATLAS_DATA_DIR manda; si no, la configuración; si no, data/."""
            por_defecto = (cfg or {}).get("paths", {}).get("data_dir", "data")
            return Path(os.environ.get("ATLAS_DATA_DIR", por_defecto)).expanduser()
    ''',
    "src/atlas_lab/metricas.py": '''
        import numpy as np

        def precision(pred: np.ndarray, y: np.ndarray) -> float:
            return float(np.mean(pred == y))
    ''',
    "tests/test_metricas.py": '''
        import numpy as np
        import pytest
        from atlas_lab.config import ruta_datos
        from atlas_lab.metricas import precision

        def test_precision():
            assert precision(np.array([1, 0, 1]), np.array([1, 1, 1])) == pytest.approx(2 / 3)

        def test_ruta_datos(monkeypatch, tmp_path):
            monkeypatch.setenv("ATLAS_DATA_DIR", str(tmp_path))
            assert ruta_datos({"paths": {"data_dir": "otra"}}) == tmp_path

        @pytest.mark.slow
        def test_entrenamiento_completo():
            pass  # aquí iría un entrenamiento corto de verdad
    ''',
    "configs/base.yaml": '''
        paths:
          data_dir: data
          runs_dir: runs
        modelo: {capas: 2, ancho: 128}
        optim: {lr: 3.0e-4, pasos: 2000}
        semillas: [0, 1, 2, 3, 4]
    ''',
    "scripts/entrenar.py": '''
        """Punto de entrada fino: lee la configuración, llama al paquete y escribe en runs/."""
        from atlas_lab.config import ruta_datos
        print("datos en", ruta_datos())
    ''',
    "notebooks/README.md": "Exploración. Los notebooks importan de atlas_lab y se versionan sin salidas.\n",
    "data/README.md": "Cómo obtener los datos crudos y verificarlos: sha256sum -c MANIFEST.sha256\n",
    "data/MANIFEST.sha256": "",
    "docs/cuaderno.md": "# Cuaderno de laboratorio\n",
    "reports/figures/.gitkeep": "",
    "README.md": "# atlas-lab\n\nuv sync; uv run pre-commit install; uv run pytest\n",
    ".env.example": "WANDB_API_KEY=\nATLAS_DATA_DIR=\n",
    # lo que NO debe entrar en git
    ".env": "WANDB_API_KEY=clave-de-ejemplo\n",
    "data/raw/precios.parquet": "no son datos de verdad",
    "runs/2026-02-24_1610/ckpt.pt": "tampoco",
    "notebooks/.ipynb_checkpoints/x.ipynb": "{}",
}

def git(*args, cwd):
    r = subprocess.run(["git", "-c", "user.name=Atlas lab", "-c", "[email protected]", *args],
                       cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace")
    return r.stdout

with tempfile.TemporaryDirectory() as tmp:
    raiz = Path(tmp) / "atlas-lab"
    for ruta, texto in PLANTILLA.items():
        p = raiz / ruta
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(textwrap.dedent(texto).lstrip("\n"), encoding="utf-8")

    git("init", "-q", "-b", "main", cwd=raiz)
    git("add", "-A", cwd=raiz)
    versionado = git("ls-files", cwd=raiz).split()
    print(f"Entran en el primer commit ({len(versionado)} ficheros):")
    for f in versionado:
        print("   ", f)
    print("\nIgnorados, con la regla responsable:")
    for f in [".env", "data/raw/precios.parquet", "runs/2026-02-24_1610/ckpt.pt", "notebooks/.ipynb_checkpoints/x.ipynb"]:
        print("   ", git("check-ignore", "-v", f, cwd=raiz).strip().replace("\t", "  ->  "))
    git("commit", "-q", "-m", "plantilla del proyecto", cwd=raiz)

    # un clon limpio solo tiene lo versionado: ¿pasan los tests?
    clon = Path(tmp) / "clon"
    subprocess.run(["git", "clone", "-q", str(raiz), str(clon)], check=True)
    r = subprocess.run([sys.executable, "-m", "pytest", "-m", "not slow", "-q", "-p", "no:cacheprovider"],
                       cwd=clon, capture_output=True, text=True, env={**os.environ, "PYTHONPATH": "src"})
    print("\npytest en el clon limpio:", r.stdout.strip().splitlines()[-1])
    print("¿llegaron datos al clon?", (clon / "data" / "raw").exists())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To bring the template to your course repository, five steps: move reusable notebook code to src/atlas_lab/ with one test per function; copy .gitignore and check with git status --ignored that nothing slips through; add tools with uv add --dev pre-commit ruff mypy nbstripout; copy .pre-commit-config.yaml and run uv run pre-commit install and uv run pre-commit run --all-files (the first time reformats many files: make that a separate commit, so it does not mix with content changes); and write exact commands reproducing each result in README.

Common mistakes

Exercises

NumericWorst-case evaluations
Between the last known good commit and HEAD, which is bad, there are 1000 candidate first bad commits (including HEAD). With exact evaluation, how many evaluations does git bisect need in the worst case to locate it?
NumericSix steps with 10% error
There are 64 candidate first bad commits and each script evaluation independently errs with probability 0.1 (on good and bad commits alike). With what probability does git bisect identify the culprit?
NumericHow many repetitions?
A regression has size Δ\Delta and an evaluation has Gaussian noise of standard deviation σ=Δ\sigma = \Delta. The script averages rr independent evaluations per commit and uses the midpoint threshold. With 64 candidates (6 steps on every path), what is the smallest rr giving success probability at least 0.95?
QuizWhat goes in git?
In the course project, which paths should be under version control?

More than one answer may be correct.

QuizBranch, tag or worktree
Three situations. (1) You want to test whether a cosine scheduler improves on linear, requiring a training-loop change. (2) You have generated table 2 to send your supervisor and want to regenerate it exactly in six months. (3) A ten-hour run using yesterday's version is underway and you want to keep coding on main. Which mechanism fits each?
QuizThe script that breaks
Your bisect script is metrica = evaluar(); sys.exit(0 if metrica >= umbral else 1). Commit c24 lacks a module added later, so evaluar() raises ModuleNotFoundError uncaught. What does git bisect run do with c24?
QuizA failure that comes and goes
In history c0, ..., c63 a failure appeared at c20, was fixed at c40 and reappeared for another reason at c50. Run git bisect with c0 good and c63 bad, exact evaluation and midpoint rule ⌊(b+m)/2⌋\lfloor (b + m)/2 \rfloor. Which commit does it identify?
CodeThe git bisect run script
Implement codigo_salida(evaluar, umbral, mayor_es_mejor=True), the heart of a git bisect run script. evaluar() evaluates the current commit and returns the metric. Return 125 if evaluar() raises ImportError (including ModuleNotFoundError), SyntaxError or FileNotFoundError, because the commit is unevaluable; return 1 for any other exception (code runs but fails) or if metric is NaN; otherwise return 0 if metric is at least as good as threshold (greater or equal if mayor_es_mejor, less or equal otherwise) and 1 if worse. Tests include a simulated 64-commit bisection with one that does not compile.
def codigo_salida(evaluar, umbral, mayor_es_mejor=True):
  """Código de salida para git bisect run: 0 bueno, 1 malo, 125 no evaluable."""
  metrica = evaluar()
  if mayor_es_mejor:
      return 1 if metrica < umbral else 0
  return 1 if metrica > umbral else 0
Shift+Enter to run
CodeBisection with majority voting
Implement bisect_ruidoso(n, prueba, reps=1). History is c0, ..., c(n-1); c0 is good and c(n-1) bad, and do not need evaluation. prueba(i) returns True if commit i appears bad and may err. Test each visited commit exactly reps times and decide by majority; return the first bad commit index. If reps is not a positive odd integer, raise ValueError. Tests check noiseless accuracy, test count per commit, and that with test error 0.15 and reps=9 you succeed on at least 92% of 400 simulated histories (theory gives 96.7%).
def bisect_ruidoso(n, prueba, reps=1):
  """Primer commit malo en c0..c(n-1) (c0 bueno, c(n-1) malo) con una prueba ruidosa."""
  bueno, malo = 0, n - 1
  while malo - bueno > 1:
      medio = (bueno + malo) // 2
      if prueba(medio):          # True significa «parece malo»
          malo = medio
      else:
          bueno = medio
  return malo
Shift+Enter to run
ProofNobody does better than bisect
Prove: With nn candidate first bad commits and an exact test answering ‘good’ or ‘bad’, any deterministic strategy always locating the culprit needs at least ⌈log⁡2n⌉\lceil \log_2 n \rceil tests in the worst case.
0
Fix any strategy, which may choose each commit to test based on previous answers.

Step 1 of 4. How do you represent the strategy?

Summary

Key idea
A research project is an instrument: structure separates reliable from exploratory and source from derived, automation enforces that separation on each commit, git makes history a queryable experiment record, and bisect traverses it in ⌈log⁡2n⌉\lceil \log_2 n \rceil steps provided evaluation does not lie.
  • The package in src/ contains all code producing results, with tests; notebooks import it; scripts are thin; configurations are declarative and versioned.
  • Data, checkpoints, runs, notebook outputs and secrets never enter git because what enters remains in history. Replace them with configurable paths and a SHA-256 checksum manifest.
  • pre-commit runs ruff, mypy, nbstripout, quick tests and large-file blocking at every commit and should take seconds so nobody skips it.
  • Small intentional commits, branches by hypothesis (merged with --no-ff or archived with a tag), annotated tags per result and worktrees for running two versions at once, each with its own environment. No important run from a dirty tree.
  • Bisection finds a good-to-bad transition in ⌈log⁡2n⌉\lceil \log_2 n \rceil evaluations, the optimal bound. Without monotonicity it may not be the one sought.
  • With noisy evaluations, an error on the path removes the culprit forever: success is ∏j(1−p(kj))\prod_j (1 - p(k_j)). Fixed seeds, threshold calibrated on them and averaging several evaluations make it reliable; the script exits 125 when the commit is unevaluable.
  • The lab notebook records hypothesis, prior prediction, run, result with uncertainty and decision, linked to commits and runs.