Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,14 @@ once with `python scripts/pack_dataset.py` (4.7 GB) and upload it to `MyDrive/aa
```bash
python scripts/download_data.py # ~1 h, resumable; --sources/--limit for subsets
python scripts/download_models.py # ~3.5 GB into the HF cache
# + our fine-tuned runs (~1 GB) into $AAI521_DATA_ROOT/checkpoints (D14)
python scripts/smoke_models.py # zero-shot sanity check -> outputs/smoke/
python scripts/curate_and_split.py # quality features, filters, group splits
python scripts/pack_dataset.py # one tar for Google Drive / Colab

python scripts/train.py --config configs/train/denoise.yaml # also: super_resolution, colorize, inpaint
python scripts/train.py --config configs/train/denoise.yaml --max-steps 150 --train-limit 64 --val-limit 16 --run-name smoke # quick sanity run
python scripts/upload_checkpoints.py --dry-run # after retraining: push runs to the team HF repo (D14)
python scripts/evaluate.py # test split -> outputs/eval/<task>.csv
python scripts/evaluate.py --limit 8 --inpaint-limit 8 --examples 8 --out-dir $AAI521_DATA_ROOT/outputs/eval_examples

Expand Down
8 changes: 8 additions & 0 deletions configs/models.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,11 @@ models:
allow_patterns: ["big-lama.pt"]
role: comparison
notes: Big-LaMa TorchScript (Fourier convolutions); strong non-diffusion inpainting baseline.

# Our fine-tuned weights (decision D14): one Hub model repo with one folder per training
# run, mirroring $AAI521_DATA_ROOT/checkpoints/<run_name>/. Upload with
# scripts/upload_checkpoints.py; download_models.py fetches them into place.
# Pin `revision` to a commit hash before reporting final numbers so results are reproducible.
finetuned:
repo_id: aai521-group3/aai521-restoration-checkpoints
revision: cef1c8776ee3d68f02691e147cb538e7b5aadeb3
27 changes: 27 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,30 @@ copied to `MyDrive/aai521/outputs/`:

Rerun `evaluate.py` and copy the CSV again once the fine-tuned checkpoints exist. BOPBtL
does not need to rerun as long as the seed and limit are unchanged.

## D14 — Host fine-tuned checkpoints on the Hugging Face Hub (2026-12-01)

