Download binding_clip/train.py from Kiriti-Ray/binding-clip: direct link, hf CLI and curl.
- Browser
- Download file 9.73 kB
-
https://huggingface.co/Kiriti-Ray/binding-clip/resolve/main/binding_clip/train.py
- Command line
-
hf download hf://Kiriti-Ray/binding-clip/binding_clip/train.py
-
curl -L -o train.py https://huggingface.co/Kiriti-Ray/binding-clip/resolve/main/binding_clip/train.py
9.73 kB
| """Train the global, unary, and ordered-pair variants on CLEVR-CoGenT.""" | |
| import argparse | |
| import json | |
| import math | |
| from pathlib import Path | |
| import platform | |
| import time | |
| import numpy as np | |
| import torch | |
| from torch.nn import functional as F | |
| from torch.utils.data import DataLoader | |
| from .data import CoGenT | |
| from .factorized import attribute_loss | |
| from .model import Config, MODES, build_model, load_model, save_model | |
| from .vision import center_weights | |
| def resolve_device(name): | |
| if name == "auto": | |
| if torch.backends.mps.is_available(): | |
| return "mps" | |
| if torch.cuda.is_available(): | |
| return "cuda" | |
| return "cpu" | |
| if name == "mps" and not torch.backends.mps.is_available(): | |
| raise RuntimeError("MPS unavailable. Run from a Metal-enabled terminal or select --device cpu.") | |
| return name | |
| def set_seed(seed): | |
| torch.manual_seed(seed) | |
| torch.set_num_threads(4) | |
| def bootstrap_clustered(values, cluster): | |
| groups, inverse = np.unique(cluster, return_inverse=True) | |
| if not groups.size: | |
| return None | |
| counts = np.bincount(inverse) | |
| outcomes = np.bincount(inverse, weights=values) | |
| rng = np.random.default_rng(65) | |
| means = [] | |
| for _ in range(1000): | |
| selections = rng.integers(len(groups), size=len(groups)) | |
| means.append(outcomes[selections].sum() / counts[selections].sum()) | |
| return { | |
| "accuracy": float(outcomes.sum() / counts.sum()), | |
| "ci95": np.quantile(means, [0.025, 0.975]).tolist(), | |
| "comparisons": int(len(values)), | |
| "scenes": int(len(groups)), | |
| } | |
| def evaluate(model, loader, device, confidence=False, return_examples=False): | |
| model.eval() | |
| correctness = [] | |
| cross_shapes = [] | |
| scene_ids = [] | |
| distances = [] | |
| for images, captions, centers, cross_shape, scene_id in loader: | |
| scores, affinities = model(images.to(device), captions.to(device)) | |
| correctness.append((scores[:, :1] > scores[:, 1:]).cpu()) | |
| cross_shapes.append(cross_shape) | |
| scene_ids.append(scene_id) | |
| if affinities is not None: | |
| predicted = model.coordinates[affinities[:, 0].argmax(dim=-1)].cpu() | |
| distances.append((predicted - centers).norm(dim=-1)) | |
| correct = torch.cat(correctness).numpy() | |
| cross = torch.cat(cross_shapes).numpy() | |
| scenes = torch.cat(scene_ids).numpy() | |
| metrics = {} | |
| for name, values in { | |
| "color_swap": correct[:, 0], | |
| "spatial_flip": correct[:, 1], | |
| "joint": correct.all(axis=1), | |
| }.items(): | |
| metrics[name] = float(values.mean()) | |
| if confidence: | |
| metrics[f"{name}_ci"] = bootstrap_clustered(values, scenes) | |
| metrics[f"{name}_cross_shape"] = bootstrap_clustered(values[cross], scenes[cross]) | |
| if distances: | |
| radii = torch.cat(distances) | |
| metrics["point_error"] = radii.mean().item() | |
| metrics["point_accuracy_at_0.12"] = (radii <= 0.12).float().mean().item() | |
| metrics["comparisons"] = len(correct) | |
| metrics["scenes"] = len(np.unique(scenes)) | |
| if return_examples: | |
| return metrics, (correct, cross, scenes) | |
| return metrics | |
| def localization_loss(model, affinities, centers): | |
| soft_targets = center_weights(centers, model.coordinates) | |
| return -(soft_targets * affinities[:, 0].log_softmax(dim=-1)).sum(dim=-1).mean() | |
| def train_one(config, args, train, val_a, device, val_b=None): | |
| set_seed(args.seed) | |
| model = build_model(config).to(device) | |
| optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.04) | |
| generator = torch.Generator().manual_seed(args.seed) | |
| batches = DataLoader(train, batch_size=args.batch_size, shuffle=True, generator=generator) | |
| development = DataLoader(val_a, batch_size=args.batch_size) | |
| total_steps = len(batches) * args.epochs | |
| warmup = max(1, int(total_steps * 0.05)) | |
| def schedule(step): | |
| if step < warmup: | |
| return (step + 1) / warmup | |
| progress = (step - warmup) / max(1, total_steps - warmup) | |
| return 0.1 + 0.9 * (1 + math.cos(math.pi * progress)) / 2 | |
| scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule) | |
| destination = args.output / config.mode | |
| parameters = sum(p.numel() for p in model.parameters()) | |
| print(f"{config.mode}: {parameters:,} parameters on {device}", flush=True) | |
| best = -1.0 | |
| history = [] | |
| start = time.monotonic() | |
| for epoch in range(args.epochs): | |
| model.train() | |
| train.epoch = epoch | |
| train_losses = [] | |
| for images, captions, centers, _, _ in batches: | |
| images, captions = images.to(device), captions.to(device) | |
| targets = torch.zeros(len(images), dtype=torch.long, device=device) | |
| scores, affinities, *attributes = ( | |
| model.rank(images, captions) if config.mode == "factorized" else model(images, captions) | |
| ) | |
| loss = F.cross_entropy(scores, targets) | |
| if affinities is not None: | |
| centers = centers.to(device) | |
| loss = loss + args.localization * localization_loss(model, affinities, centers) | |
| if attributes: | |
| color, shape = attributes | |
| loss = loss + args.attribute_weight * attribute_loss(color, shape, centers, model.coordinates) | |
| optimizer.zero_grad(set_to_none=True) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| optimizer.step() | |
| scheduler.step() | |
| train_losses.append(loss.detach()) | |
| mean_loss = torch.stack(train_losses).mean().item() | |
| if not math.isfinite(mean_loss): | |
| raise RuntimeError(f"Non-finite loss in {config.mode} epoch {epoch + 1}") | |
| metrics = evaluate(model, development, device) | |
| row = {"epoch": epoch + 1, "train_loss": mean_loss, "valA": metrics} | |
| print(json.dumps(row), flush=True) | |
| history.append(row) | |
| if metrics["joint"] > best: | |
| best = metrics["joint"] | |
| save_model(model, destination) | |
| best_epoch = epoch + 1 | |
| (destination / "history.json").write_text(json.dumps(history, indent=2) + "\n") | |
| best_model = load_model(destination, device) | |
| results = { | |
| "mode": config.mode, | |
| "parameters": parameters, | |
| "device": device, | |
| "torch": str(torch.__version__), | |
| "platform": platform.platform(), | |
| "seed": args.seed, | |
| "epochs": args.epochs, | |
| "batch_size": args.batch_size, | |
| "learning_rate": args.lr, | |
| "localization_weight": 0.0 if config.mode == "global" else args.localization, | |
| "attribute_weight": args.attribute_weight if config.mode == "factorized" else 0.0, | |
| "train_scenes": len(train), | |
| "selected_epoch": best_epoch, | |
| "wall_minutes": (time.monotonic() - start) / 60, | |
| "valA": evaluate(best_model, development, device, confidence=True), | |
| } | |
| if val_b is not None: | |
| results["valB"] = evaluate(best_model, DataLoader(val_b, batch_size=args.batch_size), device, confidence=True) | |
| (destination / "results.json").write_text(json.dumps(results, indent=2) + "\n") | |
| print(f"{config.mode}: final evaluation written to {destination / 'results.json'}", flush=True) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("data", type=Path) | |
| parser.add_argument("output", type=Path) | |
| parser.add_argument("--mode", choices=(*MODES, "all"), default="all") | |
| parser.add_argument("--device", choices=("auto", "cpu", "mps", "cuda"), default="auto") | |
| parser.add_argument("--epochs", type=int, default=12) | |
| parser.add_argument("--batch-size", type=int, default=48) | |
| parser.add_argument("--resolution", type=int, default=96) | |
| parser.add_argument("--width", type=int, default=128) | |
| parser.add_argument("--depth", type=int, default=4) | |
| parser.add_argument("--heads", type=int, default=4) | |
| parser.add_argument("--embedding", type=int, default=64) | |
| parser.add_argument("--grid-size", type=int, default=6) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--lr", type=float, default=0.0007) | |
| parser.add_argument("--localization", type=float, default=0.35) | |
| parser.add_argument("--attribute-weight", type=float, default=1.0) | |
| parser.add_argument("--train-limit", type=int) | |
| parser.add_argument("--validation-limit", type=int) | |
| parser.add_argument("--evaluate-val-b", action="store_true", help="Evaluate condition B once per selected checkpoint.") | |
| args = parser.parse_args() | |
| if min(args.epochs, args.batch_size) < 1 or args.lr <= 0 or min(args.localization, args.attribute_weight) < 0: | |
| parser.error("epochs, batch size, and learning rate must be positive and auxiliary weights nonnegative") | |
| if any(limit is not None and limit < 1 for limit in (args.train_limit, args.validation_limit)): | |
| parser.error("data limits must be positive") | |
| device = resolve_device(args.device) | |
| modes = MODES if args.mode == "all" else (args.mode,) | |
| configs = [ | |
| Config(mode, args.resolution, args.width, args.depth, args.heads, args.embedding, args.grid_size) | |
| for mode in modes | |
| ] | |
| train = CoGenT(args.data, "trainA", args.resolution, args.train_limit) | |
| val_a = CoGenT(args.data, "valA", args.resolution, args.validation_limit) | |
| val_b = CoGenT(args.data, "valB", args.resolution, args.validation_limit) if args.evaluate_val_b else None | |
| print(f"{len(train):,} usable trainA scenes, {len(val_a):,} valA comparisons", flush=True) | |
| for config in configs: | |
| train_one(config, args, train, val_a, device, val_b) | |
| if __name__ == "__main__": | |
| main() | |