File size: 36,900 Bytes
addddc4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 | """Supervised TinyCNN training from materialized voxel caches."""
from __future__ import annotations
import hashlib
import json
import random
import time
from pathlib import Path
from typing import Any
import numpy as np
import torch
from numpy.lib.npyio import NpzFile
from torch import nn
from torch.utils.data import DataLoader, Dataset
from e_jepa_ttc.artifacts.protocol import get_current_protocol_identity
from e_jepa_ttc.data.ml_cache import validate_voxel_cache
from e_jepa_ttc.evaluation.bootstrap import sequence_bootstrap_interval
from e_jepa_ttc.evaluation.metrics import regression_metrics
from e_jepa_ttc.models import build_regressor
from e_jepa_ttc.reproducibility import (
cuda_device_count,
cuda_device_name,
cuda_is_usable,
resolve_device,
seed_torch_cpu,
)
from e_jepa_ttc.training.checkpoints import checkpoint_provenance
from e_jepa_ttc.utils.io import ensure_parent, write_structured
def _hash_file(filepath: str | Path) -> str:
h = hashlib.sha256()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(8192 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def _get_git_commit() -> str:
import subprocess
try:
return subprocess.check_output(["git", "rev-parse", "HEAD"]).decode("ascii").strip()
except Exception:
return "unknown"
class VoxelCacheDataset(Dataset[tuple[torch.Tensor, torch.Tensor]]):
"""Dataset backed by arrays from an `.npz` voxel cache."""
def __init__(self, x: np.ndarray, y_log_ttc: np.ndarray, indices: np.ndarray) -> None:
self.x = x
self.y_log_ttc = y_log_ttc
self.indices = indices.astype(np.int64)
def __len__(self) -> int:
return int(self.indices.shape[0])
def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
real_idx = int(self.indices[idx])
x = torch.from_numpy(self.x[real_idx].astype(np.float32, copy=False))
y = torch.tensor(self.y_log_ttc[real_idx], dtype=torch.float32)
return x, y
def _set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
seed_torch_cpu(seed)
if cuda_is_usable():
torch.cuda.manual_seed_all(seed)
def _split_indices(split: np.ndarray, name: str) -> np.ndarray:
return np.flatnonzero(split.astype(str) == name).astype(np.int64)
def _split_indices_any(split: np.ndarray, names: tuple[str, ...]) -> np.ndarray:
split_text = split.astype(str)
mask = np.isin(split_text, np.array(names, dtype=str))
return np.flatnonzero(mask).astype(np.int64)
def _available_split_names(split: np.ndarray) -> set[str]:
return set(split.astype(str).tolist())
def _evaluate_model(
model: nn.Module,
dataset: VoxelCacheDataset,
*,
device: torch.device,
batch_size: int,
num_workers: int = 0,
) -> tuple[np.ndarray, np.ndarray, float]:
loader_kwargs: dict[str, Any] = {
"batch_size": batch_size,
"shuffle": False,
"num_workers": num_workers,
"pin_memory": device.type == "cuda",
}
if num_workers > 0:
loader_kwargs.update(persistent_workers=True, prefetch_factor=2)
loader = DataLoader(dataset, **loader_kwargs)
predictions: list[np.ndarray] = []
targets: list[np.ndarray] = []
start = time.perf_counter()
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device=device, non_blocking=True)
pred_log = model(x).detach().cpu().numpy()
predictions.append(np.exp(pred_log))
targets.append(np.exp(y.numpy()))
elapsed = time.perf_counter() - start
if not predictions:
return np.empty(0), np.empty(0), elapsed
return np.concatenate(targets), np.concatenate(predictions), elapsed
def _prediction_metadata(
cache: NpzFile,
indices: np.ndarray,
) -> dict[str, np.ndarray]:
"""Return sample-level identity arrays aligned with saved predictions."""
metadata: dict[str, np.ndarray] = {
"global_index": indices.astype(np.int64, copy=False),
}
optional_fields = (
"sequence_id",
"timestamp_us",
"context_start_us",
"context_end_us",
)
for field in optional_fields:
if field in cache.files:
metadata[field] = np.asarray(cache[field])[indices]
return metadata
def _sequence_macro_mae(
y_true: np.ndarray,
y_pred: np.ndarray,
sequence_ids: np.ndarray | None,
) -> float:
"""Return sequence-macro MAE, falling back to sample-micro MAE."""
if sequence_ids is None:
return float(np.mean(np.abs(y_true - y_pred)))
sequence_text = np.asarray(sequence_ids).astype(str)
values = [
float(
np.mean(
np.abs(y_true[sequence_text == sequence_id] - y_pred[sequence_text == sequence_id])
)
)
for sequence_id in np.unique(sequence_text)
]
return float(np.mean(values))
def _atomic_torch_save(payload: dict[str, Any], path: Path) -> None:
"""Write a checkpoint atomically so interruption cannot corrupt the previous state."""
temporary_path = path.with_suffix(path.suffix + ".tmp")
torch.save(payload, temporary_path)
temporary_path.replace(path)
def _split_evaluation(
*,
y_true: np.ndarray,
y_pred: np.ndarray,
seconds: float,
metadata: dict[str, np.ndarray],
) -> dict[str, Any]:
"""Build aggregate and sequence-aware metrics for one evaluation split."""
payload: dict[str, Any] = {
"count": int(y_true.shape[0]),
"metrics": regression_metrics(y_true, y_pred),
"seconds": seconds,
}
sequence_ids = metadata.get("sequence_id")
if sequence_ids is None:
payload["sequence_metrics_status"] = "unavailable_missing_sequence_id"
return payload
sequence_text = sequence_ids.astype(str)
per_sequence: dict[str, Any] = {}
for sequence_id in np.unique(sequence_text):
selected = sequence_text == sequence_id
per_sequence[str(sequence_id)] = {
"count": int(np.sum(selected)),
"metrics": regression_metrics(y_true[selected], y_pred[selected]),
}
payload["sequence_count"] = len(per_sequence)
payload["per_sequence"] = per_sequence
payload["mae_sequence_bootstrap_95"] = sequence_bootstrap_interval(
y_true,
y_pred,
sequence_text,
iterations=2000,
confidence=0.95,
seed=0,
)
return payload
def _save_prediction_artifact(
path: Path,
*,
evaluation_splits: tuple[str, ...],
predictions: dict[str, np.ndarray],
targets: dict[str, np.ndarray],
metadata: dict[str, dict[str, np.ndarray]],
) -> None:
"""Save predictions together with the identities required for clustered analysis."""
arrays: dict[str, np.ndarray] = {}
for split_name in evaluation_splits:
arrays[f"{split_name}_pred"] = predictions[split_name].astype(np.float32, copy=False)
arrays[f"{split_name}_true"] = targets[split_name].astype(np.float32, copy=False)
for field, values in metadata[split_name].items():
arrays[f"{split_name}_{field}"] = np.asarray(values)
np.savez(ensure_parent(path), **arrays)
def _train_one_epoch(
model: nn.Module,
loader: DataLoader[tuple[torch.Tensor, torch.Tensor]],
optimizer: torch.optim.Optimizer,
loss_fn: nn.Module,
*,
device: torch.device,
scaler: torch.amp.GradScaler | None,
) -> float:
model.train()
losses: list[float] = []
use_amp = scaler is not None and device.type == "cuda"
for x, y in loader:
x = x.to(device=device, non_blocking=True)
y = y.to(device=device, non_blocking=True)
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=use_amp):
pred = model(x)
loss = loss_fn(pred, y)
if scaler is None:
loss.backward()
optimizer.step()
else:
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optimizer)
scaler.update()
losses.append(float(loss.detach().cpu()))
return float(np.mean(losses)) if losses else float("nan")
def _load_pretrained_encoder(
model: nn.Module,
checkpoint_path: str | Path,
*,
device: torch.device,
expected_model_name: str,
) -> dict[str, Any]:
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
state = checkpoint.get("encoder_state_dict")
if state is None:
msg = f"Checkpoint {checkpoint_path} does not contain encoder_state_dict."
raise ValueError(msg)
source_model_name = checkpoint.get("model_name", "tiny-cnn")
if source_model_name != expected_model_name:
msg = (
f"Checkpoint encoder is {source_model_name!r}, but training model is "
f"{expected_model_name!r}."
)
raise ValueError(msg)
model.encoder.load_state_dict(state)
return {
**checkpoint_provenance(checkpoint_path, checkpoint),
"source_model": checkpoint.get("model"),
"source_model_name": source_model_name,
}
def train_tiny_cnn(
*,
cache_path: str | Path,
output_dir: str | Path,
epochs: int = 80,
batch_size: int = 64,
learning_rate: float = 3e-4,
weight_decay: float = 1e-3,
seed: int = 42,
device_name: str = "auto",
pretrained_encoder_path: str | Path | None = None,
freeze_encoder: bool = False,
train_fraction: float = 1.0,
subset_manifest_path: str | Path | None = None,
model_name: str = "tiny-cnn",
navigation_mode: str = "enabled",
evaluation_splits: tuple[str, ...] = ("train", "validation", "test"),
train_splits: tuple[str, ...] = ("train",),
validation_splits: tuple[str, ...] = ("validation",),
num_workers: int = 0,
early_stopping_patience: int = 8,
early_stopping_min_epochs: int = 12,
early_stopping_min_delta_relative: float = 0.003,
resume: bool = False,
dry_run_fingerprint: bool = False,
) -> dict[str, Any] | str:
"""Train a supervised TTC model on a materialized voxel cache."""
_set_seed(seed)
if not 0.0 < train_fraction <= 1.0:
msg = "train_fraction must be in (0, 1]."
raise ValueError(msg)
if navigation_mode not in ("enabled", "disabled"):
raise ValueError("navigation_mode must be 'enabled' or 'disabled'")
if not evaluation_splits:
msg = "evaluation_splits must contain at least one split."
raise ValueError(msg)
if not train_splits:
msg = "train_splits must contain at least one split."
raise ValueError(msg)
if not validation_splits:
msg = "validation_splits must contain at least one split."
raise ValueError(msg)
if num_workers < 0:
raise ValueError("num_workers must be non-negative.")
if early_stopping_patience < 0:
raise ValueError("early_stopping_patience must be non-negative.")
if early_stopping_min_epochs <= 0:
raise ValueError("early_stopping_min_epochs must be positive.")
if early_stopping_min_delta_relative < 0.0:
raise ValueError("early_stopping_min_delta_relative must be non-negative.")
cache = np.load(cache_path, allow_pickle=False)
validate_voxel_cache(cache)
x = cache["x"]
if navigation_mode == "disabled":
if bool(cache.get("navigation_channels", False)):
nav_count = len(cache["navigation_feature_names"])
x[:, -nav_count:, :, :] = 0.0
y_ttc = cache["y_ttc"].astype(np.float32)
split = cache["split"].astype(str)
y_log = np.log(np.clip(y_ttc, 1e-4, None)).astype(np.float32)
available_splits = _available_split_names(split)
missing_names = sorted(
(set(train_splits) | set(validation_splits) | set(evaluation_splits)) - available_splits
)
if missing_names:
msg = f"Requested split names are missing from cache: {missing_names}."
raise ValueError(msg)
train_idx = _split_indices_any(split, train_splits)
val_idx = _split_indices_any(split, validation_splits)
split_indices = {
split_name: _split_indices(split, split_name) for split_name in available_splits
}
if train_idx.size == 0 or val_idx.size == 0:
msg = "Requested train and validation splits must be non-empty."
raise ValueError(msg)
missing_eval_splits = [
split_name for split_name in evaluation_splits if split_indices[split_name].size == 0
]
if missing_eval_splits:
msg = f"Requested evaluation splits are empty: {missing_eval_splits}."
raise ValueError(msg)
full_train_count = int(train_idx.size)
subset_sha256 = ""
if subset_manifest_path is not None and Path(subset_manifest_path).exists():
manifest_path = Path(subset_manifest_path)
with manifest_path.open("r", encoding="utf-8") as f:
manifest_data = json.load(f)
unsigned_manifest = dict(manifest_data)
declared_subset_sha256 = unsigned_manifest.pop("sha256", None)
canonical_manifest = json.dumps(
unsigned_manifest,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
).encode("utf-8")
computed_subset_sha256 = hashlib.sha256(canonical_manifest).hexdigest()
if declared_subset_sha256 != computed_subset_sha256:
raise ValueError(
f"Subset manifest signature mismatch: {manifest_path}. "
"Regenerate it rather than editing indices by hand."
)
requested_train_idx = np.array(manifest_data["global_indices"], dtype=np.int64)
if requested_train_idx.ndim != 1 or requested_train_idx.size == 0:
raise ValueError("Subset manifest global_indices must be a non-empty vector.")
if np.unique(requested_train_idx).size != requested_train_idx.size:
raise ValueError("Subset manifest contains duplicate global indices.")
if not np.isin(requested_train_idx, train_idx).all():
raise ValueError("Subset manifest contains indices outside the requested train split.")
train_idx = np.sort(requested_train_idx)
if "sequence_id" in cache:
declared_sequences = np.asarray(manifest_data.get("sequence_ids", [])).astype(str)
actual_sequences = cache["sequence_id"][train_idx].astype(str)
if not np.array_equal(declared_sequences, actual_sequences):
raise ValueError("Subset manifest sequence_ids do not match cache indices.")
subset_sha256 = computed_subset_sha256
print(f"Loaded subset manifest from {manifest_path} with {train_idx.size} samples.")
elif train_fraction < 1.0:
rng = np.random.default_rng(seed)
if "sequence_id" in cache:
seqs = cache["sequence_id"][train_idx]
unique_seqs = np.sort(np.unique(seqs))
subset_idx = []
for seq in unique_seqs:
seq_idx = train_idx[seqs == seq]
shuffled = rng.permutation(seq_idx)
subset_count = max(1, int(round(seq_idx.size * train_fraction)))
subset_idx.append(shuffled[:subset_count])
train_idx = np.sort(np.concatenate(subset_idx)).astype(np.int64)
else:
shuffled = rng.permutation(train_idx)
subset_count = max(1, int(round(train_idx.size * train_fraction)))
train_idx = np.sort(shuffled[:subset_count]).astype(np.int64)
if subset_manifest_path is not None:
manifest_path = Path(subset_manifest_path)
ensure_parent(manifest_path)
payload = {
"global_indices": train_idx.tolist(),
"sequence_ids": (
cache["sequence_id"][train_idx].astype(str).tolist()
if "sequence_id" in cache
else []
),
"ttc_bins": [], # Could compute bins here if needed
"source_split_hash": "",
"seed": seed,
"requested_fraction": train_fraction,
"effective_fraction": float(train_idx.size / full_train_count),
}
payload_bytes = json.dumps(
payload,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
).encode("utf-8")
subset_sha256 = hashlib.sha256(payload_bytes).hexdigest()
payload["sha256"] = subset_sha256
with manifest_path.open("w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
print(f"Saved subset manifest to {manifest_path}")
commit = _get_git_commit()
cache_sha256 = _hash_file(cache_path)
split_manifest_sha256 = (
str(cache["split_manifest_sha256"]) if "split_manifest_sha256" in cache else ""
)
device = resolve_device(device_name)
model_tag = model_name.replace("-", "_")
train_dataset = VoxelCacheDataset(x, y_log, train_idx)
val_dataset = VoxelCacheDataset(x, y_log, val_idx)
datasets = {
split_name: VoxelCacheDataset(x, y_log, indices)
for split_name, indices in split_indices.items()
}
datasets["__train_selection__"] = train_dataset
datasets["__validation_selection__"] = val_dataset
train_loader_kwargs: dict[str, Any] = {
"batch_size": batch_size,
"shuffle": True,
"num_workers": num_workers,
"pin_memory": device.type == "cuda",
}
if num_workers > 0:
train_loader_kwargs.update(persistent_workers=True, prefetch_factor=2)
train_loader = DataLoader(train_dataset, **train_loader_kwargs)
model = build_regressor(model_name, in_channels=int(x.shape[1])).to(device)
pretrained_encoder: dict[str, Any] | None = None
if pretrained_encoder_path is not None:
pretrained_encoder = _load_pretrained_encoder(
model,
pretrained_encoder_path,
device=device,
expected_model_name=model_name,
)
run_fingerprint_payload = {
"git_commit": commit,
"protocol_version": get_current_protocol_identity()[0],
"protocol_sha256": get_current_protocol_identity()[1],
"cache_sha256": cache_sha256,
"split_manifest_sha256": split_manifest_sha256,
"subset_manifest_sha256": subset_sha256,
"model_name": model_name,
"resolved_model_config": {
"in_channels": int(x.shape[1]),
"width": getattr(model, "width", 48) if hasattr(model, "width") else 48,
},
"navigation_mode": navigation_mode,
"label_fraction": train_fraction,
"seed": seed,
"batch_size": batch_size,
"freeze_encoder": freeze_encoder,
"train_splits": list(train_splits),
"validation_splits": list(validation_splits),
"evaluation_splits": list(evaluation_splits),
"pretraining_checkpoint_sha256": pretrained_encoder.get("checkpoint_sha256", "")
if pretrained_encoder
else "",
"optimizer_config": {"learning_rate": learning_rate, "weight_decay": weight_decay},
"training_steps": epochs,
"num_workers": num_workers,
"early_stopping": {
"patience": early_stopping_patience,
"min_epochs": early_stopping_min_epochs,
"min_delta_relative": early_stopping_min_delta_relative,
"monitor": "validation_sequence_macro_mae",
},
}
run_fingerprint = hashlib.sha256(
json.dumps(run_fingerprint_payload, sort_keys=True).encode("utf-8")
).hexdigest()
if dry_run_fingerprint:
return run_fingerprint
if freeze_encoder:
for param in model.encoder.parameters():
param.requires_grad_(False)
trainable_parameters = [param for param in model.parameters() if param.requires_grad]
if not trainable_parameters:
msg = "No trainable parameters remain after applying freeze settings."
raise ValueError(msg)
optimizer = torch.optim.AdamW(trainable_parameters, lr=learning_rate, weight_decay=weight_decay)
loss_fn = nn.SmoothL1Loss(beta=0.25)
scaler = torch.amp.GradScaler("cuda") if device.type == "cuda" else None
output = Path(output_dir)
output.mkdir(parents=True, exist_ok=True)
best_path = output / "tiny_cnn_best.pt"
last_path = output / "tiny_cnn_last.pt"
resume_path = output / "resume.pt"
metrics_path = output / "metrics.json"
history_path = output / "history.jsonl"
best_val_mae = float("inf")
best_epoch = -1
epochs_without_improvement = 0
start_epoch = 1
completed_epoch = 0
stopped_early = False
history: list[dict[str, Any]] = []
start_time = time.perf_counter()
resolved_model_config = {
"in_channels": int(x.shape[1]),
"width": getattr(model, "width", 48) if hasattr(model, "width") else 48,
}
def checkpoint_payload(
*,
epoch: int,
role: str,
selected_by: str,
) -> dict[str, Any]:
return {
"model_state_dict": model.state_dict(),
"model_name": model_name,
"epoch": epoch,
"checkpoint_role": role,
"checkpoint_selected_by": selected_by,
"cache_path": str(cache_path),
"seed": seed,
"pretrained_encoder": pretrained_encoder,
"in_channels": int(x.shape[1]),
"cache_sha256": cache_sha256,
"split_manifest_sha256": split_manifest_sha256,
"subset_manifest_sha256": subset_sha256,
"navigation_mode": navigation_mode,
"label_fraction": train_fraction,
"protocol_version": get_current_protocol_identity()[0],
"protocol_sha256": get_current_protocol_identity()[1],
"git_commit": commit,
"resolved_model_config": resolved_model_config,
"run_fingerprint": run_fingerprint,
"run_fingerprint_payload": run_fingerprint_payload,
}
if resume:
if not resume_path.is_file():
raise FileNotFoundError(f"Resume checkpoint does not exist: {resume_path}")
resume_state = torch.load(resume_path, map_location=device, weights_only=False)
if resume_state.get("run_fingerprint") != run_fingerprint:
raise ValueError(
"Resume fingerprint differs from the current data/config/code fingerprint."
)
model.load_state_dict(resume_state["model_state_dict"])
optimizer.load_state_dict(resume_state["optimizer_state_dict"])
if scaler is not None and resume_state.get("scaler_state_dict") is not None:
scaler.load_state_dict(resume_state["scaler_state_dict"])
completed_epoch = int(resume_state["epoch"])
start_epoch = completed_epoch + 1
best_val_mae = float(resume_state["best_validation_sequence_macro_mae"])
best_epoch = int(resume_state["best_epoch"])
epochs_without_improvement = int(resume_state["epochs_without_improvement"])
rng_state = resume_state["rng_state"]
random.setstate(rng_state["python"])
np.random.set_state(rng_state["numpy"])
torch.set_rng_state(rng_state["torch"])
if device.type == "cuda" and rng_state.get("cuda"):
torch.cuda.set_rng_state_all(rng_state["cuda"])
if history_path.is_file():
history = [
json.loads(line)
for line in history_path.read_text(encoding="utf-8").splitlines()
if line.strip()
]
elif resume_path.exists():
raise FileExistsError(
f"{resume_path} already exists. Pass resume=True or choose a new output directory."
)
history_mode = "a" if resume else "w"
with history_path.open(history_mode, encoding="utf-8") as history_file:
for epoch in range(start_epoch, epochs + 1):
train_loss = _train_one_epoch(
model,
train_loader,
optimizer,
loss_fn,
device=device,
scaler=scaler,
)
val_true, val_pred, val_seconds = _evaluate_model(
model,
val_dataset,
device=device,
batch_size=batch_size,
num_workers=num_workers,
)
val_metrics = regression_metrics(val_true, val_pred)
validation_sequence_ids = (
np.asarray(cache["sequence_id"])[val_idx] if "sequence_id" in cache.files else None
)
validation_sequence_macro_mae = _sequence_macro_mae(
val_true,
val_pred,
validation_sequence_ids,
)
row = {
"epoch": epoch,
"train_loss": train_loss,
"validation": val_metrics,
"validation_sequence_macro_mae": validation_sequence_macro_mae,
"validation_seconds": val_seconds,
}
history.append(row)
history_file.write(json.dumps(row, sort_keys=True) + "\n")
history_file.flush()
improvement_threshold = (
best_val_mae * (1.0 - early_stopping_min_delta_relative)
if np.isfinite(best_val_mae)
else float("inf")
)
if validation_sequence_macro_mae < improvement_threshold:
best_val_mae = validation_sequence_macro_mae
best_epoch = epoch
epochs_without_improvement = 0
_atomic_torch_save(
checkpoint_payload(
epoch=epoch,
role="best",
selected_by="validation_sequence_macro_mae",
),
best_path,
)
else:
epochs_without_improvement += 1
completed_epoch = epoch
resume_payload = checkpoint_payload(
epoch=epoch,
role="resume",
selected_by="latest_completed_epoch",
)
resume_payload.update(
{
"optimizer_state_dict": optimizer.state_dict(),
"scaler_state_dict": scaler.state_dict() if scaler is not None else None,
"best_validation_sequence_macro_mae": best_val_mae,
"best_epoch": best_epoch,
"epochs_without_improvement": epochs_without_improvement,
"rng_state": {
"python": random.getstate(),
"numpy": np.random.get_state(),
"torch": torch.get_rng_state(),
"cuda": torch.cuda.get_rng_state_all() if device.type == "cuda" else [],
},
}
)
_atomic_torch_save(resume_payload, resume_path)
if (
early_stopping_patience > 0
and epoch >= early_stopping_min_epochs
and epochs_without_improvement >= early_stopping_patience
):
stopped_early = True
break
_atomic_torch_save(
checkpoint_payload(
epoch=completed_epoch,
role="last",
selected_by="early_stopping" if stopped_early else "final_epoch",
),
last_path,
)
checkpoint = torch.load(best_path, map_location=device, weights_only=False)
model.load_state_dict(checkpoint["model_state_dict"])
split_results: dict[str, Any] = {}
predictions: dict[str, np.ndarray] = {}
targets: dict[str, np.ndarray] = {}
prediction_metadata: dict[str, dict[str, np.ndarray]] = {}
for split_name in evaluation_splits:
dataset = datasets[split_name]
y_true, y_pred, seconds = _evaluate_model(
model,
dataset,
device=device,
batch_size=batch_size,
num_workers=num_workers,
)
metadata = _prediction_metadata(cache, split_indices[split_name])
split_results[split_name] = _split_evaluation(
y_true=y_true,
y_pred=y_pred,
seconds=seconds,
metadata=metadata,
)
predictions[split_name] = y_pred
targets[split_name] = y_true
prediction_metadata[split_name] = metadata
predictions_path = output / "predictions.npz"
summary: dict[str, Any] = {
"model": f"{model_tag}_voxel_supervised",
"model_name": model_name,
"cache": str(cache_path),
"output_dir": output.as_posix(),
"device": str(device),
"torch_version": torch.__version__,
"cuda_available": cuda_is_usable(),
"cuda_device_count": cuda_device_count(),
"gpu_name": cuda_device_name(device),
"seed": seed,
"downstream_seed": seed,
"pretrain_seed": (
pretrained_encoder.get("source_seed") if pretrained_encoder is not None else None
),
"epochs": epochs,
"epochs_completed": completed_epoch,
"stopped_early": stopped_early,
"batch_size": batch_size,
"num_workers": num_workers,
"learning_rate": learning_rate,
"weight_decay": weight_decay,
"early_stopping": {
"monitor": "validation_sequence_macro_mae",
"patience": early_stopping_patience,
"min_epochs": early_stopping_min_epochs,
"min_delta_relative": early_stopping_min_delta_relative,
"best_value": best_val_mae,
},
"resume_checkpoint": resume_path.as_posix(),
"pretrained_encoder": pretrained_encoder,
"freeze_encoder": freeze_encoder,
"train_fraction": train_fraction,
"train_splits": list(train_splits),
"validation_splits": list(validation_splits),
"evaluation_splits": list(evaluation_splits),
"full_train_count": full_train_count,
"effective_train_count": int(train_idx.size),
"best_epoch": best_epoch,
"best_checkpoint": best_path.as_posix(),
"last_checkpoint": last_path.as_posix(),
"elapsed_seconds": time.perf_counter() - start_time,
"splits": split_results,
"cache_sha256": cache_sha256,
"split_manifest_sha256": split_manifest_sha256,
"subset_manifest_sha256": subset_sha256,
"navigation_mode": navigation_mode,
"protocol_version": get_current_protocol_identity()[0],
"protocol_sha256": get_current_protocol_identity()[1],
"git_commit": commit,
"run_fingerprint": run_fingerprint,
"run_fingerprint_payload": run_fingerprint_payload,
"final_test_opened": False,
"predictions_path": predictions_path.as_posix(),
"prediction_identity_fields": sorted(
{field for split_metadata in prediction_metadata.values() for field in split_metadata}
),
}
_save_prediction_artifact(
predictions_path,
evaluation_splits=evaluation_splits,
predictions=predictions,
targets=targets,
metadata=prediction_metadata,
)
write_structured(metrics_path, summary)
return summary
def evaluate_supervised_checkpoint(
*,
cache_path: str | Path,
checkpoint_path: str | Path,
output_path: str | Path | None = None,
batch_size: int = 64,
device_name: str = "auto",
evaluation_splits: tuple[str, ...] = ("validation",),
model_name: str | None = None,
allow_final_test_evaluation: bool = False,
) -> dict[str, Any]:
"""Evaluate a saved supervised TTC checkpoint without retraining."""
if not evaluation_splits:
msg = "evaluation_splits must contain at least one split."
raise ValueError(msg)
if not allow_final_test_evaluation and any(
"test" in s or "CPLA-high" in s for s in evaluation_splits
):
raise ValueError(
"Evaluation on test or CPLA-high splits requires allow_final_test_evaluation=True."
)
if batch_size <= 0:
msg = "batch_size must be positive."
raise ValueError(msg)
cache = np.load(cache_path, allow_pickle=False)
validate_voxel_cache(cache)
x = cache["x"]
y_ttc = cache["y_ttc"].astype(np.float32)
split = cache["split"].astype(str)
y_log = np.log(np.clip(y_ttc, 1e-4, None)).astype(np.float32)
available_splits = _available_split_names(split)
missing_names = sorted(set(evaluation_splits) - available_splits)
if missing_names:
msg = f"Requested split names are missing from cache: {missing_names}."
raise ValueError(msg)
split_indices = {
split_name: _split_indices(split, split_name) for split_name in available_splits
}
missing_eval_splits = [
split_name for split_name in evaluation_splits if split_indices[split_name].size == 0
]
if missing_eval_splits:
msg = f"Requested evaluation splits are empty: {missing_eval_splits}."
raise ValueError(msg)
device = resolve_device(device_name)
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
checkpoint_model_name = str(checkpoint.get("model_name", "tiny-cnn"))
selected_model_name = model_name or checkpoint_model_name
if selected_model_name != checkpoint_model_name:
msg = (
f"Checkpoint model is {checkpoint_model_name!r}, but evaluation model is "
f"{selected_model_name!r}."
)
raise ValueError(msg)
model = build_regressor(selected_model_name, in_channels=int(x.shape[1])).to(device)
state = checkpoint.get("model_state_dict")
if state is None:
msg = f"Checkpoint {checkpoint_path} does not contain model_state_dict."
raise ValueError(msg)
model.load_state_dict(state)
split_results: dict[str, Any] = {}
predictions: dict[str, np.ndarray] = {}
targets: dict[str, np.ndarray] = {}
prediction_metadata: dict[str, dict[str, np.ndarray]] = {}
for split_name in evaluation_splits:
dataset = VoxelCacheDataset(x, y_log, split_indices[split_name])
y_true, y_pred, seconds = _evaluate_model(
model,
dataset,
device=device,
batch_size=batch_size,
)
metadata = _prediction_metadata(cache, split_indices[split_name])
split_results[split_name] = _split_evaluation(
y_true=y_true,
y_pred=y_pred,
seconds=seconds,
metadata=metadata,
)
predictions[split_name] = y_pred
targets[split_name] = y_true
prediction_metadata[split_name] = metadata
summary: dict[str, Any] = {
"checkpoint": Path(checkpoint_path).as_posix(),
"checkpoint_epoch": checkpoint.get("epoch"),
"checkpoint_seed": checkpoint.get("seed"),
"downstream_seed": checkpoint.get("seed"),
"pretrained_encoder": checkpoint.get("pretrained_encoder"),
"pretrain_seed": (
checkpoint.get("pretrained_encoder", {}).get("source_seed")
if isinstance(checkpoint.get("pretrained_encoder"), dict)
else None
),
"checkpoint_role": checkpoint.get("checkpoint_role"),
"checkpoint_selected_by": checkpoint.get("checkpoint_selected_by"),
"checkpoint_cache": checkpoint.get("cache_path"),
"cache": str(cache_path),
"device": str(device),
"torch_version": torch.__version__,
"cuda_available": cuda_is_usable(),
"cuda_device_count": cuda_device_count(),
"gpu_name": cuda_device_name(device),
"model_name": selected_model_name,
"batch_size": batch_size,
"evaluation_splits": list(evaluation_splits),
"splits": split_results,
"final_test_opened": allow_final_test_evaluation,
"prediction_identity_fields": sorted(
{field for split_metadata in prediction_metadata.values() for field in split_metadata}
),
}
if output_path is not None:
output = ensure_parent(output_path)
predictions_path = output.with_suffix(".predictions.npz")
summary["predictions_path"] = predictions_path.as_posix()
_save_prediction_artifact(
predictions_path,
evaluation_splits=evaluation_splits,
predictions=predictions,
targets=targets,
metadata=prediction_metadata,
)
write_structured(output, summary)
return summary
|