**Problem.** Fine-tuned weights lived only on the machine that trained them, so the web
app and `evaluate.py` silently fell back to pretrained weights for everyone else, and a
grader cloning the repo could not reproduce the fine-tuned rows. The weights (~1 GB,
mostly DDColor-L's 870 MB) are too large for git.

**Decision.** One public HF model repo for the team (`finetuned.repo_id` in
`configs/models.yaml`) with one folder per training run, mirroring
`$AAI521_DATA_ROOT/checkpoints/<run_name>/`.

* `scripts/upload_checkpoints.py` pushes `best.safetensors` (or `best_lora/` for the SD 1.5
LoRA), `config.json`, `metrics.csv` and `summary.json` per run, plus a generated model
card, as one commit. `last_state.pt` (optimiser state, 2.7 GB for DDColor-L) is resume-only
and never uploaded.
* `scripts/download_models.py` now also fetches those folders into the checkpoint root
(`--no-finetuned` to skip). The pipeline's existing `<run_name>/best.safetensors` lookup
is unchanged, so no loader code moved.
* **Swapping a model** (e.g. a better inpainting LoRA): retrain, then
`upload_checkpoints.py --tasks inpaint -m "..."`. Only that run's files change.
* **Reproducibility.** The upload prints the commit hash; set `finetuned.revision` to it
before reporting final numbers so later uploads cannot change reported results.

Run folder names come from `configs/train/<task>.yaml` (`config.train_run_names()`), the
same source the pipeline uses. Each set of weights inherits its base model's license
(listed in the model card).
34 changes: 28 additions & 6 deletions scripts/download_models.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
"""Download the pretrained checkpoints listed in ``configs/models.yaml`` to the HF cache.
"""Download the checkpoints listed in ``configs/models.yaml``.

Pretrained models go to the HF cache. Our fine-tuned runs (``finetuned:``, decision D14)
are written into ``$AAI521_DATA_ROOT/checkpoints/<run_name>/``, where the pipeline,
web app and ``evaluate.py`` pick them up automatically.

Usage:
python scripts/download_models.py # all models
python scripts/download_models.py # all models + fine-tuned runs
python scripts/download_models.py --models colorize super_resolution
python scripts/download_models.py --no-finetuned # pretrained only
python scripts/download_models.py --models --finetuned # fine-tuned runs only
"""

from __future__ import annotations
Expand All @@ -11,18 +17,25 @@
import logging
import sys

from restoration.config import load_models_config, logs_dir
from restoration.models.registry import fetch_model
from restoration.config import checkpoint_root, load_models_config, logs_dir, train_run_names
from restoration.models.registry import fetch_finetuned, fetch_model
from restoration.utils.logging import setup_logging

logger = logging.getLogger("download_models")


def main(argv: list[str] | None = None) -> int:
"""Download requested models; returns a process exit code."""
registry = load_models_config().models
config = load_models_config()
registry = config.models
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--models", nargs="+", choices=sorted(registry), default=list(registry))
parser.add_argument("--models", nargs="*", choices=sorted(registry), default=list(registry))
parser.add_argument(
"--finetuned",
action=argparse.BooleanOptionalAction,
default=True,
help="also fetch our fine-tuned runs into the checkpoint root (default: on)",
)
args = parser.parse_args(argv)
setup_logging(logs_dir(), "download_models")

Expand All @@ -33,6 +46,15 @@ def main(argv: list[str] | None = None) -> int:
except Exception: # keep going so one gated/missing repo doesn't block the rest
logger.exception("Model %s failed", name)
failed.append(name)
if args.finetuned:
if config.finetuned is None or config.finetuned.repo_id.startswith("HF_ORG/"):
logger.warning("No finetuned.repo_id in configs/models.yaml; using pretrained only")
else:
try:
fetch_finetuned(config.finetuned, train_run_names(), checkpoint_root())
except Exception:
logger.exception("Fine-tuned checkpoints failed")
failed.append("finetuned")
if failed:
logger.error("Failed models: %s", ", ".join(failed))
return 1
Expand Down
28 changes: 25 additions & 3 deletions scripts/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
python scripts/evaluate.py # all tasks + end-to-end
python scripts/evaluate.py --tasks denoise super_resolution --limit 100
python scripts/evaluate.py --tasks denoise_inpaint --inpaint-limit 100 # vs BOPBtL (D13)
python scripts/evaluate.py --tasks denoise_inpaint --methods fine-tuned # add rows only
# qualitative PNGs only (same first images as the full run, so rows match its CSVs):
python scripts/evaluate.py --limit 8 --inpaint-limit 8 --examples 8 --out-dir <dir>
"""
Expand Down Expand Up @@ -275,6 +276,13 @@ def main(argv: list[str] | None = None) -> int:
"--examples", type=int, default=0, help="predictions per method saved as PNGs"
)
parser.add_argument("--out-dir", type=Path, help="default: $AAI521_DATA_ROOT/outputs/eval")
parser.add_argument(
"--methods",
nargs="+",
help="denoise_inpaint only: run just the methods whose name contains one of these "
"strings (e.g. 'fine-tuned') and merge them into the existing CSV, replacing rows "
"for the same methods and keeping the rest",
)
args = parser.parse_args(argv)
setup_logging(logs_dir(), "evaluate")
seed_everything(args.seed)
Expand Down Expand Up @@ -318,13 +326,27 @@ def main(argv: list[str] | None = None) -> int:
import pandas as pd

