msc-kd-data / lib /msc_lib.py
Shanmuk4622's picture
msc_lib.py v1.1.0
f87e0cd verified
Raw History Blame Contribute Delete
131 kB
"""
msc_lib.py v1.0.0 -- MSC Phase 0 shared library.
Uploaded once by NB00_bootstrap, downloaded identically by every run notebook,
and pinned by sha256 in config.json so that "did all four runs execute the same
code?" is answerable by a hash rather than by memory.
Design principle (inherited from E2AM): HuggingFace is the *only* permanent
store. /kaggle/working is scratch for artifacts, /kaggle/temp is scratch for
datasets and regenerable intermediates. A session can die at any instant.
Parallel-safety (inherited from the AI-detection build): every run writes ONLY
to runs/{run_id}/ and per_sample/{run_id}/. Four accounts never touch the same
path, so concurrent commits collide only at the repo-revision level, which is
handled by push stagger + 412/409 retry.
What this library adds over E2AM, because the science needs it:
- Checkpoints carry ALL FOUR RNG states. Without them a resumed run is not
the same run, the seeds are meaningless, and the noise ceiling -- which is
the denominator of every transfer number in the project -- is invalid.
- config_hash asserted on resume, computed over the `science` block only.
- SIGTERM / atexit / KeyboardInterrupt all trigger an immediate full push.
- A wall-clock push timer (20 min) rather than an epoch-milestone timer,
staggered per account.
- An eleven-stage machine with STATE.json, so any cell is safe to re-run and
a cold session resumes at the first incomplete stage.
- Row-alignment assertions and a dataset fingerprint, because a misaligned
per-sample table destroys real correlations or manufactures fake ones and
nothing downstream looks broken.
Sections:
1. utils -- atomic io, hashing, RNG state, seeding
2. hf_store -- background uploader, batched commits, backoff
3. stages -- STATE.json stage machine
4. config -- science/runtime split, config_hash
5. data -- CIFAR-100, canonical ordering, fingerprint
6. models -- resnet32x4 / wrn-40-2, CIFAR recipe faithful
7. exits -- exit heads, pooled-feature cache, 3 head seeds
8. energy -- NVML sampler
9. checkpoint -- full-state save/load
10. train -- training loop, gate, signal handlers
11. sweeps -- depth / resolution oracle sweeps
12. battery -- 7 difficulty scores
13. emit -- per-sample Parquet with assertions
"""
from __future__ import annotations
__version__ = "1.1.0"
import atexit
import csv
import hashlib
import json
import os
import pickle
import random
import shutil
import signal
import sys
import threading
import time
import traceback
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple
import numpy as np
# torch is optional so the analysis driver can import this module on a CPU-only
# session with no torch installed. When it is absent we install a stub whose
# only job is to let the module *import*: nn.Module must be a usable base class
# and torch.no_grad must be a pass-through decorator, because both are
# evaluated at class-definition time. Anything that actually touches torch then
# fails loudly at call time rather than silently doing the wrong thing.
try:
import torch
import torch.nn as nn
import torch.nn.functional as F
_HAS_TORCH = True
except Exception: # pragma: no cover
_HAS_TORCH = False
class _Missing:
"""Every attribute access returns something that raises when used."""
def __init__(self, name="torch"):
self._name = name
def __getattr__(self, item):
if item == "Module":
return object
if item in ("no_grad", "inference_mode"):
def _passthrough(fn=None):
if fn is None:
return _passthrough
return fn
return _passthrough
def _raise(*a, **k):
raise RuntimeError(
f"{self._name}.{item} used but PyTorch is not installed. "
f"This code path requires a GPU session.")
return _raise
torch = _Missing("torch") # type: ignore
nn = _Missing("torch.nn") # type: ignore
F = _Missing("torch.nn.functional") # type: ignore
# =============================================================================
# 1. utils
# =============================================================================
def now_iso() -> str:
import datetime
return datetime.datetime.now(datetime.timezone.utc).isoformat()
def ensure_dir(p) -> Path:
p = Path(p)
p.mkdir(parents=True, exist_ok=True)
return p
def atomic_write_bytes(path, data: bytes) -> None:
"""Write via a temp file + os.replace. os.replace is atomic on POSIX.
Never write directly to a file another process may read, and never write
directly to ckpt_last.pt -- a session killed mid-write leaves a truncated
file and the run is lost.
"""
path = Path(path)
ensure_dir(path.parent)
tmp = path.with_suffix(path.suffix + ".tmp")
with open(tmp, "wb") as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
def atomic_write_text(path, text: str) -> None:
atomic_write_bytes(path, text.encode("utf-8"))
def atomic_write_json(path, obj) -> None:
atomic_write_text(path, json.dumps(obj, indent=2, sort_keys=True, default=str))
def atomic_save_torch(path, obj) -> None:
path = Path(path)
ensure_dir(path.parent)
tmp = path.with_suffix(path.suffix + ".tmp")
torch.save(obj, tmp)
os.replace(tmp, path)
def read_json(path, default=None):
try:
return json.loads(Path(path).read_text(encoding="utf-8"))
except Exception:
return default
def sha256_file(path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def sha256_bytes(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
def canonical_json(obj) -> str:
"""Stable serialisation for hashing: sorted keys, normalised numerics.
Floats are round-tripped through repr so that 0.05 hashes identically on
every platform and every Python build.
"""
def norm(o):
if isinstance(o, dict):
return {str(k): norm(o[k]) for k in sorted(o, key=str)}
if isinstance(o, (list, tuple)):
return [norm(x) for x in o]
if isinstance(o, float):
return repr(float(o))
if isinstance(o, (np.integer,)):
return int(o)
if isinstance(o, (np.floating,)):
return repr(float(o))
return o
return json.dumps(norm(obj), sort_keys=True, separators=(",", ":"))
def derive_seed(*parts) -> int:
"""Deterministic 31-bit seed from any tuple of identifiers.
Used so that every source of randomness gets its own seed derived from the
run seed, rather than sharing one global stream. Sharing a stream between
seed 1 and seed 2 would inflate the noise ceiling and bias every transfer
number in the optimistic direction.
"""
s = ":".join(str(p) for p in parts)
return int(hashlib.sha256(s.encode()).hexdigest()[:15], 16) % (2 ** 31 - 1)
def set_all_seeds(seed: int, deterministic: bool = True) -> Dict[str, Any]:
"""Seed python / numpy / torch / cuda and request deterministic kernels.
Returns a dict recording what was actually achieved -- determinism is not
always available (some ops have no deterministic CUDA implementation), and
where it is disabled that fact must be recorded in the config rather than
silently assumed.
"""
random.seed(seed)
np.random.seed(seed % (2 ** 32 - 1))
info = {"seed": int(seed), "deterministic": False, "reason": None}
if not _HAS_TORCH:
return info
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
if deterministic:
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
try:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True)
info["deterministic"] = True
except Exception as e:
try:
torch.use_deterministic_algorithms(True, warn_only=True)
except Exception:
pass
info["reason"] = f"{type(e).__name__}: {e}"
print(f"[SEED] full determinism unavailable -> warn_only. {info['reason']}")
else:
info["reason"] = "disabled by config"
return info
def rng_state() -> Dict[str, Any]:
"""Capture every RNG stream that affects training.
Omitting any of these means a resumed run is not the same run as an
uninterrupted one, which makes the seeds -- and therefore the entire
noise ceiling -- meaningless.
"""
st = {
"python": random.getstate(),
"numpy": np.random.get_state(),
"torch": torch.get_rng_state(),
"cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else [],
}
return st
def rng_restore(st: Dict[str, Any]) -> None:
random.setstate(st["python"])
np.random.set_state(st["numpy"])
torch.set_rng_state(st["torch"].cpu() if hasattr(st["torch"], "cpu") else st["torch"])
if torch.cuda.is_available() and st.get("cuda"):
try:
torch.cuda.set_rng_state_all([s.cpu() if hasattr(s, "cpu") else s
for s in st["cuda"]])
except Exception as e:
print(f"[RNG] cuda state restore failed ({e}) -- continuity is void")
def worker_init_fn_factory(base_seed: int) -> Callable[[int], None]:
"""Per-worker seeding. Without this, dataloader workers inherit a seed
derived from torch's global generator in a way that is not stable across
resume, and augmentation order silently diverges."""
def _init(worker_id: int) -> None:
s = (base_seed + worker_id) % (2 ** 31 - 1)
random.seed(s)
np.random.seed(s % (2 ** 32 - 1))
torch.manual_seed(s)
return _init
def disk_free_mb(path="/kaggle/working") -> int:
try:
return shutil.disk_usage(str(path)).free // (1024 * 1024)
except Exception:
return 1 << 30
def hardware_report() -> Dict[str, Any]:
rep: Dict[str, Any] = {"time_utc": now_iso(), "python": sys.version.split()[0]}
try:
rep["torch"] = torch.__version__
rep["cuda_available"] = bool(torch.cuda.is_available())
if torch.cuda.is_available():
rep["gpu_name"] = torch.cuda.get_device_name(0)
rep["gpu_count"] = torch.cuda.device_count()
rep["cuda_version"] = torch.version.cuda
rep["cudnn_version"] = torch.backends.cudnn.version()
rep["vram_gb"] = round(
torch.cuda.get_device_properties(0).total_memory / 1e9, 2)
except Exception as e:
rep["torch_error"] = str(e)
try:
import torchvision
rep["torchvision"] = torchvision.__version__
except Exception:
pass
try:
import subprocess
rep["nvidia_smi"] = subprocess.run(
["nvidia-smi", "--query-gpu=name,driver_version",
"--format=csv,noheader"],
capture_output=True, text=True, timeout=10).stdout.strip()
except Exception:
pass
try:
import subprocess
rep["pip_freeze"] = subprocess.run(
[sys.executable, "-m", "pip", "freeze"],
capture_output=True, text=True, timeout=120).stdout.splitlines()
except Exception:
pass
return rep
class Tee:
"""Mirror stdout to a file so logs/{run_id}/stdout.log is a real artifact.
The thing everyone wishes they had kept.
"""
def __init__(self, path):
self.path = Path(path)
ensure_dir(self.path.parent)
self._f = open(self.path, "a", encoding="utf-8", buffering=1)
self._stdout = sys.stdout
def write(self, s):
self._stdout.write(s)
try:
self._f.write(s)
except Exception:
pass
def flush(self):
self._stdout.flush()
try:
self._f.flush()
except Exception:
pass
def install(self):
sys.stdout = self
return self
def close(self):
sys.stdout = self._stdout
try:
self._f.close()
except Exception:
pass
# =============================================================================
# 2. hf_store -- background uploader with batched commits
# =============================================================================
@dataclass
class _Pending:
local_path: str
repo_path: str
fingerprint: str
enqueued_at: float
class HFStore:
"""Batched, rate-limited, crash-tolerant uploader for one HF repo.
One worker thread. Files are buffered and flushed as a SINGLE commit when
the interval elapses, the buffer fills, or flush() is called. Six files in
six commits is six times the rate-limit consumption for no benefit.
Concurrency: Phase 0 runs four accounts against the same repos at once.
Two failure modes are handled differently and must not be conflated:
429 (rate limit) -> exponential backoff 60/120/240/600s. Slow down.
412 / 409 (revision conflict from a concurrent commit) -> immediate retry
with 1-5s jitter. A 60s sleep here would serialise
all four accounts for no reason.
A failed push NEVER propagates into training. It is logged and retried on
the next cycle.
"""
MAX_ATTEMPTS_429 = 6
MAX_ATTEMPTS_CONFLICT = 5
BACKOFF_429 = (60, 120, 240, 600, 600, 600)
BATCH_MAX_FILES = 200
BATCH_MAX_BYTES = 2 * 1024 * 1024 * 1024
def __init__(self, repo_id: str, token: str, repo_type: str = "model",
interval_sec: float = 1200.0, offset_sec: float = 0.0,
commits_per_hour: int = 30, private: bool = True):
self.repo_id = repo_id
self.token = token
self.repo_type = repo_type
self.interval_sec = float(interval_sec)
self.offset_sec = float(offset_sec)
self.commits_per_hour = int(commits_per_hour)
self.private = private
self._buffer: Dict[str, _Pending] = {}
self._buf_lock = threading.Lock()
self._fingerprints: Set[str] = set()
self._fp_lock = threading.Lock()
self._commit_times: List[float] = []
self._commit_lock = threading.Lock()
self._stop = threading.Event()
self._wakeup = threading.Event()
self._thread: Optional[threading.Thread] = None
self._in_commit = False
self._api = None
self._stats = {"queued": 0, "uploaded": 0, "dedup_skipped": 0,
"commits": 0, "retries_429": 0, "retries_conflict": 0,
"rate_waits": 0, "failed": 0}
self._stats_lock = threading.Lock()
# ------------------------------------------------------------------ life
def start(self) -> bool:
try:
from huggingface_hub import HfApi, create_repo
create_repo(repo_id=self.repo_id, token=self.token, exist_ok=True,
repo_type=self.repo_type, private=self.private)
self._api = HfApi(token=self.token)
except Exception as e:
print(f"[HF] init failed for {self.repo_id}: {e}")
return False
self._stop.clear()
self._thread = threading.Thread(target=self._loop, daemon=True,
name=f"hf-{self.repo_type}")
self._thread.start()
print(f"[HF] {self.repo_id} ready "
f"(interval={self.interval_sec/60:.0f}min, "
f"offset={self.offset_sec/60:.0f}min, "
f"<={self.commits_per_hour} commits/hr)")
return True
def healthcheck(self, session_id: str) -> bool:
"""Live write test. Fail fast in Cell 1 rather than after three hours.
A run that discovers at the end that it cannot push is strictly worse
than one that never starts.
"""
try:
from huggingface_hub import CommitOperationAdd, CommitOperationDelete
p = f"_healthcheck/{session_id}.txt"
self._api.create_commit(
repo_id=self.repo_id, repo_type=self.repo_type,
operations=[CommitOperationAdd(
path_in_repo=p,
path_or_fileobj=now_iso().encode())],
commit_message="healthcheck")
self._api.create_commit(
repo_id=self.repo_id, repo_type=self.repo_type,
operations=[CommitOperationDelete(path_in_repo=p)],
commit_message="healthcheck cleanup")
print(f"[HF] write healthcheck OK -> {self.repo_id}")
return True
except Exception as e:
print(f"[HF] WRITE HEALTHCHECK FAILED for {self.repo_id}: {e}")
return False
def stop(self, drain: bool = True, timeout: float = 300.0) -> None:
if self._thread is None:
return
if drain:
self.flush(timeout=timeout)
self._stop.set()
self._wakeup.set()
self._thread.join(timeout=15)
self._thread = None
# ------------------------------------------------------------------- api
def enqueue(self, local_path, repo_path: str) -> bool:
"""Buffer a file for the next batched commit. False if deduplicated."""
local_path = Path(local_path)
if not local_path.exists():
return False
fp = self._fingerprint(local_path, repo_path)
with self._fp_lock:
if fp in self._fingerprints:
with self._stats_lock:
self._stats["dedup_skipped"] += 1
return False
repo_path = repo_path.replace("\\", "/")
with self._buf_lock:
self._buffer[repo_path] = _Pending(str(local_path), repo_path,
fp, time.time())
n = len(self._buffer)
nbytes = sum(self._safe_size(p.local_path)
for p in self._buffer.values())
with self._stats_lock:
self._stats["queued"] += 1
if n >= self.BATCH_MAX_FILES or nbytes >= self.BATCH_MAX_BYTES:
self._wakeup.set()
return True
def enqueue_dir(self, local_dir, repo_prefix: str,
skip: Sequence[str] = ()) -> int:
local_dir = Path(local_dir)
if not local_dir.exists():
return 0
n = 0
for f in sorted(local_dir.rglob("*")):
if not f.is_file():
continue
rel = f.relative_to(local_dir).as_posix()
if any(s in rel for s in skip) or rel.endswith(".tmp"):
continue
n += int(self.enqueue(f, f"{repo_prefix.rstrip('/')}/{rel}"))
return n
def flush(self, timeout: float = 300.0) -> bool:
self._wakeup.set()
deadline = time.time() + timeout
while time.time() < deadline:
with self._buf_lock:
empty = not self._buffer
if empty and not self._in_commit:
return True
time.sleep(0.5)
print(f"[HF] flush timed out after {timeout}s for {self.repo_id}")
return False
def stats(self) -> Dict[str, int]:
with self._stats_lock:
with self._buf_lock:
pending = len(self._buffer)
return dict(self._stats, pending=pending,
commits_last_hour=self._commits_in_last_hour())
def list_files(self) -> Set[str]:
try:
return set(self._api.list_repo_files(repo_id=self.repo_id,
repo_type=self.repo_type))
except Exception as e:
print(f"[HF] list_repo_files: {e}")
return set()
def download(self, repo_path: str, local_path=None) -> Optional[Path]:
try:
from huggingface_hub import hf_hub_download
p = hf_hub_download(repo_id=self.repo_id, filename=repo_path,
repo_type=self.repo_type, token=self.token)
if local_path is not None:
ensure_dir(Path(local_path).parent)
shutil.copy2(p, local_path)
return Path(local_path)
return Path(p)
except Exception as e:
msg = str(e).lower()
if "404" not in msg and "not found" not in msg and "entrynotfound" not in msg:
print(f"[HF] download {repo_path}: {e}")
return None
def snapshot(self, local_dir, allow_patterns: Optional[List[str]] = None) -> bool:
"""Pull only what this run needs. /kaggle/working is 20 GB and shared
with the artifacts, so never snapshot the whole repo."""
try:
from huggingface_hub import snapshot_download
ensure_dir(local_dir)
snapshot_download(repo_id=self.repo_id, repo_type=self.repo_type,
local_dir=str(local_dir), token=self.token,
allow_patterns=allow_patterns)
return True
except Exception as e:
msg = str(e).lower()
if "404" in msg or "not found" in msg:
print(f"[HF] no prior snapshot in {self.repo_id} (fresh repo)")
else:
print(f"[HF] snapshot warning: {e}")
return False
# ------------------------------------------------------------- internals
@staticmethod
def _fingerprint(local_path: Path, repo_path: str) -> str:
try:
st = local_path.stat()
return f"{repo_path}|{st.st_size}|{int(st.st_mtime)}"
except Exception:
return f"{repo_path}|?|{time.time()}"
@staticmethod
def _safe_size(p: str) -> int:
try:
return Path(p).stat().st_size
except Exception:
return 0
def _commits_in_last_hour(self) -> int:
now = time.time()
with self._commit_lock:
self._commit_times = [t for t in self._commit_times if now - t < 3600]
return len(self._commit_times)
def _wait_for_rate_limit(self) -> None:
while not self._stop.is_set():
now = time.time()
with self._commit_lock:
self._commit_times = [t for t in self._commit_times
if now - t < 3600]
if len(self._commit_times) < self.commits_per_hour:
return
oldest = self._commit_times[0]
wait = max(1.0, 3600 - (now - oldest) + 1.0)
with self._stats_lock:
self._stats["rate_waits"] += 1
print(f"[HF] rate guard: {len(self._commit_times)} commits/hr, "
f"sleeping {wait:.0f}s")
if self._stop.wait(wait):
return
def _loop(self) -> None:
# Honour the per-account stagger exactly once, at thread start, so the
# four accounts' commit phases stay 5 minutes apart for the whole run.
if self.offset_sec > 0:
if self._stop.wait(self.offset_sec):
return
while not self._stop.is_set():
self._wakeup.wait(timeout=self.interval_sec)
self._wakeup.clear()
if self._stop.is_set():
break
with self._buf_lock:
if not self._buffer:
continue
batch = list(self._buffer.values())
self._buffer.clear()
self._wait_for_rate_limit()
self._in_commit = True
try:
if not self._commit_batch(batch):
with self._buf_lock:
for pf in batch:
self._buffer.setdefault(pf.repo_path, pf)
finally:
self._in_commit = False
with self._buf_lock:
final = list(self._buffer.values())
self._buffer.clear()
if final:
self._commit_batch(final)
def _commit_batch(self, batch: List[_Pending]) -> bool:
if not batch:
return True
try:
from huggingface_hub import CommitOperationAdd
except Exception as e:
print(f"[HF] huggingface_hub missing CommitOperationAdd: {e}")
return False
ops, kept = [], []
for pf in batch:
if not Path(pf.local_path).exists():
continue
ops.append(CommitOperationAdd(path_in_repo=pf.repo_path,
path_or_fileobj=pf.local_path))
kept.append(pf)
if not ops:
return True
attempt_429 = 0
attempt_conflict = 0
while True:
try:
self._api.create_commit(
repo_id=self.repo_id, repo_type=self.repo_type,
operations=ops,
commit_message=f"msc: {len(ops)} files @ {now_iso()}")
with self._commit_lock:
self._commit_times.append(time.time())
with self._fp_lock:
for pf in kept:
self._fingerprints.add(pf.fingerprint)
with self._stats_lock:
self._stats["commits"] += 1
self._stats["uploaded"] += len(ops)
print(f"[HF] committed {len(ops)} files -> {self.repo_id}")
return True
except BaseException as e:
code = self._status_code(e)
if code == 429:
if attempt_429 >= self.MAX_ATTEMPTS_429:
break
wait = self.BACKOFF_429[min(attempt_429,
len(self.BACKOFF_429) - 1)]
attempt_429 += 1
with self._stats_lock:
self._stats["retries_429"] += 1
print(f"[HF] 429 rate limited, backoff {wait}s "
f"(attempt {attempt_429})")
if self._stop.wait(wait):
break
elif code in (409, 412):
# Concurrent commit from another account. NOT a rate limit.
if attempt_conflict >= self.MAX_ATTEMPTS_CONFLICT:
break
attempt_conflict += 1
with self._stats_lock:
self._stats["retries_conflict"] += 1
wait = random.uniform(1.0, 5.0)
print(f"[HF] {code} revision conflict, retry in "
f"{wait:.1f}s (attempt {attempt_conflict})")
if self._stop.wait(wait):
break
else:
print(f"[HF] commit failed ({type(e).__name__}): {e}")
break
with self._stats_lock:
self._stats["failed"] += 1
return False
@staticmethod
def _status_code(e: BaseException) -> Optional[int]:
for attr in ("response", "request"):
r = getattr(e, attr, None)
code = getattr(r, "status_code", None)
if code:
return int(code)
s = str(e)
for c in (429, 412, 409, 401, 403):
if str(c) in s:
return c
return None
def load_hf_token() -> str:
"""Kaggle Secrets first, then environment. Never printed anywhere."""
try:
from kaggle_secrets import UserSecretsClient
t = UserSecretsClient().get_secret("HF_TOKEN")
if t:
return t.strip()
except Exception:
pass
for k in ("HF_TOKEN", "HUGGINGFACE_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
if os.environ.get(k):
return os.environ[k].strip()
raise RuntimeError(
"HF_TOKEN not found. Add it under Kaggle -> Add-ons -> Secrets "
"with the name HF_TOKEN, and enable it for this notebook.")
# =============================================================================
# 3. stages -- STATE.json stage machine
# =============================================================================
STAGES = [
"env_capture",
"dataset",
"budgets",
"train_backbone",
"accuracy_gate",
"cache_features",
"train_heads",
"sweep_depth",
"sweep_resolution",
"difficulty_battery",
"emit_parquet",
"finalise",
]
class StageMachine:
"""Idempotency contract.
STATE.json records which stages are done and the sha256 of their outputs.
Every cell opens with `if sm.done(name): skip`. Consequences:
- Every cell is safe to re-run; the second run is a hash-verifying no-op.
- A fresh session with empty local disk pulls STATE.json, finds the first
incomplete stage, pulls only what that stage needs, and continues.
Stage 5 (cache_features) writes to /kaggle/temp and is never pushed: it is
recomputed deterministically from ckpt_last, which is the definition of not
needing to store it.
"""
def __init__(self, local_path, store: Optional[HFStore], repo_path: str):
self.local_path = Path(local_path)
self.store = store
self.repo_path = repo_path
self.state: Dict[str, Any] = {"stages": {}, "schema": "msc_v1"}
self._lock = threading.Lock()
def pull(self) -> Dict[str, Any]:
if self.store is not None:
p = self.store.download(self.repo_path)
if p is not None:
try:
shutil.copy2(p, self.local_path)
except Exception:
pass
loaded = read_json(self.local_path, default=None)
if loaded:
self.state = loaded
return self.state
def done(self, stage: str) -> bool:
return bool(self.state.get("stages", {}).get(stage, {}).get("done"))
def first_incomplete(self) -> str:
for s in STAGES:
if not self.done(s):
return s
return "finalise"
def mark(self, stage: str, outputs: Optional[Dict[str, str]] = None,
**extra) -> None:
with self._lock:
self.state.setdefault("stages", {})[stage] = {
"done": True, "at": now_iso(),
"sha256": outputs or {}, **extra,
}
self.state["updated_utc"] = now_iso()
atomic_write_json(self.local_path, self.state)
if self.store is not None:
self.store.enqueue(self.local_path, self.repo_path)
print(f"[STAGE] {stage} complete")
def note(self, key: str, value) -> None:
with self._lock:
self.state.setdefault("notes", {})[key] = value
atomic_write_json(self.local_path, self.state)
if self.store is not None:
self.store.enqueue(self.local_path, self.repo_path)
class RunStatus:
"""STATUS.json heartbeat. With four concurrent sessions this is the only
thing that makes a dead session detectable."""
def __init__(self, local_path, store: Optional[HFStore], repo_path: str,
run_id: str):
self.local_path = Path(local_path)
self.store = store
self.repo_path = repo_path
self.run_id = run_id
self.data: Dict[str, Any] = {
"run_id": run_id, "state": "starting", "stage": None,
"epoch": -1, "anomalies": [], "started_at": now_iso(),
}
def update(self, **fields) -> None:
self.data.update(fields)
self.data["updated_at"] = now_iso()
atomic_write_json(self.local_path, self.data)
if self.store is not None:
self.store.enqueue(self.local_path, self.repo_path)
def anomaly(self, kind: str, detail: str) -> None:
self.data.setdefault("anomalies", []).append(
{"kind": kind, "detail": detail, "at": now_iso()})
print(f"[ANOMALY] {kind}: {detail}")
self.update()
class Registry:
"""Optimistic claim protocol over HF. No locking primitive exists, so this
is advisory -- but with dynamic claiming it is what decides who does what.
Design point inherited from the AI-detection build: **one writer per path**.
We never append to a shared runs.jsonl from multiple accounts (concurrent
appends conflict and lose entries). Instead each run has its own claim file
and its own done file, so two accounts can never write the same object:
registry/claims/{run_id}.json written only by whoever holds the run
registry/done/{run_id}.json written once, at completion
registry/runs.jsonl static manifest from NB00, never appended
State of a run is then derived, not stored:
DONE -> done/{run_id}.json exists
HELD -> claims/{run_id}.json exists and updated_at is < stale_h old
AVAILABLE -> otherwise (includes a dead session's stale claim)
Race handling: two workers can still claim the same run in the same second.
After writing our claim we wait a random 3-8 s and re-read; if the winner
is not us, we yield and pick another. That is enough for a handful of
accounts and costs nothing when there is no contention.
"""
STALE_H = 2.0
def __init__(self, store: HFStore, account: str, session_id: str,
namespace: str = ""):
"""`namespace` isolates a queue. Smoke runs use "_smoke/" so that a
500-sample 2-epoch rehearsal can exercise the entire claim protocol
without marking a real run done -- which would make the queue skip it
forever, and would look exactly like success."""
self.store = store
self.account = str(account)
self.session_id = session_id
self.ns = namespace
self._tmp = ensure_dir(Path("/tmp/msc_registry"))
def _claim_path(self, run_id: str) -> str:
return f"registry/{self.ns}claims/{run_id}.json"
def _done_path(self, run_id: str) -> str:
return f"registry/{self.ns}done/{run_id}.json"
# ------------------------------------------------------------- reading
def _list(self) -> Set[str]:
return self.store.list_files()
def _read(self, repo_path: str) -> Optional[Dict[str, Any]]:
p = self.store.download(repo_path)
return read_json(p, default=None) if p else None
def status(self, run_ids: Sequence[str]) -> Dict[str, Dict[str, Any]]:
files = self._list()
now = time.time()
out: Dict[str, Dict[str, Any]] = {}
for rid in run_ids:
if self._done_path(rid) in files:
out[rid] = {"state": "done"}
continue
cp = self._claim_path(rid)
if cp in files:
c = self._read(cp) or {}
age_h = (now - float(c.get("epoch_s", 0))) / 3600.0
if age_h < self.STALE_H:
out[rid] = {"state": "held", "by": c.get("account"),
"session": c.get("session"), "age_h": round(age_h, 2)}
else:
out[rid] = {"state": "stale", "by": c.get("account"),
"age_h": round(age_h, 2)}
else:
out[rid] = {"state": "available"}
return out
def print_board(self, run_ids: Sequence[str]) -> Dict[str, Dict[str, Any]]:
st = self.status(run_ids)
print(f"{'run_id':34s} {'state':10s} detail")
print("-" * 74)
for rid in run_ids:
s = st[rid]
detail = ""
if s["state"] in ("held", "stale"):
detail = f"account {s.get('by')}, {s.get('age_h')} h ago"
print(f"{rid:34s} {s['state']:10s} {detail}")
return st
# ------------------------------------------------------------- writing
def _write_claim(self, run_id: str) -> None:
rec = {"run_id": run_id, "account": self.account,
"session": self.session_id, "claimed_at": now_iso(),
"epoch_s": time.time(), "host": os.uname().nodename
if hasattr(os, "uname") else "?"}
p = self._tmp / f"claim_{self.ns.strip('/')}{run_id}.json"
atomic_write_json(p, rec)
self.store.enqueue(p, self._claim_path(run_id))
self.store.flush(120)
def heartbeat(self, run_id: str) -> None:
"""Staleness detection depends on this. Called on every push cycle."""
try:
self._write_claim(run_id)
except Exception as e:
print(f"[REGISTRY] heartbeat failed (non-fatal): {e}")
def complete(self, run_id: str, metrics: Dict[str, Any]) -> None:
rec = {"run_id": run_id, "account": self.account,
"session": self.session_id, "finished_at": now_iso(),
**{k: (float(v) if isinstance(v, (int, float)) else str(v))
for k, v in metrics.items()}}
p = self._tmp / f"done_{self.ns.strip('/')}{run_id}.json"
atomic_write_json(p, rec)
self.store.enqueue(p, self._done_path(run_id))
self.store.flush(120)
print(f"[REGISTRY] {run_id} marked done")
@staticmethod
def plan(run_ids: Sequence[str], n_workers: int) -> Dict[int, List[str]]:
"""Deal the runs round-robin: worker i gets run_ids[i::n_workers].
With 4 runs and 3 workers this is 2+1+1, which is what you want -- the
alternative (contiguous chunks) gives 2+2+0 and leaves a worker idle.
This is a *plan*, not an assignment. It exists so you can see up front
who is expected to do what. Nothing enforces it: a worker that finishes
its share moves on to steal whatever is still outstanding, so a worker
that never starts costs wall clock and nothing else.
"""
n_workers = max(1, int(n_workers))
return {w: list(run_ids[w - 1::n_workers])
for w in range(1, n_workers + 1)}
def show_plan(self, run_ids: Sequence[str], n_workers: int,
me: int) -> List[str]:
pl = self.plan(run_ids, n_workers)
st = self.status(run_ids)
print(f"\nPLAN — {len(run_ids)} runs across {n_workers} worker(s) "
f"[{'+'.join(str(len(v)) for v in pl.values())}]")
print("-" * 78)
for w, runs in pl.items():
tag = " <-- THIS NOTEBOOK" if w == me else ""
print(f" worker {w}{tag}")
for r in runs:
print(f" {r:34s} {st[r]['state']}")
if not runs:
print(" (nothing in its share; it will steal instead)")
print("-" * 78)
print(" Shares are advisory. Any worker that finishes its own share")
print(" steals whatever is still outstanding, so idle workers never")
print(" block the queue -- if worker 3 never starts, workers 1 and 2")
print(" will pick up its runs automatically.")
outstanding = [r for r in run_ids if st[r]["state"] != "done"]
print(f" {len(run_ids)-len(outstanding)}/{len(run_ids)} done, "
f"{len(outstanding)} outstanding\n")
return pl.get(me, [])
def claim_next(self, run_ids: Sequence[str], prefer: Optional[str] = None,
force: bool = False,
my_share: Optional[Sequence[str]] = None) -> Optional[str]:
"""Claim one available run. None when there is nothing left to do.
`prefer` pins a specific run_id (manual mode). `force` takes it even if
someone else holds it -- for when you know the other session is dead
and you do not want to wait out the staleness window.
"""
st = self.status(run_ids)
if prefer:
s = st.get(prefer)
if s is None:
raise ValueError(f"{prefer} is not in the run manifest")
if s["state"] == "done" and not force:
print(f"[REGISTRY] {prefer} is already done. Nothing to do.")
return None
if s["state"] == "held" and not force:
raise RuntimeError(
f"{prefer} is held by account {s.get('by')} "
f"({s.get('age_h')} h ago). Set FORCE_CLAIM=True only if "
f"you know that session is dead -- two sessions writing the "
f"same run will corrupt its checkpoint.")
candidates = [prefer]
else:
free = [r for r in run_ids if st[r]["state"] == "available"]
stale = [r for r in run_ids if st[r]["state"] == "stale"]
if my_share:
# Own share first, then steal. Ordering only; a run outside the
# share is just as claimable, which is what stops an absent
# worker from stalling the queue.
mine = set(my_share)
free = ([r for r in free if r in mine] +
[r for r in free if r not in mine])
stale = ([r for r in stale if r in mine] +
[r for r in stale if r not in mine])
candidates = free + stale
if not candidates:
return None
for rid in candidates:
if my_share is not None and rid not in set(my_share) and not prefer:
print(f"[REGISTRY] own share exhausted -> STEALING {rid} "
f"(it was planned for another worker that has not taken it)")
if st.get(rid, {}).get("state") == "stale":
print(f"[REGISTRY] taking over stale claim on {rid} "
f"({st[rid].get('age_h')} h old) -- resuming from ckpt_last")
self._write_claim(rid)
# optimistic: settle, then confirm we actually won
time.sleep(random.uniform(3.0, 8.0))
c = self._read(self._claim_path(rid)) or {}
if c.get("session") == self.session_id or force:
print(f"[REGISTRY] claimed {rid} (account {self.account})")
return rid
print(f"[REGISTRY] lost race for {rid} to account {c.get('account')}, "
f"trying another")
return None
def log_exception(path, stage: str, epoch: int, e: BaseException) -> None:
"""Failures that were recovered from are still evidence."""
rec = {"at": now_iso(), "stage": stage, "epoch": epoch,
"type": type(e).__name__, "msg": str(e),
"traceback": traceback.format_exc()[-4000:]}
p = Path(path)
ensure_dir(p.parent)
with open(p, "a", encoding="utf-8") as f:
f.write(json.dumps(rec) + "\n")
# =============================================================================
# 4. config -- science / runtime split and config_hash
# =============================================================================
def build_config(run_id: str, arch: str, seed: int, *,
dataset: str = "cifar100", epochs: int = 240,
batch_size: int = 64, lr: float = 0.05,
momentum: float = 0.9, weight_decay: float = 5e-4,
milestones: Sequence[int] = (150, 180, 210),
gamma: float = 0.1,
exit_fractions: Sequence[float] = (0.2, 0.4, 0.6, 0.8, 1.0),
resolutions: Sequence[int] = (16, 20, 24, 28, 32),
taus: Sequence[float] = (0.0, 0.1, 0.2, 0.3, 0.5),
head_seeds: Sequence[int] = (1, 2, 3),
head_epochs: int = 20, head_lr: float = 0.01,
train_seen_n: int = 5000,
el2n_epoch: int = 20,
deterministic: bool = True,
smoke: bool = False) -> Dict[str, Any]:
"""The science block is hashed; the runtime block is not.
Hashing runtime would make every legitimate resume on a different session
fail, and a policy that cries wolf gets disabled by the third day.
"""
science = {
"run_id": run_id,
"arch": arch,
"dataset": dataset,
"seed": int(seed),
"epochs": int(epochs),
"batch_size": int(batch_size),
"lr": float(lr),
"momentum": float(momentum),
"weight_decay": float(weight_decay),
"milestones": [int(m) for m in milestones],
"gamma": float(gamma),
"augment": "randomcrop32_pad4 + hflip",
"normalize_mean": [0.5071, 0.4865, 0.4409],
"normalize_std": [0.2673, 0.2564, 0.2762],
"exit_fractions": [float(f) for f in exit_fractions],
"resolutions": [int(r) for r in resolutions],
"resolution_primary": "native",
"taus": [float(t) for t in taus],
"head_seeds": [int(s) for s in head_seeds],
"head_epochs": int(head_epochs),
"head_lr": float(head_lr),
"head_augment": False,
"train_seen_n": int(train_seen_n),
"el2n_epoch": int(el2n_epoch),
"model_of_record": "ckpt_last",
"smoke": bool(smoke),
"lib_version": __version__,
}
runtime = {
"account_index": 0,
"push_interval_min": 20,
"session_budget_h": 8.5,
"num_workers": 2,
"amp": True,
"deterministic": bool(deterministic),
"work_dir": "/kaggle/working",
"scratch_dir": "/kaggle/temp",
"force_claim": False,
"force_config_override": False,
"fast_data": True,
"show_progress": True,
}
return {"science": science, "runtime": runtime}
def config_hash(cfg: Dict[str, Any]) -> str:
return sha256_bytes(canonical_json(cfg["science"]).encode())
class ConfigDriftError(RuntimeError):
pass
def assert_config_hash(cfg: Dict[str, Any], ckpt: Dict[str, Any]) -> None:
"""Fail loudly on mismatch. Silently resuming under an edited config is
worse than crashing."""
want = config_hash(cfg)
got = ckpt.get("config_hash")
if got == want:
return
if cfg["runtime"].get("force_config_override"):
print(f"[CONFIG] !! OVERRIDE: hash {got} != {want}. "
f"Run will be permanently marked config_override=true.")
return
raise ConfigDriftError(
f"config_hash mismatch.\n checkpoint: {got}\n current: {want}\n"
f"The science block has changed since this run started. Either restore "
f"the original config, or set runtime.force_config_override=True to "
f"resume anyway (the run will be permanently flagged)."
)
ACCURACY_GATE = {
# arch -> (published, halt_below, warn_below)
"resnet32x4": (79.42, 78.40, 79.00),
"wrn40x2": (75.61, 74.60, 75.20),
}
# =============================================================================
# 5. data -- CIFAR-100 with a canonical, asserted ordering
# =============================================================================
CIFAR100_MEAN = (0.5071, 0.4865, 0.4409)
CIFAR100_STD = (0.2673, 0.2564, 0.2762)
# Team-owned Kaggle mirrors of the ORIGINAL cs.toronto.edu tarballs.
# Using the official pickle rather than any PNG-folder mirror is not a
# convenience choice: with a train/<class>/*.png layout, enumeration order
# depends on filenames and class-directory sort order, so two runs using
# different mirrors would get different sample_idx -> image maps. That breaks
# row alignment at the source and nothing downstream looks wrong.
KAGGLE_DATASETS = {
"cifar100": "shanmuk4622/dataset-cifar100-python",
"cifar10": "shanmuk4622/dataset-cifar10-python",
}
_PICKLE_DIRNAME = {"cifar100": "cifar-100-python", "cifar10": "cifar-10-batches-py"}
_PICKLE_FILES = {"cifar100": ("train", "test"),
"cifar10": ("data_batch_1", "test_batch")}
def _is_pickle_root(p: Path, which: str) -> bool:
"""True if p DIRECTLY contains the split files (no nesting)."""
return p.is_dir() and all((p / f).exists() for f in _PICKLE_FILES[which])
def _find_pickle_root(base: Path, which: str, depth: int = 3) -> Optional[Path]:
"""Locate the directory holding the split files, whatever the nesting.
Kaggle datasets preserve whatever the uploader zipped, so all three of
these are possible and all three must work:
<base>/cifar-100-python/train
<base>/train
<base>/anything/cifar-100-python/train
"""
if not base.exists():
return None
if _is_pickle_root(base, which):
return base
cand = base / _PICKLE_DIRNAME[which]
if _is_pickle_root(cand, which):
return cand
try:
for p in base.rglob("*"):
if p.is_dir() and len(p.relative_to(base).parts) <= depth \
and _is_pickle_root(p, which):
return p
except Exception:
pass
return None
def _extract_any_tarball(base: Path, which: str, scratch: Path) -> Optional[Path]:
"""Some uploads keep the .tar.gz. Extract to scratch, never to
/kaggle/working -- that is 20 GB and it is the artifact space."""
import tarfile
if not base.exists():
return None
for tb in list(base.glob("*.tar.gz")) + list(base.glob("*.tgz")):
dest = ensure_dir(scratch / "data")
print(f"[DATA] extracting {tb.name} -> {dest}")
try:
with tarfile.open(tb) as t:
t.extractall(dest)
except Exception as e:
print(f"[DATA] extract failed: {e}")
continue
r = _find_pickle_root(dest, which)
if r is not None:
return r
return None
def locate_cifar(which: str = "cifar100",
scratch_dir: str = "/kaggle/temp") -> str:
"""Return the directory that DIRECTLY contains the CIFAR pickle splits.
Resolution order, fastest first:
1. An attached Kaggle dataset (no download at all).
2. kagglehub download of the team mirror -- public, inside Kaggle, fast.
3. A tarball in any attached dataset, extracted to scratch.
4. torchvision download from cs.toronto.edu (last resort, slowest).
Whichever path wins, dataset_fingerprint() is asserted against the value
frozen at bootstrap, so a changed source cannot silently repermute
sample_idx.
"""
assert which in KAGGLE_DATASETS, f"unknown dataset {which}"
scratch = Path(scratch_dir)
slug = KAGGLE_DATASETS[which]
short = slug.split("/")[-1]
# 1. attached Kaggle dataset -- check the expected mount name first
inp = Path("/kaggle/input")
for base in [inp / short, inp / short.replace("dataset-", ""),
inp / _PICKLE_DIRNAME[which]]:
r = _find_pickle_root(base, which)
if r is not None:
print(f"[DATA] attached Kaggle dataset: {r}")
return str(r)
if inp.exists():
for base in sorted(inp.iterdir()):
r = _find_pickle_root(base, which)
if r is not None:
print(f"[DATA] attached Kaggle dataset: {r}")
return str(r)
# 2. kagglehub -- the mirrors are public, so no credentials needed
try:
import kagglehub
print(f"[DATA] kagglehub download: {slug}")
p = Path(kagglehub.dataset_download(slug))
r = _find_pickle_root(p, which) or _extract_any_tarball(p, which, scratch)
if r is not None:
print(f"[DATA] kagglehub -> {r}")
return str(r)
print(f"[DATA] kagglehub returned {p} but no pickle splits inside")
except Exception as e:
print(f"[DATA] kagglehub unavailable ({type(e).__name__}: {e})")
# 3. tarball inside any attached dataset
if inp.exists():
for base in sorted(inp.iterdir()):
r = _extract_any_tarball(base, which, scratch)
if r is not None:
return str(r)
# 3b. anything already extracted into scratch by a previous session
r = _find_pickle_root(scratch / "data", which)
if r is not None:
print(f"[DATA] cached in scratch: {r}")
return str(r)
# 4. torchvision, last resort
root = ensure_dir(scratch / "data")
print(f"[DATA] falling back to torchvision download of {which} "
f"(slower; prefer attaching {slug})")
from torchvision import datasets
ds = datasets.CIFAR100 if which == "cifar100" else datasets.CIFAR10
ds(root=str(root), train=True, download=True)
ds(root=str(root), train=False, download=True)
r = _find_pickle_root(root, which)
assert r is not None, f"{which} download did not produce the pickle splits"
return str(r)
def locate_cifar100(scratch_dir: str = "/kaggle/temp") -> str:
"""Back-compat alias. Phase 0 is CIFAR-100 only."""
return locate_cifar("cifar100", scratch_dir)
def _load_cifar100_raw(root: str, train: bool) -> Tuple[np.ndarray, np.ndarray]:
"""Load straight from the pickle so the ordering is canonically defined.
`root` DIRECTLY contains `train` and `test` -- locate_cifar() has already
resolved whatever nesting the Kaggle upload happened to use.
"""
f = Path(root) / ("train" if train else "test")
if not f.exists(): # tolerate a stray extra nesting
alt = Path(root) / "cifar-100-python" / ("train" if train else "test")
if alt.exists():
f = alt
with open(f, "rb") as fh:
d = pickle.load(fh, encoding="bytes")
data = d[b"data"].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1) # NHWC uint8
labels = np.array(d[b"fine_labels"], dtype=np.int64)
return np.ascontiguousarray(data), labels
def dataset_fingerprint(root: str) -> Dict[str, str]:
"""sha256 over labels and the leading image bytes, both splits.
Asserted equal across all four runs at analysis time. Catches a swapped
mirror, a re-uploaded dataset, and a torchvision version change -- any of
which would silently repermute sample_idx.
"""
fp = {}
for split, train in (("train", True), ("test", False)):
data, labels = _load_cifar100_raw(root, train)
fp[f"{split}_n"] = str(len(labels))
fp[f"{split}_labels_sha256"] = sha256_bytes(labels.astype(np.uint8).tobytes())
fp[f"{split}_pixels_sha256"] = sha256_bytes(data[:100].tobytes())
return fp
class CIFAR100Tensor:
"""In-memory uint8 dataset. Order is the pickle order, always.
Augmentation is applied on the fly and consumes the per-worker torch RNG,
so it is captured by the checkpoint's RNG state.
"""
def __init__(self, root: str, train: bool, augment: bool,
indices: Optional[np.ndarray] = None):
data, labels = _load_cifar100_raw(root, train)
self.all_idx = np.arange(len(labels)) if indices is None else np.asarray(indices)
self.data = torch.from_numpy(data[self.all_idx]).permute(0, 3, 1, 2).contiguous()
self.labels = torch.from_numpy(labels[self.all_idx])
self.augment = augment
self.mean = torch.tensor(CIFAR100_MEAN).view(3, 1, 1)
self.std = torch.tensor(CIFAR100_STD).view(3, 1, 1)
def __len__(self) -> int:
return len(self.labels)
def __getitem__(self, i: int):
img = self.data[i]
if self.augment:
# torchvision RandomCrop(32, padding=4): zero-pad the uint8 image,
# then crop. Zero in [0,255] space, NOT zero after normalisation.
img = F.pad(img.unsqueeze(0), (4, 4, 4, 4), mode="constant",
value=0).squeeze(0)
top = int(torch.randint(0, 9, (1,)).item())
left = int(torch.randint(0, 9, (1,)).item())
img = img[:, top:top + 32, left:left + 32]
if torch.rand(1).item() < 0.5:
img = torch.flip(img, dims=[2])
x = img.float().div_(255.0).sub_(self.mean).div_(self.std)
return x, self.labels[i], int(self.all_idx[i])
def build_loaders(cfg: Dict[str, Any], root: str, device=None,
fast_gpu: bool = True):
"""Train loader is shuffled with an explicit, seeded generator.
EVERY eval loader is shuffle=False, drop_last=False, sampler=None --
the canonical ordering that sample_idx refers to."""
from torch.utils.data import DataLoader
sci, rt = cfg["science"], cfg["runtime"]
seed = sci["seed"]
nw = int(rt.get("num_workers", 2))
n_train = 500 if sci["smoke"] else None
n_test = 500 if sci["smoke"] else None
tr_idx = np.arange(n_train) if n_train else None
te_idx = np.arange(n_test) if n_test else None
train_ds = CIFAR100Tensor(root, True, augment=True, indices=tr_idx)
train_eval_ds = CIFAR100Tensor(root, True, augment=False, indices=tr_idx)
test_ds = CIFAR100Tensor(root, False, augment=False, indices=te_idx)
g = torch.Generator()
g.manual_seed(derive_seed(seed, "dataloader_shuffle"))
common = dict(num_workers=nw, pin_memory=True,
persistent_workers=bool(nw), )
if nw:
common["prefetch_factor"] = 4
common["worker_init_fn"] = worker_init_fn_factory(
derive_seed(seed, "worker"))
gpu_ds = None
if fast_gpu and device is not None and getattr(device, "type", "") == "cuda":
try:
gpu_ds = GPUCifar(root, True, device, indices=tr_idx)
print(f"[DATA] GPU-resident training set: {len(gpu_ds)} images, "
f"{gpu_ds.x.numel()/1e6:.0f} MB uint8 on device "
f"(dataloader removed from the critical path)")
except Exception as e:
print(f"[DATA] GPU pipeline unavailable ({e}); using DataLoader")
gpu_ds = None
train_loader = DataLoader(train_ds, batch_size=sci["batch_size"],
shuffle=True, drop_last=False, generator=g,
**common)
eval_common = dict(num_workers=nw, pin_memory=True,
persistent_workers=bool(nw))
if nw:
eval_common["prefetch_factor"] = 4
train_eval_loader = DataLoader(train_eval_ds, batch_size=256, shuffle=False,
drop_last=False, sampler=None, **eval_common)
test_loader = DataLoader(test_ds, batch_size=256, shuffle=False,
drop_last=False, sampler=None, **eval_common)
return train_loader, train_eval_loader, test_loader, gpu_ds
class GPUCifar:
"""The whole dataset resident on the GPU as uint8, augmented in batch.
Why this exists: CIFAR ResNets at batch 64 are *latency* bound, not compute
bound. resnet32x4 is ~1.09 GMACs, so a batch takes single-digit ms on a T4 --
but a Python DataLoader doing per-sample pad/crop/flip/normalise on 2 Kaggle
vCPUs cannot keep up, and the GPU spends most of the epoch waiting. Moving
the 150 MB of uint8 pixels onto the card removes the dataloader from the
critical path entirely.
Semantics are matched to torchvision EXACTLY, not approximately:
RandomCrop(32, padding=4) -> zero-pad in [0,255] uint8 space, THEN crop.
(Padding before normalisation matters: zero in pixel space is NOT
zero after Normalize, so padding a normalised tensor would train on
different data.)
RandomHorizontalFlip(p=0.5)
ToTensor -> /255
Normalize(mean, std)
verify_msc_lib.py section 15 asserts pixel-exact agreement with the
torchvision ops for fixed (top, left, flip), so this is a speed change and
not a recipe change.
Augmentation draws from the torch CUDA RNG, so it is captured by the
checkpoint's RNG state and a resumed run sees the same augmentations.
"""
def __init__(self, root: str, train: bool, device, indices=None):
data, labels = _load_cifar100_raw(root, train)
idx = np.arange(len(labels)) if indices is None else np.asarray(indices)
self.sample_idx = torch.from_numpy(idx.astype(np.int64)).to(device)
self.x = torch.from_numpy(data[idx]).permute(0, 3, 1, 2).contiguous().to(device)
self.y = torch.from_numpy(labels[idx]).to(device)
self.device = device
self.n = len(idx)
self.mean = torch.tensor(CIFAR100_MEAN, device=device).view(1, 3, 1, 1) * 255.0
self.std = torch.tensor(CIFAR100_STD, device=device).view(1, 3, 1, 1) * 255.0
self._padded = None
def __len__(self) -> int:
return self.n
def _norm(self, xb: torch.Tensor) -> torch.Tensor:
return (xb.float() - self.mean) / self.std
def augment(self, xb_u8: torch.Tensor, gen=None) -> torch.Tensor:
"""Batched RandomCrop(32, pad=4) + RandomHorizontalFlip, on GPU."""
b = xb_u8.shape[0]
xp = F.pad(xb_u8, (4, 4, 4, 4), mode="constant", value=0) # uint8 space
top = torch.randint(0, 9, (b,), device=self.device, generator=gen)
left = torch.randint(0, 9, (b,), device=self.device, generator=gen)
ar = torch.arange(32, device=self.device)
r = (top.view(b, 1) + ar.view(1, 32)).view(b, 1, 32, 1).expand(b, 3, 32, 40)
xp = xp.gather(2, r)
c = (left.view(b, 1) + ar.view(1, 32)).view(b, 1, 1, 32).expand(b, 3, 32, 32)
xp = xp.gather(3, c)
flip = torch.rand(b, device=self.device, generator=gen) < 0.5
xp = torch.where(flip.view(b, 1, 1, 1), xp.flip(3), xp)
return self._norm(xp)
def train_batches(self, batch_size: int, gen=None):
perm = torch.randperm(self.n, device=self.device, generator=gen)
for i in range(0, self.n, batch_size):
sl = perm[i:i + batch_size]
yield self.augment(self.x[sl], gen), self.y[sl], self.sample_idx[sl]
def eval_batches(self, batch_size: int = 512, resolution: int = 32,
mode: str = "native"):
"""Deterministic order, no augmentation. THIS is the canonical
sample_idx ordering that every per-sample table refers to."""
for i in range(0, self.n, batch_size):
xb = self._norm(self.x[i:i + batch_size])
if resolution != 32:
xb = F.interpolate(xb, size=(resolution, resolution),
mode="bilinear", align_corners=False)
if mode == "upsample":
xb = F.interpolate(xb, size=(32, 32), mode="bilinear",
align_corners=False)
yield xb, self.y[i:i + batch_size], self.sample_idx[i:i + batch_size]
def n_batches(self, batch_size: int) -> int:
return (self.n + batch_size - 1) // batch_size
def make_progress(total: int, desc: str, enable: bool = True):
"""tqdm if available, otherwise a dependency-free fallback bar."""
if not enable:
class _Null:
def update(self, n=1): pass
def set_postfix_str(self, s): pass
def close(self): pass
return _Null()
try:
from tqdm.auto import tqdm
return tqdm(total=total, desc=desc, leave=False, dynamic_ncols=True,
mininterval=0.5)
except Exception:
class _Bar:
def __init__(s, total, desc):
s.total, s.desc, s.i, s.t0 = total, desc, 0, time.time()
s.post = ""
def update(s, n=1):
s.i += n
if s.i % max(1, s.total // 40) and s.i != s.total:
return
frac = s.i / max(s.total, 1)
done = int(30 * frac)
el = time.time() - s.t0
eta = el / max(frac, 1e-9) - el
sys.stdout.write(f"\r {s.desc} |{'#'*done}{'.'*(30-done)}| "
f"{s.i}/{s.total} {el:5.1f}s eta {eta:5.1f}s {s.post}")
sys.stdout.flush()
def set_postfix_str(s, t): s.post = t
def close(s):
sys.stdout.write("\r" + " " * 110 + "\r")
sys.stdout.flush()
return _Bar(total, desc)
def frozen_train_slice(n_total: int, n_slice: int, master_seed: int = 0) -> List[int]:
"""A fixed 5,000-index slice of the TRAINING set that IS trained on.
Identical across all four runs. Note: trained on, not held out -- EL2N,
forgetting events and prediction depth are only defined on training
examples, and holding 5,000 out would cost ~0.5-1 point of test accuracy
and risk tripping the accuracy gate for a reason unrelated to the recipe.
"""
rng = np.random.default_rng(derive_seed(master_seed, "train_seen_slice"))
return sorted(rng.choice(n_total, size=min(n_slice, n_total),
replace=False).tolist())
# =============================================================================
# 6. models -- faithful to the CRD/DKD CIFAR recipe
# =============================================================================
#
# These must match mdistiller exactly, because the accuracy gate compares
# against published numbers (resnet32x4 79.42, wrn-40-2 75.61) produced under
# that implementation. The ONLY deliberate change is AvgPool2d(8) ->
# AdaptiveAvgPool2d(1), which is bit-identical at 32px and is what lets the
# resolution axis run genuinely at native r.
class _BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super().__init__()
self.conv1 = nn.Conv2d(inplanes, planes, 3, stride, 1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(planes, planes, 3, 1, 1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
def forward(self, x):
residual = x if self.downsample is None else self.downsample(x)
out = self.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
return F.relu(out + residual)
class ResNetCifar(nn.Module):
"""resnet32x4 = ResNetCifar(32, [32, 64, 128, 256]).
depth 32 -> n = (32-2)//6 = 5 blocks per stage, 15 blocks total.
"""
def __init__(self, depth: int, num_filters: Sequence[int],
num_classes: int = 100):
super().__init__()
assert (depth - 2) % 6 == 0
n = (depth - 2) // 6
self.inplanes = num_filters[0]
self.conv1 = nn.Conv2d(3, num_filters[0], 3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(num_filters[0])
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(num_filters[1], n, 1)
self.layer2 = self._make_layer(num_filters[2], n, 2)
self.layer3 = self._make_layer(num_filters[3], n, 2)
self.avgpool = nn.AdaptiveAvgPool2d(1) # was AvgPool2d(8); identical at 32px
self.fc = nn.Linear(num_filters[3], num_classes)
self.preact = False
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out",
nonlinearity="relu")
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, planes, blocks, stride):
downsample = None
if stride != 1 or self.inplanes != planes:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes, 1, stride, bias=False),
nn.BatchNorm2d(planes))
layers = [_BasicBlock(self.inplanes, planes, stride, downsample)]
self.inplanes = planes
layers += [_BasicBlock(planes, planes) for _ in range(1, blocks)]
return nn.Sequential(*layers)
def blocks(self) -> List[nn.Module]:
return list(self.layer1) + list(self.layer2) + list(self.layer3)
def stem(self, x):
return self.relu(self.bn1(self.conv1(x)))
def head_from(self, feat):
"""The model's own classifier. Exit K uses this verbatim."""
return self.fc(self.avgpool(feat).flatten(1))
def forward(self, x):
f = self.stem(x)
for b in self.blocks():
f = b(f)
return self.head_from(f)
class _WideBasic(nn.Module):
"""Pre-activation block, as in the WRN reference implementation."""
def __init__(self, in_planes, out_planes, stride):
super().__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, 3, stride, 1, bias=False)
self.bn2 = nn.BatchNorm2d(out_planes)
self.relu2 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_planes, out_planes, 3, 1, 1, bias=False)
self.equalInOut = (in_planes == out_planes and stride == 1)
self.convShortcut = None if self.equalInOut else nn.Conv2d(
in_planes, out_planes, 1, stride, 0, bias=False)
def forward(self, x):
if not self.equalInOut:
x = self.relu1(self.bn1(x))
out = self.relu2(self.bn2(self.conv1(x)))
else:
out = self.relu1(self.bn1(x))
out = self.relu2(self.bn2(self.conv1(out)))
out = self.conv2(out)
return out + (x if self.equalInOut else self.convShortcut(x))
class WideResNet(nn.Module):
"""wrn-40-2 = WideResNet(40, 2). n = (40-4)//6 = 6 -> 18 blocks."""
def __init__(self, depth: int, widen: int, num_classes: int = 100):
super().__init__()
assert (depth - 4) % 6 == 0
n = (depth - 4) // 6
ch = [16, 16 * widen, 32 * widen, 64 * widen]
self.conv1 = nn.Conv2d(3, ch[0], 3, 1, 1, bias=False)
self.block1 = self._make(ch[0], ch[1], n, 1)
self.block2 = self._make(ch[1], ch[2], n, 2)
self.block3 = self._make(ch[2], ch[3], n, 2)
self.bn1 = nn.BatchNorm2d(ch[3])
self.relu = nn.ReLU(inplace=True)
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Linear(ch[3], num_classes)
self.preact = True
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode="fan_out",
nonlinearity="relu")
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.constant_(m.bias, 0)
@staticmethod
def _make(inp, outp, n, stride):
return nn.Sequential(*[
_WideBasic(inp if i == 0 else outp, outp, stride if i == 0 else 1)
for i in range(n)])
def blocks(self) -> List[nn.Module]:
return list(self.block1) + list(self.block2) + list(self.block3)
def stem(self, x):
return self.conv1(x)
def head_from(self, feat):
return self.fc(self.avgpool(self.relu(self.bn1(feat))).flatten(1))
def forward(self, x):
f = self.stem(x)
for b in self.blocks():
f = b(f)
return self.head_from(f)
def build_model(arch: str, num_classes: int = 100) -> nn.Module:
if arch == "resnet32x4":
return ResNetCifar(32, [32, 64, 128, 256], num_classes)
if arch == "wrn40x2":
return WideResNet(40, 2, num_classes)
raise ValueError(f"unknown arch {arch}")
def exit_block_indices(model: nn.Module, fractions: Sequence[float]) -> List[int]:
"""round(frac * n_blocks), minimum 1. Documented rounding rule."""
n = len(model.blocks())
idx = [max(1, int(round(f * n))) for f in fractions]
assert idx[-1] == n, f"last exit must be the full backbone: {idx[-1]} != {n}"
assert all(a < b for a, b in zip(idx, idx[1:])), f"exits not strictly increasing: {idx}"
return idx
@torch.no_grad()
def exit_channels(model: nn.Module, block_idx: Sequence[int],
device="cpu") -> List[int]:
model.eval()
x = torch.zeros(2, 3, 32, 32, device=device)
f = model.stem(x)
chans, want = [], set(block_idx)
for i, b in enumerate(model.blocks(), start=1):
f = b(f)
if i in want:
chans.append(int(f.shape[1]))
return chans
def measure_budgets(model: nn.Module, block_idx: Sequence[int],
resolutions: Sequence[int]) -> Dict[str, Any]:
"""Measured FLOPs per configuration, not assumed.
Stage FLOPs are near-equal by design in these architectures, but 'near' is
not 'is', and Q2's PCA reads raw rho values. Falls back to an analytic
conv-MAC count if fvcore/ptflops are unavailable.
"""
device = next(model.parameters()).device
model.eval()
n_blocks = len(model.blocks())
num_classes = model.fc.out_features
def flops_prefix(k: int, res: int) -> float:
"""MACs for stem + blocks[1..k] + the head that reads exit k.
The head at k < K is the *exit probe* (pool -> BN1d -> Linear over the
channels present at that depth), NOT the model's final classifier.
Calling model.head_from() on an intermediate feature map is a shape
error -- block 3 of resnet32x4 emits 64 channels into a Linear(256,100)
-- and, more importantly, it would be the wrong cost: exit k is priced
with the head that is actually attached to it.
"""
total = [0.0]
hooks = []
def hook(m, inp, out):
if isinstance(m, nn.Conv2d):
total[0] += (m.in_channels / m.groups) * m.out_channels * \
m.kernel_size[0] * m.kernel_size[1] * out.shape[2] * out.shape[3]
elif isinstance(m, nn.Linear):
total[0] += m.in_features * m.out_features
for mod in model.modules():
if isinstance(mod, (nn.Conv2d, nn.Linear)):
hooks.append(mod.register_forward_hook(hook))
head_macs = 0.0
with torch.no_grad():
x = torch.zeros(1, 3, res, res, device=device)
f = model.stem(x)
for i, b in enumerate(model.blocks(), start=1):
if i > k:
break
f = b(f)
if k >= n_blocks:
_ = model.head_from(f) # the real classifier; hook counts it
else:
head_macs = float(f.shape[1]) * num_classes # linear probe
for h in hooks:
h.remove()
return total[0] + head_macs
full32 = flops_prefix(len(model.blocks()), 32)
depth = [flops_prefix(k, 32) for k in block_idx]
res = [flops_prefix(len(model.blocks()), r) for r in resolutions]
out = {
"flops_full_32px": full32,
"depth_block_idx": list(map(int, block_idx)),
"depth_flops": depth,
"rho_depth": [f / full32 for f in depth],
"resolutions": list(map(int, resolutions)),
"resolution_flops": res,
"rho_resolution": [f / full32 for f in res],
"rho_resolution_analytic": [(r / 32.0) ** 2 for r in resolutions],
"note": "MACs counted by forward hooks on Conv2d/Linear; head cost included.",
}
for key in ("rho_depth", "rho_resolution"):
v = out[key]
assert abs(v[-1] - 1.0) < 1e-6, f"{key}[-1] must be 1.0, got {v[-1]}"
assert all(a < b for a, b in zip(v, v[1:])), f"{key} not ascending: {v}"
return out
# =============================================================================
# 7. exits -- probes on a genuinely frozen backbone
# =============================================================================
class ExitHead(nn.Module):
"""pool -> BN -> linear. Deliberately small.
A heavier head would do its own representation learning, which confounds
the measurement: we want to read what the backbone has computed by this
depth, not what a capable head can recover from it.
"""
def __init__(self, in_channels: int, num_classes: int):
super().__init__()
self.norm = nn.BatchNorm1d(in_channels)
self.fc = nn.Linear(in_channels, num_classes)
def forward(self, pooled: torch.Tensor) -> torch.Tensor:
return self.fc(self.norm(pooled))
def backbone_hash(model: nn.Module) -> str:
"""sha256 over parameters AND buffers.
Buffers are where BatchNorm running statistics live. A parameter-only
comparison would miss BN drift, which is precisely the failure mode
requires_grad=False does not prevent.
"""
h = hashlib.sha256()
for k, v in sorted(model.state_dict().items()):
h.update(k.encode())
h.update(np.ascontiguousarray(v.detach().cpu().numpy()).tobytes())
return h.hexdigest()
@torch.no_grad()
def cache_pooled_features(model: nn.Module, loader, block_idx: Sequence[int],
device, out_path) -> Dict[str, Any]:
"""One pass over the data, storing globally-pooled features at each exit.
This is the strongest possible freeze: after caching, the backbone is not
in the training graph at all. It also makes head training a seconds-long
linear+BN fit rather than a 15-minute pass, which is what makes three head
seeds free.
No augmentation -- these are probes measuring a representation, not
deployed classifiers.
"""
model.eval()
want = set(block_idx)
feats: Dict[int, List[torch.Tensor]] = {k: [] for k in block_idx}
labels, idxs = [], []
for x, y, si in loader:
x = x.to(device, non_blocking=True)
f = model.stem(x)
for i, b in enumerate(model.blocks(), start=1):
f = b(f)
if i in want:
g = model.relu(model.bn1(f)) if getattr(model, "preact", False) \
and i == len(model.blocks()) else f
feats[i].append(F.adaptive_avg_pool2d(g, 1).flatten(1).cpu())
labels.append(y.clone())
idxs.append(si.clone() if torch.is_tensor(si) else torch.as_tensor(si))
out = {"block_idx": list(map(int, block_idx)),
"labels": torch.cat(labels),
"sample_idx": torch.cat(idxs)}
for k in block_idx:
out[f"feat_{k}"] = torch.cat(feats[k])
ensure_dir(Path(out_path).parent)
torch.save(out, out_path)
return out
def train_exit_heads(cached_train: Dict[str, Any], cached_test: Dict[str, Any],
block_idx: Sequence[int], num_classes: int,
head_seed: int, epochs: int, lr: float,
device) -> Dict[int, nn.Module]:
"""Fit one probe per exit on cached pooled features.
Exit K is NOT trained here -- it is the model's own classifier, used
verbatim, because compute_msc takes preds[:, -1] as the full-compute
reference y*. If that column came from a probe, the reference decision
would be the probe's rather than the model's.
"""
heads: Dict[int, nn.Module] = {}
y = cached_train["labels"].to(device)
n = y.numel()
for k in block_idx[:-1]:
set_all_seeds(derive_seed(head_seed, "head", k), deterministic=False)
X = cached_train[f"feat_{k}"].to(device)
head = ExitHead(X.shape[1], num_classes).to(device)
opt = torch.optim.SGD(head.parameters(), lr=lr, momentum=0.9,
weight_decay=5e-4)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
bs = 256
g = torch.Generator(device="cpu")
g.manual_seed(derive_seed(head_seed, "head_shuffle", k))
for _ in range(epochs):
head.train()
perm = torch.randperm(n, generator=g).to(device)
for i in range(0, n, bs):
sl = perm[i:i + bs]
if sl.numel() < 2:
continue
opt.zero_grad(set_to_none=True)
loss = F.cross_entropy(head(X[sl]), y[sl])
loss.backward()
opt.step()
sched.step()
head.eval()
heads[k] = head
return heads
# =============================================================================
# 8. energy -- NVML background sampler
# =============================================================================
class EnergyMonitor:
"""Direct power sampling at >=10 Hz. Reported as methodology, never as a
novelty claim. Cumulative joules survive restarts via the checkpoint."""
def __init__(self, csv_path, hz: float = 10.0):
self.csv_path = Path(csv_path)
self.dt = 1.0 / hz
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
self.joules = 0.0
self._h = None
def start(self, resume_joules: float = 0.0) -> bool:
self.joules = float(resume_joules)
try:
import pynvml
pynvml.nvmlInit()
self._h = pynvml.nvmlDeviceGetHandleByIndex(0)
except Exception as e:
print(f"[ENERGY] NVML unavailable ({e}); energy.csv will be empty")
return False
ensure_dir(self.csv_path.parent)
if not self.csv_path.exists():
atomic_write_text(self.csv_path, "time_utc,watts,cum_joules\n")
self._stop.clear()
self._thread = threading.Thread(target=self._loop, daemon=True,
name="nvml")
self._thread.start()
return True
def _loop(self):
import pynvml
last = time.time()
buf = []
while not self._stop.is_set():
time.sleep(self.dt)
try:
w = pynvml.nvmlDeviceGetPowerUsage(self._h) / 1000.0
except Exception:
continue
now = time.time()
self.joules += w * (now - last)
last = now
buf.append(f"{now_iso()},{w:.2f},{self.joules:.1f}\n")
if len(buf) >= 100:
try:
with open(self.csv_path, "a") as f:
f.writelines(buf)
except Exception:
pass
buf = []
if buf:
try:
with open(self.csv_path, "a") as f:
f.writelines(buf)
except Exception:
pass
def stop(self):
self._stop.set()
if self._thread:
self._thread.join(timeout=5)
self._thread = None
# =============================================================================
# 9. checkpoint -- the full resumability contract
# =============================================================================
CKPT_REQUIRED = ("run_id", "epoch", "global_step", "model", "optimizer",
"scheduler", "scaler", "rng", "best_metric", "config_hash",
"wall_seconds", "energy_joules")
def _schema_check(state: Dict[str, Any]) -> None:
"""Runs on SAVE as well as load, so an omission is caught the first time
rather than at the first resume."""
missing = [k for k in CKPT_REQUIRED if k not in state]
if missing:
raise RuntimeError(f"checkpoint schema incomplete, missing: {missing}")
for k in ("python", "numpy", "torch", "cuda"):
if k not in state["rng"]:
raise RuntimeError(f"checkpoint rng state missing '{k}'. "
f"A resumed run would not equal an uninterrupted "
f"one, which makes the seeds meaningless.")
def save_checkpoint(path, cfg, model, optimizer, scheduler, scaler,
epoch: int, global_step: int, best_metric: float,
wall_seconds: float, energy_joules: float,
extra: Optional[Dict[str, Any]] = None) -> None:
state = {
"run_id": cfg["science"]["run_id"],
"epoch": int(epoch),
"global_step": int(global_step),
"model": model.state_dict(),
"optimizer": optimizer.state_dict(),
"scheduler": scheduler.state_dict() if scheduler is not None else None,
"scaler": scaler.state_dict() if scaler is not None else None,
"rng": rng_state(),
"best_metric": float(best_metric),
"config_hash": config_hash(cfg),
"wall_seconds": float(wall_seconds),
"energy_joules": float(energy_joules),
"torch_version": torch.__version__,
"gpu_name": (torch.cuda.get_device_name(0)
if torch.cuda.is_available() else "cpu"),
"deterministic": bool(cfg["runtime"].get("deterministic", True)),
"saved_at": now_iso(),
}
if extra:
state.update(extra)
_schema_check(state)
atomic_save_torch(path, state)
def load_checkpoint(path, cfg, model, optimizer, scheduler, scaler,
device, status: Optional[RunStatus] = None
) -> Optional[Dict[str, Any]]:
"""Returns None if there is nothing to resume from."""
path = Path(path)
if not path.exists():
return None
try:
try:
st = torch.load(path, map_location=device, weights_only=False)
except TypeError:
st = torch.load(path, map_location=device)
except Exception as e:
print(f"[RESUME] checkpoint at {path} is unreadable: {e}")
return None
try:
_schema_check(st)
except Exception as e:
print(f"[RESUME] {e}")
return None
assert_config_hash(cfg, st) # raises ConfigDriftError on mismatch
model.load_state_dict(st["model"], strict=True)
if optimizer is not None and st.get("optimizer"):
optimizer.load_state_dict(st["optimizer"])
if scheduler is not None and st.get("scheduler"):
scheduler.load_state_dict(st["scheduler"])
if scaler is not None and st.get("scaler"):
scaler.load_state_dict(st["scaler"])
rng_restore(st["rng"])
cur_gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu"
if st.get("gpu_name") != cur_gpu:
msg = f"resumed on {cur_gpu}, started on {st.get('gpu_name')}"
print(f"[RESUME] WARNING: {msg}. Bit-exact continuity is void; "
f"the run remains scientifically valid.")
if status:
status.anomaly("gpu_change", msg)
if st.get("torch_version") != torch.__version__:
msg = f"torch {st.get('torch_version')} -> {torch.__version__}"
print(f"[RESUME] WARNING: {msg}")
if status:
status.anomaly("torch_version_change", msg)
print(f"[RESUME] epoch {st['epoch']} -> continuing at {st['epoch'] + 1}")
return st
def resume_continuity_check(history_csv, resumed_epoch: int,
status: Optional[RunStatus] = None) -> None:
"""Standing guard on every real resume.
A resume that restores weights but not RNG produces a perfectly smooth
loss curve, so smoothness alone proves nothing -- but a discontinuity
definitely proves something is wrong, and it must be surfaced rather than
absorbed.
"""
p = Path(history_csv)
if not p.exists():
return
try:
rows = list(csv.DictReader(open(p)))
losses = [float(r["train_loss"]) for r in rows if r.get("train_loss")]
except Exception:
return
if len(losses) < 12:
return
pre = losses[:resumed_epoch]
if len(pre) < 11 or resumed_epoch >= len(losses):
return
deltas = [abs(pre[i] - pre[i - 1]) for i in range(-10, 0)]
med = float(np.median(deltas)) if deltas else 0.0
jump = abs(losses[resumed_epoch] - pre[-1])
if med > 0 and jump > 5 * med:
msg = (f"resume jump {jump:.4f} vs median epoch delta {med:.4f} "
f"at epoch {resumed_epoch}")
if status:
status.anomaly("RESUME_ANOMALY", msg)
else:
print(f"[ANOMALY] {msg}")
else:
print(f"[RESUME] continuity OK (jump {jump:.4f}, median delta {med:.4f})")
# =============================================================================
# 10. train -- loop, signal handlers, accuracy gate
# =============================================================================
class Interrupt:
"""SIGTERM / SIGINT / atexit -> one immediate full push, then exit.
Kaggle sends SIGTERM before killing a session, and catching it buys enough
time for a final push. Do NOT rely on it: the grace period is short and a
hard kill gives no handlers at all. The 20-minute cadence and the per-epoch
local checkpoint are the real guarantee; this is the bonus path.
"""
def __init__(self, on_stop: Callable[[str], None]):
self.stop_requested = False
self.reason = None
self._fired = False
self._lock = threading.Lock()
self._on_stop = on_stop
for sig in (signal.SIGTERM, signal.SIGINT):
try:
signal.signal(sig, self._handle)
except Exception:
pass
atexit.register(self._atexit)
def _handle(self, signum, frame):
self.stop_requested = True
self.reason = f"signal_{signum}"
print(f"\n[SIGNAL] {signum} received -> flushing to HF and stopping")
self._fire(self.reason)
def _atexit(self):
self._fire("atexit")
def _fire(self, reason: str):
# Re-entrant safe: a second SIGTERM during the final push must not
# restart it.
with self._lock:
if self._fired:
return
self._fired = True
try:
self._on_stop(reason)
except BaseException as e:
print(f"[SIGNAL] final push failed: {e}")
@torch.no_grad()
def evaluate(model, loader, device, amp: bool = True) -> Dict[str, Any]:
model.eval()
correct = correct5 = total = 0
loss_sum = 0.0
for x, y, _ in loader:
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
with torch.autocast("cuda", enabled=amp and device.type == "cuda"):
logits = model(x)
loss_sum += float(F.cross_entropy(logits.float(), y, reduction="sum"))
top5 = logits.topk(min(5, logits.shape[1]), dim=1).indices
correct += int((top5[:, 0] == y).sum())
correct5 += int((top5 == y[:, None]).any(1).sum())
total += y.numel()
return {"top1": correct / max(total, 1), "top5": correct5 / max(total, 1),
"loss": loss_sum / max(total, 1), "n": total}
@torch.no_grad()
def el2n_and_preds(model, loader, device, amp: bool = True):
"""EL2N = ||softmax(f(x)) - onehot(y)||_2, the during-training variant.
NOT GraNd-at-init, which failed reproduction (arXiv 2303.14753). Also
returns per-sample correctness, which is what forgetting events count.
"""
model.eval()
el2n, correct, idxs = [], [], []
for x, y, si in loader:
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
with torch.autocast("cuda", enabled=amp and device.type == "cuda"):
logits = model(x)
p = F.softmax(logits.float(), dim=1)
oh = F.one_hot(y, p.shape[1]).float()
el2n.append(torch.linalg.vector_norm(p - oh, dim=1).cpu())
correct.append((p.argmax(1) == y).cpu())
idxs.append(si.clone() if torch.is_tensor(si) else torch.as_tensor(si))
return (torch.cat(el2n).numpy(), torch.cat(correct).numpy().astype(bool),
torch.cat(idxs).numpy())
def accuracy_gate(arch: str, top1_pct: float, gate_path,
smoke: bool = False) -> Dict[str, Any]:
"""Hard gate between training and the oracle sweep. It raises.
MSC computed from an undertrained model is meaningless, and discovering
that in week 3 is exactly what Phase 0 exists to prevent.
"""
published, halt, warn = ACCURACY_GATE[arch]
if smoke:
halt, warn = 0.5, 1.0 # code path still runs, threshold lowered
res = {"arch": arch, "top1_pct": float(top1_pct), "published": published,
"halt_below": halt, "warn_below": warn,
"margin_vs_published": float(top1_pct - published),
"passed": bool(top1_pct >= halt),
"warned": bool(top1_pct < warn), "smoke": smoke, "at": now_iso()}
atomic_write_json(gate_path, res)
if not res["passed"]:
raise RuntimeError(
f"ACCURACY GATE FAILED: {arch} reached {top1_pct:.2f}% "
f"(HALT below {halt}%, published {published}%). "
f"Fix the training recipe before generating any MSC table.")
if res["warned"]:
print(f"[GATE] WARNING: {arch} {top1_pct:.2f}% is below the "
f"{warn}% warn line (published {published}%)")
else:
print(f"[GATE] PASS: {arch} {top1_pct:.2f}% (published {published}%)")
return res
def append_history(path, row: Dict[str, Any]) -> None:
p = Path(path)
ensure_dir(p.parent)
new = not p.exists()
with open(p, "a", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(row))
if new:
w.writeheader()
w.writerow(row)
def train_backbone(cfg, model, loaders, device, paths, store_model, store_data,
sm: StageMachine, status: RunStatus,
interrupt: Optional[Interrupt] = None,
heartbeat_fn: Optional[Callable[[], None]] = None
) -> Dict[str, Any]:
"""The training loop. Checkpoints at epoch boundaries only.
Mid-epoch resumption would require dataloader worker state, which is not
reliably serialisable. Epochs are ~45 s, so the granularity is fine.
"""
sci, rt = cfg["science"], cfg["runtime"]
train_loader, train_eval_loader, test_loader = loaders
amp = bool(rt.get("amp", True)) and device.type == "cuda"
optimizer = torch.optim.SGD(model.parameters(), lr=sci["lr"],
momentum=sci["momentum"],
weight_decay=sci["weight_decay"], nesterov=False)
scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer, milestones=sci["milestones"], gamma=sci["gamma"])
scaler = torch.amp.GradScaler("cuda", enabled=amp)
start_epoch, best, step, wall0, joules0 = 0, 0.0, 0, 0.0, 0.0
st = load_checkpoint(paths["ckpt_last"], cfg, model, optimizer, scheduler,
scaler, device, status)
if st is None and store_model is not None:
p = store_model.download(f"runs/{sci['run_id']}/ckpt_last.pt",
paths["ckpt_last"])
if p is not None:
st = load_checkpoint(paths["ckpt_last"], cfg, model, optimizer,
scheduler, scaler, device, status)
if st is not None:
start_epoch = st["epoch"] + 1
best = st["best_metric"]
step = st["global_step"]
wall0 = st["wall_seconds"]
joules0 = st["energy_joules"]
resume_continuity_check(paths["history"], start_epoch, status)
energy = EnergyMonitor(paths["energy"])
energy.start(resume_joules=joules0)
t_start = time.time()
nan_streak = 0
el2n_scores = None
forget_counts = np.zeros(len(train_eval_loader.dataset), dtype=np.int32)
prev_correct = np.zeros(len(train_eval_loader.dataset), dtype=bool)
def _elapsed_h():
return (wall0 + (time.time() - t_start)) / 3600.0
gpu_ds = loaders[3] if len(loaders) > 3 else None
use_gpu_pipe = gpu_ds is not None
n_iter = (gpu_ds.n_batches(sci["batch_size"]) if use_gpu_pipe
else len(train_loader))
aug_gen = None
if use_gpu_pipe and device.type == "cuda":
aug_gen = torch.Generator(device=device)
aug_gen.manual_seed(derive_seed(sci["seed"], "gpu_aug"))
for epoch in range(start_epoch, sci["epochs"]):
model.train()
run_loss, seen = 0.0, 0
t_ep = time.time()
t_data = t_step = 0.0
# Toneva's forgetting events are counted from the predictions the
# forward pass ALREADY produces during training -- on the augmented
# sample, which is the original definition. The previous version ran a
# second full pass over all 50,000 training images every epoch to
# recompute them, which cost ~25-30% of every epoch and was less
# faithful, not more.
ep_correct = np.zeros(len(forget_counts), dtype=bool)
ep_seen = np.zeros(len(forget_counts), dtype=bool)
bar = make_progress(n_iter, f"ep {epoch:3d}/{sci['epochs']}",
enable=show_progress)
it = (gpu_ds.train_batches(sci["batch_size"], aug_gen) if use_gpu_pipe
else train_loader)
t_mark = time.time()
for batch in it:
x, y, si = batch
if not use_gpu_pipe:
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
t_data += time.time() - t_mark
t1 = time.time()
optimizer.zero_grad(set_to_none=True)
with torch.autocast("cuda", enabled=amp):
logits = model(x)
loss = F.cross_entropy(logits, y)
if not torch.isfinite(loss):
nan_streak += 1
if nan_streak > 20:
bar.close()
raise RuntimeError(
f"non-finite loss for {nan_streak} consecutive steps at "
f"epoch {epoch} (lr={optimizer.param_groups[0]['lr']}, "
f"scale={scaler.get_scale() if amp else 'n/a'}). "
f"Set runtime.amp=False and resume.")
t_mark = time.time()
continue
nan_streak = 0
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
with torch.no_grad():
ok = (logits.detach().argmax(1) == y)
si_np = (si.cpu().numpy() if torch.is_tensor(si)
else np.asarray(si))
ep_correct[si_np] = ok.cpu().numpy()
ep_seen[si_np] = True
bs = y.numel()
run_loss += float(loss) * bs
seen += bs
step += 1
t_step += time.time() - t1
bar.update(1)
if step % 20 == 0:
bar.set_postfix_str(f"loss {run_loss/max(seen,1):.3f}")
t_mark = time.time()
bar.close()
scheduler.step()
t_train = time.time() - t_ep
t1 = time.time()
ev = evaluate(model, test_loader, device, amp)
t_eval = time.time() - t1
train_loss = run_loss / max(seen, 1)
is_best = ev["top1"] > best
best = max(best, ev["top1"])
# forgetting = correct -> incorrect transition, counted only on samples
# actually visited this epoch
flips = prev_correct & ~ep_correct & ep_seen
forget_counts += flips.astype(np.int32)
prev_correct = np.where(ep_seen, ep_correct, prev_correct)
np.save(paths["forget"], forget_counts)
t1 = time.time()
if epoch == sci["el2n_epoch"]:
# EL2N needs the softmax vector, so this one extra pass is real --
# but it happens ONCE, at the configured epoch, not every epoch.
el2n_scores, _, el2n_idx = el2n_and_preds(model, train_eval_loader,
device, amp)
order = np.argsort(el2n_idx)
np.save(paths["el2n"], el2n_scores[order])
print(f" [EL2N] captured at epoch {epoch}")
t_extra = time.time() - t1
t1 = time.time()
save_checkpoint(paths["ckpt_last"], cfg, model, optimizer, scheduler,
scaler, epoch, step, best,
wall0 + time.time() - t_start, energy.joules)
if is_best:
shutil.copy2(paths["ckpt_last"], paths["ckpt_best"])
t_ckpt = time.time() - t1
t_total = time.time() - t_ep
eta_h = (sci["epochs"] - epoch - 1) * t_total / 3600.0
status.update(state="running", stage="train_backbone", epoch=epoch,
test_top1=ev["top1"], best=best)
if store_model is not None:
store_model.enqueue(paths["ckpt_last"],
f"runs/{sci['run_id']}/ckpt_last.pt")
if is_best:
store_model.enqueue(paths["ckpt_best"],
f"runs/{sci['run_id']}/ckpt_best.pt")
if store_data is not None:
for key, rp in (("history", "history.csv"),
("energy", "energy.csv")):
store_data.enqueue(paths[key], f"logs/{sci['run_id']}/{rp}")
append_history(paths["history"], {
"epoch": epoch, "train_loss": f"{train_loss:.6f}",
"test_top1": f"{ev['top1']:.6f}", "test_top5": f"{ev['top5']:.6f}",
"test_loss": f"{ev['loss']:.6f}",
"lr": f"{optimizer.param_groups[0]['lr']:.6f}",
"scaler_scale": f"{scaler.get_scale() if amp else 0:.1f}",
"energy_j": f"{energy.joules:.1f}",
"sec_total": f"{t_total:.2f}", "sec_data": f"{t_data:.2f}",
"sec_compute": f"{t_step:.2f}", "sec_eval": f"{t_eval:.2f}",
"sec_extra": f"{t_extra:.2f}", "sec_ckpt": f"{t_ckpt:.2f}",
"wall_s": f"{wall0 + time.time() - t_start:.1f}",
"time_utc": now_iso(),
})
print(f" ep {epoch:3d}/{sci['epochs']} loss {train_loss:.4f} "
f"top1 {ev['top1']*100:5.2f}% best {best*100:5.2f}% "
f"lr {optimizer.param_groups[0]['lr']:.4f} "
f"| {t_total:5.1f}s (data {t_data:4.1f} gpu {t_step:4.1f} "
f"eval {t_eval:4.1f} ckpt {t_ckpt:4.1f}) eta {eta_h:4.2f}h")
if epoch == start_epoch:
slow = "dataloader" if t_data > t_step else "gpu compute"
print(f" [TIMING] first epoch {t_total:.1f}s, dominated by {slow}. "
f"240 epochs -> ~{t_total*sci['epochs']/3600:.1f} h.")
if t_data > t_step and not use_gpu_pipe:
print(" [TIMING] set FAST_DATA=True to move augmentation onto "
"the GPU and remove the dataloader from the critical path.")
# Refresh the registry claim. A 3-hour run must not let its claim go
# stale (2 h) or another worker will legitimately take it over and two
# sessions will write the same checkpoint.
if heartbeat_fn is not None and epoch % 10 == 0:
heartbeat_fn()
if disk_free_mb(rt["work_dir"]) < 2048:
status.anomaly("disk_low", f"{disk_free_mb(rt['work_dir'])} MB free")
if interrupt is not None and interrupt.stop_requested:
status.update(state="paused", stage="train_backbone", epoch=epoch)
raise KeyboardInterrupt("stop requested")
if _elapsed_h() > float(rt.get("session_budget_h", 8.5)):
status.update(state="paused", stage="train_backbone", epoch=epoch)
raise KeyboardInterrupt("session budget exhausted -- relaunch to resume")
energy.stop()
return {"best": best, "epochs_done": sci["epochs"],
"wall_seconds": wall0 + time.time() - t_start,
"energy_joules": energy.joules,
"el2n": paths["el2n"], "forget": paths["forget"]}
# =============================================================================
# 11. sweeps -- the oracle
# =============================================================================
@torch.no_grad()
def sweep_depth(model, heads: Dict[int, nn.Module], cached: Dict[str, Any],
block_idx: Sequence[int], device) -> Dict[str, np.ndarray]:
"""Per-sample argmax / top1p / top2p at each depth configuration.
Exit K comes from the model's own classifier, applied to the cached pooled
features, so preds[:, -1] is genuinely y*.
"""
K = len(block_idx)
n = cached["labels"].numel()
preds = np.zeros((n, K), dtype=np.int64)
t1 = np.zeros((n, K), dtype=np.float32)
t2 = np.zeros((n, K), dtype=np.float32)
for j, k in enumerate(block_idx):
X = cached[f"feat_{k}"].to(device)
outs = []
for i in range(0, n, 1024):
xb = X[i:i + 1024]
logits = (model.fc(xb) if k == block_idx[-1] else heads[k](xb))
outs.append(F.softmax(logits.float(), dim=1).cpu())
p = torch.cat(outs)
top2 = p.topk(2, dim=1)
preds[:, j] = top2.indices[:, 0].numpy()
t1[:, j] = top2.values[:, 0].numpy()
t2[:, j] = top2.values[:, 1].numpy()
return {"preds": preds, "top1p": t1, "top2p": t2}
@torch.no_grad()
def sweep_resolution(model, loader, resolutions: Sequence[int], device,
mode: str = "native", amp: bool = True
) -> Dict[str, np.ndarray]:
"""mode='native' -- genuinely run at r, AdaptiveAvgPool2d handles the map.
mode='upsample' -- downsample to r then back to 32; network shape fixed.
Native is the primary realisation: the cost is the FLOPs actually spent
rather than a counterfactual. Upsample is stored alongside as a robustness
column with its cost explicitly labelled idealised.
"""
model.eval()
K = len(resolutions)
P, T1, T2, ACC = [], [], [], []
for j, r in enumerate(resolutions):
preds, t1, t2, corr, tot = [], [], [], 0, 0
for x, y, _ in loader:
x = x.to(device, non_blocking=True)
if r != 32:
xr = F.interpolate(x, size=(r, r), mode="bilinear",
align_corners=False)
if mode == "upsample":
xr = F.interpolate(xr, size=(32, 32), mode="bilinear",
align_corners=False)
else:
xr = x
with torch.autocast("cuda", enabled=amp and device.type == "cuda"):
logits = model(xr)
p = F.softmax(logits.float(), dim=1)
top2 = p.topk(2, dim=1)
preds.append(top2.indices[:, 0].cpu())
t1.append(top2.values[:, 0].cpu())
t2.append(top2.values[:, 1].cpu())
corr += int((top2.indices[:, 0].cpu() == y).sum())
tot += y.numel()
P.append(torch.cat(preds).numpy())
T1.append(torch.cat(t1).numpy())
T2.append(torch.cat(t2).numpy())
ACC.append(corr / max(tot, 1))
print(f" r={r:2d}px ({mode:8s}) acc {ACC[-1]*100:5.2f}%")
return {"preds": np.stack(P, 1), "top1p": np.stack(T1, 1).astype(np.float32),
"top2p": np.stack(T2, 1).astype(np.float32),
"accuracy": np.array(ACC)}
def resolution_degeneracy_gate(acc: np.ndarray, msc_r: np.ndarray) -> Dict[str, Any]:
"""This axis is not assumed to work.
A model trained only at 32px, evaluated natively at 16px, is generalising
to a spatial-statistics regime it never saw. If accuracy collapses toward
chance then almost every sample is 'insufficient' at low r, MSC_r saturates
at 1.0, and the axis carries no per-sample signal.
"""
vals, counts = np.unique(msc_r[np.isfinite(msc_r)], return_counts=True)
max_mass = float(counts.max() / counts.sum()) if counts.size else 1.0
res = {"acc_cheapest_pct": float(acc[0] * 100),
"max_level_mass": max_mass,
"criterion_1_acc_ge_25pct": bool(acc[0] >= 0.25),
"criterion_2_mass_le_70pct": bool(max_mass <= 0.70)}
res["informative"] = res["criterion_1_acc_ge_25pct"] and res["criterion_2_mass_le_70pct"]
if not res["informative"]:
print(f"[GATE] resolution axis DEGENERATE "
f"(acc@cheapest={res['acc_cheapest_pct']:.1f}%, "
f"max level mass={max_mass:.1%}). Excluded from the Q2 preview; "
f"Q1/Q3 gates are depth-axis quantities and are unaffected.")
return res
# =============================================================================
# 12. battery -- seven difficulty scores at full compute
# =============================================================================
@torch.no_grad()
def difficulty_battery(model, loader, device, block_idx, cached_train,
cached_eval, amp: bool = True) -> Dict[str, np.ndarray]:
"""msp, margin, entropy, ce_loss, plus prediction depth via k-NN probes.
el2n and forget_events are captured during training and merged by the
caller; they are only defined on training examples, and the test-set
variants are labelled *_testadapted.
NOTE ON PREDICTION DEPTH: it is the earliest layer after which every
subsequent k-NN prediction agrees with the final one -- the same suffix
closure as MSC, with k-NN probes instead of linear heads. It is therefore
near-circular with the depth axis, and Delta-R^2 must be reported with and
without it (see 00_RESEARCH_PROTOCOL.md section 3, Q4).
"""
model.eval()
msp, margin, entropy, ce = [], [], [], []
for x, y, _ in loader:
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
with torch.autocast("cuda", enabled=amp and device.type == "cuda"):
logits = model(x)
p = F.softmax(logits.float(), dim=1)
top2 = p.topk(2, dim=1).values
msp.append(top2[:, 0].cpu())
margin.append((top2[:, 0] - top2[:, 1]).cpu())
entropy.append((-(p * (p + 1e-12).log()).sum(1)).cpu())
ce.append(F.cross_entropy(logits.float(), y, reduction="none").cpu())
pd_ = _prediction_depth(cached_train, cached_eval, block_idx, device)
return {"msp": torch.cat(msp).numpy(),
"margin": torch.cat(margin).numpy(),
"entropy": torch.cat(entropy).numpy(),
"ce_loss": torch.cat(ce).numpy(),
"pred_depth": pd_}
def _prediction_depth(cached_train, cached_eval, block_idx, device,
k: int = 30, n_fit: int = 20000) -> np.ndarray:
"""k-NN probe at each depth; depth = first index after which all
subsequent probe predictions agree with the final one."""
y_tr = cached_train["labels"].numpy()
n_fit = min(n_fit, len(y_tr))
rng = np.random.default_rng(0)
sel = rng.choice(len(y_tr), n_fit, replace=False)
n_eval = cached_eval["labels"].numel()
K = len(block_idx)
knn = np.zeros((n_eval, K), dtype=np.int64)
for j, b in enumerate(block_idx):
A = cached_train[f"feat_{b}"][sel].to(device).float()
A = A / (A.norm(dim=1, keepdim=True) + 1e-8)
yb = torch.as_tensor(y_tr[sel], device=device)
B = cached_eval[f"feat_{b}"].to(device).float()
B = B / (B.norm(dim=1, keepdim=True) + 1e-8)
out = []
for i in range(0, n_eval, 512):
sim = B[i:i + 512] @ A.T
nn_idx = sim.topk(min(k, A.shape[0]), dim=1).indices
votes = yb[nn_idx]
out.append(torch.mode(votes, dim=1).values.cpu())
knn[:, j] = torch.cat(out).numpy()
final = knn[:, -1]
agree = knn == final[:, None]
suffix = np.ones_like(agree)
suffix[:, -1] = agree[:, -1]
for j in range(K - 2, -1, -1):
suffix[:, j] = agree[:, j] & suffix[:, j + 1]
return np.where(suffix.any(1), suffix.argmax(1), K - 1).astype(np.int64)
# =============================================================================
# 13. emit -- per-sample Parquet with the alignment assertions
# =============================================================================
def emit_parquet(path, sample_idx, labels, depth, res_native, res_upsample,
battery: Dict[str, np.ndarray], resolutions: Sequence[int],
probe_k: Optional[Dict[str, np.ndarray]] = None,
meta: Optional[Dict[str, Any]] = None) -> Path:
"""Row alignment is the single most dangerous bug in this project.
A misalignment destroys real correlations or manufactures fake ones, and
nothing downstream looks broken. Every assertion here halts.
"""
import pandas as pd
sample_idx = np.asarray(sample_idx)
n = len(sample_idx)
assert np.array_equal(sample_idx, np.arange(n)), (
f"sample_idx is not the canonical 0..{n-1} ordering. The evaluation "
f"loader must be shuffle=False, drop_last=False, sampler=None.")
for name, arr in (("labels", labels), ("depth.preds", depth["preds"]),
("res_native.preds", res_native["preds"])):
assert len(arr) == n, f"{name} has {len(arr)} rows, expected {n}"
df = {"sample_idx": sample_idx.astype(np.int32),
"label": np.asarray(labels).astype(np.int16)}
K = depth["preds"].shape[1]
for j in range(K):
df[f"pred_d{j+1}"] = depth["preds"][:, j].astype(np.int16)
df[f"top1p_d{j+1}"] = depth["top1p"][:, j].astype(np.float32)
df[f"top2p_d{j+1}"] = depth["top2p"][:, j].astype(np.float32)
for j, r in enumerate(resolutions):
df[f"pred_r{r}"] = res_native["preds"][:, j].astype(np.int16)
df[f"top1p_r{r}"] = res_native["top1p"][:, j].astype(np.float32)
df[f"top2p_r{r}"] = res_native["top2p"][:, j].astype(np.float32)
if res_upsample is not None:
df[f"pred_ru{r}"] = res_upsample["preds"][:, j].astype(np.int16)
df[f"top1p_ru{r}"] = res_upsample["top1p"][:, j].astype(np.float32)
df[f"top2p_ru{r}"] = res_upsample["top2p"][:, j].astype(np.float32)
for k, v in battery.items():
df[k] = np.asarray(v)
if probe_k is not None:
df["pred_probeK"] = probe_k["preds"].astype(np.int16)
df["top1p_probeK"] = probe_k["top1p"].astype(np.float32)
df["top2p_probeK"] = probe_k["top2p"].astype(np.float32)
out = pd.DataFrame(df)
assert out.isna().sum().sum() == 0, "NaNs in the per-sample table"
# Structural identity: the full-compute column IS the reference decision,
# so agreement with itself must be exact.
assert (out[f"pred_d{K}"].values == depth["preds"][:, -1]).all()
ensure_dir(Path(path).parent)
import pyarrow as pa
import pyarrow.parquet as pq
table = pa.Table.from_pandas(out, preserve_index=False)
if meta:
md = {k.encode(): json.dumps(v, default=str).encode()
for k, v in meta.items()}
table = table.replace_schema_metadata({**(table.schema.metadata or {}), **md})
pq.write_table(table, path, compression="zstd")
print(f"[EMIT] {path} ({len(out)} rows x {len(out.columns)} cols)")
return Path(path)
def execute_run(run_id: str, BOOT: Dict[str, Any], token: str,
store_model: HFStore, store_data: HFStore,
registry: Optional["Registry"] = None,
*, smoke: bool = False, amp: bool = True,
deterministic: bool = True,
force_config_override: bool = False,
fast_data: bool = True, show_progress: bool = True,
session_budget_h: float = 8.5,
interrupt: Optional[Interrupt] = None,
work_dir: str = "/kaggle/working",
scratch_dir: str = "/kaggle/temp") -> Dict[str, Any]:
"""Run ONE run_id end to end, stages 0-11, resuming wherever it left off.
Idiom borrowed from E2AM: the library does one unit of work, the notebook
loops over units. That is what makes the account count a free parameter --
one worker draining four runs sequentially and four workers doing one each
produce identical artifacts, because the runs share nothing.
Safe to call repeatedly. Completed stages are skipped after a hash check.
"""
from huggingface_hub import hf_hub_download
import yaml
run_rec = next((r for r in BOOT["runs"] if r["run_id"] == run_id), None)
if run_rec is None:
raise ValueError(f"{run_id} not in the manifest")
arch, seed = run_rec["arch"], run_rec["seed"]
sd = BOOT["science_defaults"]
cfg = build_config(
run_id, arch, seed,
epochs=sd["epochs"], batch_size=sd["batch_size"], lr=sd["lr"],
momentum=sd["momentum"], weight_decay=sd["weight_decay"],
milestones=sd["milestones"], gamma=sd["gamma"],
exit_fractions=sd["exit_fractions"], resolutions=sd["resolutions"],
taus=sd["taus"], head_seeds=sd["head_seeds"],
head_epochs=sd["head_epochs"], head_lr=sd["head_lr"],
train_seen_n=sd["train_seen_n"], el2n_epoch=sd["el2n_epoch"],
deterministic=deterministic, smoke=smoke)
if smoke:
cfg["science"].update(epochs=2, milestones=[1], el2n_epoch=1,
head_epochs=2)
cfg["runtime"].update(amp=amp, work_dir=work_dir, scratch_dir=scratch_dir,
session_budget_h=session_budget_h,
fast_data=fast_data, show_progress=show_progress,
force_config_override=force_config_override)
cfg_hash = config_hash(cfg)
seed_info = set_all_seeds(seed, deterministic=deterministic)
cfg["runtime"]["deterministic"] = seed_info["deterministic"]
TAG = "_smoke/" if smoke else ""
local = ensure_dir(Path(work_dir) / "msc" / run_id)
scratch = ensure_dir(Path(scratch_dir) / "msc" / run_id)
P = {
"ckpt_last": local / "ckpt_last.pt", "ckpt_best": local / "ckpt_best.pt",
"history": local / "history.csv", "energy": local / "energy.csv",
"state": local / "STATE.json", "status": local / "STATUS.json",
"env": local / "env.json", "gate": local / "gate.json",
"config": local / "config.yaml", "cfghash": local / "config_hash.txt",
"bbhash": local / "backbone_hash.json",
"acc_curves": local / "accuracy_curves.json",
"el2n": scratch / "el2n.npy", "forget": scratch / "forget.npy",
"exc": local / "exceptions.jsonl", "stdout": local / "stdout.log",
"test_pq": local / "test.parquet", "seen_pq": local / "train_seen.parquet",
}
RP_M = f"runs/{TAG}{run_id}"
RP_L = f"logs/{TAG}{run_id}"
sm = StageMachine(P["state"], store_data, f"{RP_M}/STATE.json")
sm.pull()
status = RunStatus(P["status"], store_model, f"{RP_M}/STATUS.json", run_id)
status.update(state="running", stage=sm.first_incomplete(),
config_hash=cfg_hash)
def hb():
if registry is not None:
registry.heartbeat(run_id)
def push_all(reason="manual"):
try:
status.data["state"] = "paused"
status.data["stop_reason"] = reason
atomic_write_json(P["status"], status.data)
for k, rp in (("ckpt_last", f"{RP_M}/ckpt_last.pt"),
("ckpt_best", f"{RP_M}/ckpt_best.pt"),
("status", f"{RP_M}/STATUS.json")):
store_model.enqueue(P[k], rp)
for k, rp in (("history", f"{RP_L}/history.csv"),
("energy", f"{RP_L}/energy.csv"),
("stdout", f"{RP_L}/stdout.log"),
("exc", f"{RP_L}/exceptions.jsonl"),
("env", f"{RP_L}/env.json"),
("gate", f"{RP_L}/gate.json"),
("bbhash", f"{RP_L}/backbone_hash.json"),
("acc_curves", f"{RP_L}/accuracy_curves.json"),
("state", f"{RP_M}/STATE.json"),
("config", f"{RP_M}/config.yaml"),
("cfghash", f"{RP_M}/config_hash.txt")):
store_data.enqueue(P[k], rp)
store_model.flush(120)
store_data.flush(120)
print(f"[PUSH] full push complete ({reason})")
except BaseException as e:
print(f"[PUSH] final push error ({reason}): {e}")
print("=" * 74)
print(f">>> {run_id} arch={arch} seed={seed} "
f"resume at stage: {sm.first_incomplete()}")
print("=" * 74)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# ---- stage 0: environment ------------------------------------------
if not sm.done("env_capture"):
atomic_write_json(P["env"], hardware_report())
atomic_write_text(P["config"], yaml.safe_dump(cfg, sort_keys=True))
atomic_write_text(P["cfghash"], cfg_hash)
store_data.enqueue(P["env"], f"{RP_L}/env.json")
store_data.enqueue(P["config"], f"{RP_M}/config.yaml")
store_data.enqueue(P["cfghash"], f"{RP_M}/config_hash.txt")
sm.mark("env_capture")
# ---- stage 1: dataset ----------------------------------------------
data_root = sm.state.get("notes", {}).get("data_root")
if not sm.done("dataset") or not data_root:
data_root = locate_cifar("cifar100", scratch_dir)
fp = dataset_fingerprint(data_root)
assert fp == BOOT["dataset_fingerprint"], (
f"DATASET FINGERPRINT MISMATCH for {run_id}.\n"
f" bootstrap: {BOOT['dataset_fingerprint']}\n here: {fp}\n"
f"This run saw different data than NB00. Row alignment across runs "
f"would be void.")
sm.note("data_root", data_root)
sm.mark("dataset")
print("[DATA] fingerprint matches bootstrap")
# ---- stage 2: model + budgets ---------------------------------------
model = build_model(arch, 100).to(device)
block_idx = exit_block_indices(model, cfg["science"]["exit_fractions"])
BUD = json.loads(Path(hf_hub_download(
BOOT["repo_data"], f"budgets/{arch}.json", repo_type="dataset",
token=token)).read_text())
assert BUD["depth_block_idx"] == block_idx, \
"budgets/{arch}.json disagrees with the model's exit indices"
if not sm.done("budgets"):
sm.mark("budgets")
loaders = build_loaders(cfg, data_root, device=device,
fast_gpu=cfg["runtime"].get("fast_data", True))
train_loader, train_eval_loader, test_loader, _gpu_ds = loaders
# ---- stage 3: train --------------------------------------------------
if not sm.done("train_backbone"):
status.update(stage="train_backbone")
try:
summary = train_backbone(cfg, model, loaders, device, P,
store_model, store_data, sm, status,
interrupt, heartbeat_fn=hb,
show_progress=cfg["runtime"].get(
"show_progress", True))
sm.mark("train_backbone", best=str(summary["best"]))
except KeyboardInterrupt:
push_all("interrupt")
raise
except Exception as e:
log_exception(P["exc"], "train_backbone",
status.data.get("epoch", -1), e)
push_all("exception")
raise
else:
print("[SKIP] train_backbone already complete")
if not P["ckpt_last"].exists():
store_model.download(f"{RP_M}/ckpt_last.pt", P["ckpt_last"])
load_checkpoint(P["ckpt_last"], cfg, model, None, None, None,
device, status)
hb()
# ---- stage 4: accuracy gate -----------------------------------------
ev = evaluate(model, test_loader, device, cfg["runtime"]["amp"])
gate = accuracy_gate(arch, ev["top1"] * 100, P["gate"], smoke=smoke)
store_data.enqueue(P["gate"], f"{RP_L}/gate.json")
if not sm.done("accuracy_gate"):
sm.mark("accuracy_gate", top1=str(gate["top1_pct"]))
# ---- stages 5-6: freeze, cache, heads --------------------------------
model.eval()
for p_ in model.parameters():
p_.requires_grad_(False)
bb_before = backbone_hash(model)
f_tr, f_te = scratch / "feat_train.pt", scratch / "feat_test.pt"
if not (f_tr.exists() and f_te.exists()):
cached_train = cache_pooled_features(model, train_eval_loader,
block_idx, device, f_tr)
cached_test = cache_pooled_features(model, test_loader, block_idx,
device, f_te)
else:
cached_train, cached_test = torch.load(f_tr), torch.load(f_te)
if not sm.done("cache_features"):
sm.mark("cache_features")
heads = {}
for hs in cfg["science"]["head_seeds"]:
heads[hs] = train_exit_heads(cached_train, cached_test, block_idx, 100,
head_seed=hs,
epochs=cfg["science"]["head_epochs"],
lr=cfg["science"]["head_lr"], device=device)
hp = local / f"exit_heads_s{hs}.pt"
torch.save({k: v.state_dict() for k, v in heads[hs].items()}, hp)
store_model.enqueue(hp, f"{RP_M}/exit_heads_s{hs}.pt")
print(f" head seed {hs}: {len(heads[hs])} probes")
bb_after = backbone_hash(model)
assert bb_after == bb_before, (
"BACKBONE MOVED during head training. Each exit is now reading a "
"different network and the 'same model under reduced compute' "
"interpretation collapses.")
atomic_write_json(P["bbhash"], {"before": bb_before, "after": bb_after,
"unchanged": True})
store_data.enqueue(P["bbhash"], f"{RP_L}/backbone_hash.json")
if not sm.done("train_heads"):
sm.mark("train_heads")
print("[FREEZE] backbone verified unchanged (params + buffers)")
hb()
# ---- stages 7-9: sweeps + battery ------------------------------------
depth_sw = sweep_depth(model, heads[cfg["science"]["head_seeds"][0]],
cached_test, block_idx, device)
for hs in cfg["science"]["head_seeds"][1:]:
d = sweep_depth(model, heads[hs], cached_test, block_idx, device)
for nm, arr in (("preds", d["preds"]), ("t1", d["top1p"]),
("t2", d["top2p"])):
np.save(scratch / f"depth_{nm}_s{hs}.npy", arr)
if not sm.done("sweep_depth"):
sm.mark("sweep_depth")
RES = cfg["science"]["resolutions"]
print("[SWEEP] resolution (native = PRIMARY):")
res_nat = sweep_resolution(model, test_loader, RES, device, "native",
cfg["runtime"]["amp"])
print("[SWEEP] resolution (downsample-upsample = robustness):")
res_up = sweep_resolution(model, test_loader, RES, device, "upsample",
cfg["runtime"]["amp"])
labels_np = cached_test["labels"].numpy()
depth_acc = [float((depth_sw["preds"][:, j] == labels_np).mean())
for j in range(len(block_idx))]
atomic_write_json(P["acc_curves"], {
"depth": depth_acc, "resolution_native": res_nat["accuracy"].tolist(),
"resolution_upsample": res_up["accuracy"].tolist(),
"resolutions": list(RES)})
store_data.enqueue(P["acc_curves"], f"{RP_L}/accuracy_curves.json")
assert abs(depth_acc[-1] - ev["top1"]) < 5e-4, (
f"exit K accuracy {depth_acc[-1]:.4f} != backbone {ev['top1']:.4f}. "
f"Exit K must BE the model's own classifier.")
if not sm.done("sweep_resolution"):
sm.mark("sweep_resolution")
print(f"[SWEEP] depth accuracies: {[f'{a*100:.2f}%' for a in depth_acc]}")
battery = difficulty_battery(model, test_loader, device, block_idx,
cached_train, cached_test, cfg["runtime"]["amp"])
el2n_te, corr_te, _ = el2n_and_preds(model, test_loader, device,
cfg["runtime"]["amp"])
battery["el2n"] = el2n_te
battery["forget_events"] = (~corr_te).astype(np.int32)
if not sm.done("difficulty_battery"):
sm.mark("difficulty_battery")
# ---- stage 10: parquet -----------------------------------------------
meta = {"run_id": run_id, "arch": arch, "seed": seed,
"config_hash": cfg_hash, "lib_version": __version__,
"dataset_fingerprint": BOOT["dataset_fingerprint"],
"rho_depth": BUD["rho_depth"],
"rho_resolution": BUD["rho_resolution"],
"deterministic": cfg["runtime"]["deterministic"],
"resolution_primary": "native",
"head_seed_for_depth_cols": cfg["science"]["head_seeds"][0]}
emit_parquet(P["test_pq"], cached_test["sample_idx"].numpy(), labels_np,
depth_sw, res_nat, res_up, battery, RES, meta=meta)
store_data.enqueue(P["test_pq"], f"per_sample/{TAG}{run_id}/test.parquet")
if not sm.done("emit_parquet"):
sm.mark("emit_parquet")
print("[GATE] resolution degeneracy:",
json.dumps(resolution_degeneracy_gate(res_nat["accuracy"],
np.array([0.0]))))
# ---- stage 11: finalise ----------------------------------------------
push_all("finalise")
status.update(state="done", stage="finalise")
store_model.flush(300)
store_data.flush(300)
assert_inventory(run_id, arch, store_model, store_data, tag=TAG)
sm.mark("finalise", complete="true")
if registry is not None:
# In smoke mode the registry is namespaced to "_smoke/", so this marks
# the rehearsal done, never the real run.
registry.complete(run_id, {"top1_pct": gate["top1_pct"],
"config_hash": cfg_hash, "smoke": smoke})
print(f"<<< {run_id} COMPLETE top1={gate['top1_pct']:.2f}%\n")
return {"run_id": run_id, "top1_pct": gate["top1_pct"],
"depth_acc": depth_acc, "gate": gate}
ARTIFACT_INVENTORY = [
("config.yaml", "data", "runs/{tag}{run}/config.yaml"),
("config_hash.txt", "data", "runs/{tag}{run}/config_hash.txt"),
("env.json", "data", "logs/{tag}{run}/env.json"),
("budgets.json", "data", "budgets/{arch}.json"),
("ckpt_last.pt", "model", "runs/{tag}{run}/ckpt_last.pt"),
("history.csv", "data", "logs/{tag}{run}/history.csv"),
("energy.csv", "data", "logs/{tag}{run}/energy.csv"),
("gate.json", "data", "logs/{tag}{run}/gate.json"),
("backbone_hash.json", "data", "logs/{tag}{run}/backbone_hash.json"),
("accuracy_curves.json", "data", "logs/{tag}{run}/accuracy_curves.json"),
("test.parquet", "data", "per_sample/{tag}{run}/test.parquet"),
("STATE.json", "data", "runs/{tag}{run}/STATE.json"),
("STATUS.json", "model", "runs/{tag}{run}/STATUS.json"),
("stdout.log", "data", "logs/{tag}{run}/stdout.log"),
]
def assert_inventory(run_id: str, arch: str, store_model: HFStore,
store_data: HFStore, tag: str = "") -> Dict[str, Any]:
"""We train once. The check that nothing was silently skipped has to be
mechanical, so `finalise` refuses to mark a run done without it."""
files = {"model": store_model.list_files(), "data": store_data.list_files()}
missing = []
for name, repo, tmpl in ARTIFACT_INVENTORY:
p = tmpl.format(run=run_id, arch=arch, tag=tag)
if p not in files[repo]:
missing.append(f"{repo}:{p}")
res = {"run_id": run_id, "checked": len(ARTIFACT_INVENTORY),
"missing": missing, "complete": not missing, "at": now_iso()}
if missing:
raise RuntimeError(
f"ARTIFACT INVENTORY INCOMPLETE for {run_id}. Missing:\n " +
"\n ".join(missing) +
"\nThe run is NOT done. Re-run the stage that produces each.")
print(f"[INVENTORY] all {len(ARTIFACT_INVENTORY)} artifacts present for {run_id}")
return res