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 runto 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.
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.tomlanduv.lock, documentation, notebooks without outputs,data/README.md(how to obtain data) anddata/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 variableATLAS_DATA_DIRor, if absent, theconfigs/base.yamlvalue. - Checksums.
data/MANIFEST.sha256contains 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.
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). FamilyNPYincludesNPY002, prohibitingnp.random.seedand 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
srcbecause 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
slowmarker. It is lesson testing’s tests with fixtures and parametrization, excluding those actually training, which move topre-pushand 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.
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 -pstages 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 --dirtyreturns something likeres/tabla2-v1-3-ged923b6-dirty(three commits after the tag, at commited923b6, with local changes). This is central to run provenance: if-dirtyappears, 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.
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 candidates for first bad commit, ( is good by assumption). The algorithm maintains two indices, and , with an invariant, and each evaluation halves candidate count.
Proof
(2) Invariant “ is false and is true” holds initially by assumption and is preserved each step, because is assigned to only when is true and to when false. Also while , so interval strictly shrinks. At termination and the invariant states exactly that is a transition.
(1) Let be candidate count. With , the new is or ; both at most . By induction, after evaluations , using for real . The algorithm stops once , guaranteed if , that is, .
(3) If is monotone, is false for and true for , and the only transition is at .
∎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 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 distinct leaves, and a binary tree of depth has at most 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 , was fixed in and reappeared in , bisect from may point to , 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.
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 code | Meaning for bisect |
|---|---|
| 0 | commit is good |
| 1 through 127, except 125 | commit is bad |
| 125 | commit cannot be evaluated: skipped, like skip |
| anything else | abort 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.yamlyet 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 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.
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 ‘s metric is
where is regression size and the standard deviation of an evaluation (variation across seeds, splits, nondeterministic runs). The script decides “good” if . With threshold at midpoint, , one evaluation is wrong with probability
with 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 and bisection follows precisely the error-free path . If step is the first error, there are two cases: if (bad) is classified good, new is and culprit is outside the interval; if (good) is classified bad, new is and culprit is also outside. Later steps only narrow the interval, so the answer inside it is not . Success therefore equals all steps on the error-free path being correct, and by independence its probability is the product. If , every path has exactly steps, all with success probability .
∎The number is worse than it looks. With points and (regression of only two standard deviations), , and in the figure’s history (64 commits, 63 candidates: all but one path have six steps) bisection succeeds with probability (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 . There are four remedies, each worth understanding.
Average independent evaluations. The mean of measurements has standard deviation , so per-step error falls to . To guarantee success at least , the union bound says suffices:
With the previous numbers, and , and : six evaluations per commit give success at six times the cost. Total cost is evaluations, growing with the logarithm of commit count and square of : 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 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 when : it decreases exponentially with . The bound is conservative (with , reducing below 0.01 requests 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 (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 , 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 , with common to all commits evaluated with seed and 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 , and the threshold’s own noise, inherited from both endpoints (standard deviation ) 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 total evaluations for error , instead of 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.
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.
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 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 ( 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.
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)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".
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())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
More than one answer may be correct.
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?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 0bisect_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 maloStep 1 of 4. How do you represent the strategy?
Summary
- 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-ffor 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 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 . 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.