items = denoise_inpaint.build_items(args.inpaint_limit, args.seed)
frames = []
for name, factory in denoise_inpaint_methods(
methods = denoise_inpaint_methods(
device, args.inpaint_steps, items, args.seed, args.inpaint_limit
).items():
)
if args.methods:
methods = {
name: f for name, f in methods.items() if any(m in name for m in args.methods)
}
if not methods:
raise SystemExit(f"No denoise_inpaint method matches {args.methods}")
frames = []
for name, factory in methods.items():
frames.append(harness.evaluate_task(task, items, {name: factory()}, device))
free()
frame = pd.concat(frames, ignore_index=True)
existing = out_dir / f"{task}.csv"
if args.methods and existing.exists():
# Partial rerun: keep earlier rows (same seed and items) for other methods.
old = pd.read_csv(existing)
old = old[~old["method"].isin(frame["method"].unique())]
frame = pd.concat([old, frame], ignore_index=True)
logger.info("Merged %d new rows into %s", len(frame) - len(old), existing)
else:
items = end_to_end_items(args.inpaint_limit, args.seed)
import pandas as pd
Expand Down
149 changes: 149 additions & 0 deletions scripts/upload_checkpoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""Upload our fine-tuned checkpoints to the team's Hugging Face repo (decision D14).

Pushes ``<checkpoint_root>/<run_name>/`` for every task (weights, config, metrics,
summary; never ``last_state.pt``) plus a generated model card, as a single commit.
Re-running after retraining one model replaces just that run's files, so a better
inpainting LoRA can be swapped in without touching the others.

Requires a write token: run ``hf auth login`` once.

Usage:
python scripts/upload_checkpoints.py --dry-run # list what would be pushed
python scripts/upload_checkpoints.py # all four runs
python scripts/upload_checkpoints.py --tasks inpaint -m "LoRA v2 (rank 16)"
"""

from __future__ import annotations

import argparse
import json
import logging
import sys
from pathlib import Path

from huggingface_hub import CommitOperationAdd, HfApi

from restoration.config import checkpoint_root, load_models_config, logs_dir, train_run_names
from restoration.models.registry import finetuned_patterns
from restoration.utils.logging import setup_logging

logger = logging.getLogger("upload_checkpoints")


def collect_files(root: Path, run_names: dict[str, str]) -> list[Path]:
"""Local files to upload, relative to ``root``.

Raises:
FileNotFoundError: If a selected run has no weights locally.
"""
files: list[Path] = []
for task, run in run_names.items():
found = sorted(
p.relative_to(root)
for pattern in finetuned_patterns(task, run)
for p in root.glob(pattern)
if p.is_file()
)
if not any(p.suffix == ".safetensors" for p in found):
raise FileNotFoundError(f"{task}: no weights under {root / run}")
files.extend(found)
return files


def model_card(root: Path, run_names: dict[str, str]) -> str:
"""Markdown model card summarising each run from its ``summary.json``.

Each task's base model is the registry entry of the same name (``configs/models.yaml``).
"""
registry = load_models_config().models
bases = [registry[task].repo_id for task in run_names]
rows = []
for task, run in run_names.items():
summary_path = root / run / "summary.json"
summary = json.loads(summary_path.read_text()) if summary_path.exists() else {}
metric = next(((k, v) for k, v in summary.items() if k.startswith("best_")), None)
score = f"{metric[0][5:].upper()} {metric[1]:.4g}" if metric else "n/a"
base = registry[task].repo_id
rows.append(
f"| {task} | `{run}/` | [{base}](https://huggingface.co/{base}) "
f"| {summary.get('steps', 'n/a')} | {score} |"
)
base_yaml = "\n".join(f" - {b}" for b in bases)
table = "\n".join(rows)
return f"""---
license: other
base_model:
{base_yaml}
tags:
- image-restoration
- old-photo-restoration
---

# AAI-521 Group 3: fine-tuned restoration checkpoints

Fine-tuned weights for the four-stage historical-photo restoration pipeline in
[NolanRobbins/AAI-521-Final-Project](https://github.com/NolanRobbins/AAI-521-Final-Project)
(University of San Diego, AAI-521 Applied Computer Vision). Each model was fine-tuned on
synthetically degraded Library of Congress FSA/OWI color (1939-1944) and DOCUMERICA
(1972-1977) photographs.

| Task | Folder | Base model | Steps | Best validation score |
|---|---|---|---|---|
{table}

`scripts/download_models.py` places these folders under `$AAI521_DATA_ROOT/checkpoints/`,
where the pipeline loads them automatically. Each folder holds the best checkpoint
(`best.safetensors`, or `best_lora/` for the SD 1.5 inpainting LoRA), the training config,
and the per-step validation metrics.

**License.** Each set of weights is a derivative of its base model and is distributed
under that model's license; see the linked model cards.
"""


def main(argv: list[str] | None = None) -> int:
"""Upload the selected runs; returns a process exit code."""
spec = load_models_config().finetuned
all_runs = train_run_names()
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo-id", default=spec.repo_id if spec else None)
parser.add_argument("--tasks", nargs="+", choices=sorted(all_runs), default=list(all_runs))
parser.add_argument("-m", "--message", default="Upload fine-tuned checkpoints")
parser.add_argument("--private", action="store_true", help="create the repo as private")
parser.add_argument("--dry-run", action="store_true", help="list files, push nothing")
args = parser.parse_args(argv)
setup_logging(logs_dir(), "upload_checkpoints")

if not args.repo_id or args.repo_id.startswith("HF_ORG/"):
parser.error("set finetuned.repo_id in configs/models.yaml (or pass --repo-id)")

root = checkpoint_root()
run_names = {t: all_runs[t] for t in args.tasks}
files = collect_files(root, run_names)
total_mb = sum((root / f).stat().st_size for f in files) / 2**20
for f in files:
logger.info("%8.1f MB %s", (root / f).stat().st_size / 2**20, f.as_posix())
logger.info("%d files, %.1f MB -> %s", len(files), total_mb, args.repo_id)
if args.dry_run:
return 0

api = HfApi()
api.create_repo(args.repo_id, repo_type="model", private=args.private, exist_ok=True)
# The card always describes all four runs, even when only one is being replaced.
card = model_card(root, all_runs).encode("utf-8")
ops = [
CommitOperationAdd(path_in_repo=f.as_posix(), path_or_fileobj=str(root / f)) for f in files
]
ops.append(CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=card))
commit = api.create_commit(
repo_id=args.repo_id, repo_type="model", operations=ops, commit_message=args.message
)
logger.info("Pushed %s", commit.commit_url)
logger.info(
"To pin this version, set finetuned.revision: %s in configs/models.yaml", commit.oid
)
return 0


if __name__ == "__main__":
sys.exit(main())
24 changes: 24 additions & 0 deletions src/restoration/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,22 @@ class ModelSpec(_Base):
notes: str = ""


class FinetunedSpec(_Base):
"""Our fine-tuned weights on the Hugging Face Hub (decision D14).

One model repo holds one folder per training run, mirroring
``<checkpoint_root>/<run_name>/`` so a download drops straight into place.
"""

repo_id: str
revision: str | None = None


class ModelsConfig(_Base):
"""Top-level model registry (``configs/models.yaml``)."""

models: dict[str, ModelSpec]
finetuned: FinetunedSpec | None = None


def _read_yaml(path: Path) -> dict[str, Any]:
Expand All @@ -184,3 +196,15 @@ def load_data_config(path: Path = CONFIG_DIR / "data.yaml") -> DataConfig:
def load_models_config(path: Path = CONFIG_DIR / "models.yaml") -> ModelsConfig:
"""Load and validate the model registry."""
return ModelsConfig.model_validate(_read_yaml(path))


def train_run_names(train_dir: Path = CONFIG_DIR / "train") -> dict[str, str]:
"""Map each task to its run directory name from ``configs/train/<task>.yaml``.

Fine-tuned weights live at ``<checkpoint_root>/<run_name>/``; this is the single
source for those names outside the pipeline (upload and download scripts).
"""
names: dict[str, str] = {}
for path in sorted(train_dir.glob("*.yaml")):
names[path.stem] = str(_read_yaml(path)["run_name"])
return names
Loading