# examples/dinov2_training_core.py
"""Offline DINOv2 numerical training reference, not pretrained image features."""

import argparse
from collections.abc import Sequence
import copy
from dataclasses import asdict, dataclass
import hashlib
import json
import math
from numbers import Integral, Real
from pathlib import Path
import sys

import torch
from torch import Tensor
from torch import nn
import torch.nn.functional as F
from torch.nn.utils.parametrizations import weight_norm


def _count(value: int, name: str, minimum: int) -> int:
    """Validate an integral count without silently accepting booleans."""
    if isinstance(value, bool) or not isinstance(value, Integral):
        raise TypeError(f"{name} must be an integer")
    if value < minimum:
        raise ValueError(f"{name} must be at least {minimum}")
    return int(value)


def _temperature(value: float) -> float:
    """Validate a finite, strictly positive scalar temperature."""
    if isinstance(value, bool) or not isinstance(value, Real):
        raise TypeError("temperature must be a real number")
    if not math.isfinite(value) or value <= 0:
        raise ValueError("temperature must be finite and positive")
    return float(value)


def _tensor(value: Tensor, name: str, dimensions: int) -> None:
    """Validate tensor rank, floating-point dtype, and finite values."""
    if not isinstance(value, Tensor):
        raise TypeError(f"{name} must be a tensor")
    if value.ndim != dimensions:
        raise ValueError(f"{name} must have {dimensions} dimensions")
    if not value.is_floating_point():
        raise TypeError(f"{name} must have floating-point dtype")
    if not torch.isfinite(value).all():
        raise ValueError(f"{name} must contain only finite values")


def _compatible(value: Tensor, reference: Tensor, name: str) -> None:
    """Require consistent precision and device across a loss calculation."""
    if value.dtype != reference.dtype or value.device != reference.device:
        raise ValueError(f"{name} must match the student dtype and device")


def _targets(value: Tensor, reference: Tensor, shape: tuple[int, int]) -> None:
    """Validate a matrix of prototype probability distributions."""
    _tensor(value, "teacher_targets", 2)
    _compatible(value, reference, "teacher_targets")
    if tuple(value.shape) != shape:
        raise ValueError(f"teacher_targets must have shape {shape}")
    if (value < 0).any():
        raise ValueError("teacher_targets must be nonnegative")
    if not torch.allclose(
        value.sum(-1), value.new_ones(shape[0]), atol=1e-6, rtol=1e-5
    ):
        raise ValueError("teacher_targets rows must sum to one")


def _scaled_logits(value: Tensor, temperature: float) -> Tensor:
    """Scale scores and reject overflow before a probability calculation."""
    scaled = value / temperature
    if not torch.isfinite(scaled).all():
        raise ValueError("temperature scaling produced non-finite scores")
    return scaled


def dino_pairs(local_crops: int) -> tuple[tuple[int, int], ...]:
    """Return teacher-major pairs, excluding matching global views.

    Args:
        local_crops: Number of student-only local crops, at least zero.

    Returns:
        Ordered (teacher_view, student_view) pairs. Global view IDs are 0/1.
    """
    local_crops = _count(local_crops, "local_crops", 0)
    return tuple(
        (teacher, student)
        for teacher in range(2)
        for student in range(2 + local_crops)
        if teacher != student
    )


@torch.no_grad()
def sinkhorn_targets(
    scores: Tensor, temperature: float, iterations: int = 3
) -> Tensor:
    """Compute detached Sinkhorn assignments in the log domain.

    This is the single-process normalization of the pinned DINOv2 release,
    retaining input precision rather than forcing float32. Each iteration
    balances prototypes then samples. Samples are row-normalized at return;
    three iterations need not produce an exactly uniform prototype marginal.

    Args:
        scores: Nonempty teacher score matrix with shape [M, K].
        temperature: Finite, positive teacher temperature.
        iterations: Positive integer number of normalization iterations.

    Returns:
        Detached [M, K] targets, with the same dtype/device as scores.

    Raises:
        ValueError: For empty/nonfinite matrices or invalid scalar values.
        TypeError: For incorrect tensor/count/temperature types.
    """
    _tensor(scores, "scores", 2)
    temperature = _temperature(temperature)
    iterations = _count(iterations, "iterations", 1)
    samples, prototypes = scores.shape
    if samples == 0 or prototypes == 0:
        raise ValueError("Sinkhorn needs nonempty scores; skip it for M=0")
    log_q = _scaled_logits(scores, temperature).t()
    log_q = log_q - torch.logsumexp(log_q.reshape(-1), dim=0)
    for _ in range(iterations):
        log_q = log_q - torch.logsumexp(log_q, dim=1, keepdim=True)
        log_q = log_q - math.log(prototypes)
        log_q = log_q - torch.logsumexp(log_q, dim=0, keepdim=True)
        log_q = log_q - math.log(samples)
    return (log_q + math.log(samples)).exp().t().detach()


def dino_loss(
    student_logits: Sequence[Tensor],
    teacher_targets: Sequence[Tensor],
    student_temperature: float = 0.1,
) -> Tensor:
    """Average soft-target cross-entropy over every valid DINO view pair.

    Args:
        student_logits: Two global views followed by locals, each [B, K].
        teacher_targets: Exactly two global-view probability matrices [B, K].
        student_temperature: Finite, positive student temperature.

    Returns:
        Scalar loss, averaging each pair's batch mean. Teacher targets detach.
    """
    temperature = _temperature(student_temperature)
    if not isinstance(student_logits, Sequence):
        raise TypeError("student_logits must be a sequence of view tensors")
    if not isinstance(teacher_targets, Sequence):
        raise TypeError("teacher_targets must be a sequence of view tensors")
    if len(student_logits) < 2 or len(teacher_targets) != 2:
        raise ValueError(
            "DINO needs at least two student and two teacher views"
        )
    reference = student_logits[0]
    _tensor(reference, "student_logits", 2)
    if min(reference.shape) == 0:
        raise ValueError("DINO batch and prototype count must be positive")
    log_probabilities = []
    for view in student_logits:
        _tensor(view, "student_logits", 2)
        _compatible(view, reference, "student_logits")
        if view.shape != reference.shape:
            raise ValueError("all DINO views must have the same [B, K] shape")
        log_probabilities.append(
            F.log_softmax(_scaled_logits(view, temperature), dim=-1)
        )
    for targets in teacher_targets:
        _targets(targets, reference, tuple(reference.shape))
    # region: dino-loss
    losses = [
        -(teacher_targets[t].detach() * log_probabilities[s]).sum(-1).mean()
        for t, s in dino_pairs(len(student_logits) - 2)
    ]
    return torch.stack(losses).mean()
    # endregion: dino-loss


def ibot_loss(
    student_logits: Tensor,
    teacher_targets: Tensor,
    masks: Tensor,
    student_temperature: float = 0.1,
) -> Tensor:
    """Average each image's masked-patch mean over all global entries.

    Args:
        student_logits: Global patch scores [2B, N, K].
        teacher_targets: Gathered distributions [M, K], in masks' boolean order.
        masks: Boolean [2B, N] tensor on the student's device.
        student_temperature: Finite, positive student temperature.

    Returns:
        Scalar loss. Zero-mask images remain in the 2B denominator. When M=0,
        an empty [0, K] target matrix is required and no Sinkhorn is needed.
        The resulting zero still supports student backpropagation.
    """
    temperature = _temperature(student_temperature)
    _tensor(student_logits, "student_logits", 3)
    entries, patches, prototypes = student_logits.shape
    if entries == 0 or entries % 2 or patches == 0 or prototypes == 0:
        raise ValueError("iBOT requires positive [2B, N, K] dimensions")
    if not isinstance(masks, Tensor) or masks.dtype != torch.bool:
        raise TypeError("masks must be a boolean tensor")
    if masks.shape != student_logits.shape[:2]:
        raise ValueError("masks must have shape [2B, N]")
    if masks.device != student_logits.device:
        raise ValueError("masks must match the student device")
    # region: ibot-loss
    selected = student_logits[masks]
    _targets(teacher_targets, student_logits, (selected.shape[0], prototypes))
    if selected.shape[0] == 0:
        return selected.sum()
    log_probabilities = F.log_softmax(
        _scaled_logits(selected, temperature), dim=-1
    )
    patch_losses = -(teacher_targets.detach() * log_probabilities).sum(-1)
    weights = masks.sum(-1).clamp(min=1).to(student_logits.dtype).reciprocal()
    gathered_weights = weights[:, None].expand_as(masks)[masks]
    return (patch_losses * gathered_weights).sum() / entries
    # endregion: ibot-loss


def koleo_view_loss(features: Tensor) -> Tensor:
    """Regularize nearest-neighbor distance within one global-view batch.

    Args:
        features: Finite backbone CLS features [B, D], with B >= 2 and D >= 1.

    Returns:
        A scalar that can be negative. Normalize with eps=1e-8, select the
        highest dot product excluding self, and use the released distance
        norm(x - neighbor + eps) followed by -mean(log(distance + eps)).
    """
    _tensor(features, "features", 2)
    if features.shape[0] < 2 or features.shape[1] == 0:
        raise ValueError("KoLeo needs at least two images and one feature")
    # region: koleo-loss
    epsilon = 1e-8
    normalized = F.normalize(features, p=2, dim=-1, eps=epsilon)
    similarities = normalized @ normalized.t()
    # Unlike a -1 sentinel, -inf excludes self even for antipodal ties.
    similarities.fill_diagonal_(-math.inf)
    neighbors = similarities.argmax(dim=-1)
    distances = F.pairwise_distance(
        normalized, normalized[neighbors], p=2, eps=epsilon
    )
    return -(distances + epsilon).log().mean()
    # endregion: koleo-loss


def koleo_loss(global_cls: Tensor) -> Tensor:
    """Sum two separate global-view KoLeo terms, without pooling views.

    Args:
        global_cls: Backbone CLS features [2, B, D], before projection heads.

    Returns:
        Sum used by optimization, rather than the average display metric.
    """
    _tensor(global_cls, "global_cls", 3)
    if global_cls.shape[0] != 2:
        raise ValueError("global_cls must contain exactly two global views")
    return koleo_view_loss(global_cls[0]) + koleo_view_loss(global_cls[1])


@dataclass(frozen=True)
class TrainingConfig:
    """User-selectable limits; architecture and recipe remain fixed."""

    device: str = "cpu"
    seed: int = 7
    steps: int = 1
    batch_size: int = 4
    local_crops: int = 8

    def __post_init__(self):
        for name, minimum, maximum in (
            ("steps", 1, 100),
            ("batch_size", 2, 16),
            ("local_crops", 1, 8),
            ("seed", 0, 2**63 - 1),
        ):
            value = _count(getattr(self, name), name, minimum)
            if value > maximum:
                raise ValueError(f"{name} must be at most {maximum}")
        if self.device not in ("cpu", "cuda"):
            raise ValueError("device must be cpu or cuda")
        if self.device == "cuda" and not torch.cuda.is_available():
            raise ValueError("requested CUDA is unavailable")


class TinyBackbone(nn.Module):
    """Two pre-norm transformer blocks over CLS and 8-pixel patch tokens."""

    def __init__(self):
        super().__init__()
        self.patch_embed = nn.Conv2d(3, 64, kernel_size=8, stride=8)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, 64))
        self.mask_token = nn.Parameter(torch.zeros(1, 1, 64))
        self.pos_embed = nn.Parameter(torch.empty(1, 65, 64))
        nn.init.normal_(self.cls_token, std=0.02)
        nn.init.normal_(self.pos_embed, std=0.02)
        self.blocks = nn.ModuleList(
            [
                nn.TransformerEncoderLayer(
                    64,
                    4,
                    dim_feedforward=256,
                    dropout=0.0,
                    activation="gelu",
                    batch_first=True,
                    norm_first=True,
                )
                for _ in range(2)
            ]
        )
        self.norm = nn.LayerNorm(64)

    def forward(
        self, images: Tensor, masks: Tensor | None = None
    ) -> dict[str, Tensor]:
        """Replace selected embeddings before position addition and attention."""
        _tensor(images, "images", 4)
        batch, channels, height, width = images.shape
        if (
            batch == 0
            or channels != 3
            or (height, width) not in ((64, 64), (32, 32))
        ):
            raise ValueError(
                "images must be nonempty [B,3,64,64] or [B,3,32,32]"
            )
        patches = self.patch_embed(images).flatten(2).transpose(1, 2)
        if masks is not None:
            if (
                masks.dtype != torch.bool
                or masks.shape != patches.shape[:2]
                or masks.device != images.device
            ):
                raise ValueError(
                    "masks must be boolean [B,N] on the image device"
                )
            patches = torch.where(masks[..., None], self.mask_token, patches)
        grid = height // 8
        if grid == 8:
            positions = self.pos_embed
        else:
            patch_positions = (
                self.pos_embed[:, 1:].reshape(1, 8, 8, 64).permute(0, 3, 1, 2)
            )
            patch_positions = (
                F.interpolate(
                    patch_positions,
                    size=(grid, grid),
                    mode="bicubic",
                    align_corners=False,
                )
                .flatten(2)
                .transpose(1, 2)
            )
            positions = torch.cat(
                (self.pos_embed[:, :1], patch_positions), dim=1
            )
        tokens = (
            torch.cat((self.cls_token.expand(batch, -1, -1), patches), dim=1)
            + positions
        )
        for block in self.blocks:
            tokens = block(tokens)
        tokens = self.norm(tokens)
        return {"cls": tokens[:, 0], "patches": tokens[:, 1:]}


class PrototypeHead(nn.Module):
    """Three-layer MLP, normalized 16-wide bottleneck, and 32 prototypes."""

    def __init__(self):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(64, 64),
            nn.GELU(),
            nn.Linear(64, 64),
            nn.GELU(),
            nn.Linear(64, 16),
        )
        self.prototypes = weight_norm(nn.Linear(16, 32, bias=False))

    def forward(self, features: Tensor) -> Tensor:
        return self.prototypes(F.normalize(self.mlp(features), p=2, dim=-1))


class DinoTrainingCore(nn.Module):
    """Matching student and frozen clean teacher with independent CLS/patch heads."""

    def __init__(self, config: TrainingConfig | None = None):
        super().__init__()
        self.config = config if config is not None else TrainingConfig()
        self.student = nn.ModuleDict(
            {
                "backbone": TinyBackbone(),
                "cls_head": PrototypeHead(),
                "patch_head": PrototypeHead(),
            }
        ).to(device=self.config.device, dtype=torch.float64)
        self.teacher = copy.deepcopy(self.student).requires_grad_(False).eval()

    def train(self, mode: bool = True):
        """Keep the teacher in evaluation mode even when training the parent."""
        super().train(mode)
        self.teacher.eval()
        return self


def make_views_and_masks(
    config: TrainingConfig,
) -> tuple[list[Tensor], Tensor]:
    """Seed crops from one tensor image batch; simplify production block masks."""
    generator = torch.Generator(device="cpu").manual_seed(config.seed)
    images = torch.randn(
        config.batch_size, 3, 80, 80, generator=generator, dtype=torch.float64
    )
    # region: views-and-masks
    # Globals come first. The clean teacher reuses these exact image tensors.
    views = []
    for size in [64, 64] + [32] * config.local_crops:
        offsets = torch.randint(
            0, 81 - size, (config.batch_size, 2), generator=generator
        )
        crops = torch.stack(
            [
                image[:, top : top + size, left : left + size]
                for image, (top, left) in zip(images, offsets.tolist())
            ]
        )
        views.append(crops.to(config.device))
    masks = torch.zeros(2 * config.batch_size, 64, dtype=torch.bool)
    selected_entries = torch.randperm(
        2 * config.batch_size, generator=generator
    )[: config.batch_size]
    for entry in selected_entries:
        ratio = 0.1 + 0.4 * torch.rand((), generator=generator).item()
        indices = torch.randperm(64, generator=generator)[: int(64 * ratio)]
        masks[entry, indices] = True
    return views, masks.to(config.device)
    # endregion: views-and-masks


def compute_objective(
    model: DinoTrainingCore, views: list[Tensor], masks: Tensor
) -> dict[str, Tensor]:
    """Route masked globals, clean teacher globals, and unmasked student locals."""
    if len(views) != 2 + model.config.local_crops:
        raise ValueError("view count must match the configured local crops")
    batch = model.config.batch_size
    for index, view in enumerate(views):
        size = 64 if index < 2 else 32
        if tuple(view.shape) != (batch, 3, size, size):
            raise ValueError(
                "view shape must match configured batch and crop resolution"
            )
    globals_ = torch.cat(views[:2])
    student_globals = model.student["backbone"](globals_, masks)
    student_locals = model.student["backbone"](torch.cat(views[2:]))
    student_cls = model.student["cls_head"](student_globals["cls"]).split(
        batch
    )
    student_cls += model.student["cls_head"](student_locals["cls"]).split(
        batch
    )
    student_patches = model.student["patch_head"](student_globals["patches"])
    # region: teacher-targets
    with torch.no_grad():
        teacher_globals = model.teacher["backbone"](globals_)
        cls_scores = model.teacher["cls_head"](teacher_globals["cls"])
        cls_targets = sinkhorn_targets(cls_scores, 0.07, iterations=3)
        patch_scores = model.teacher["patch_head"](teacher_globals["patches"])[
            masks
        ]
        # M=0 must bypass Sinkhorn, whose normalization needs nonempty samples.
        patch_targets = (
            sinkhorn_targets(patch_scores, 0.07, iterations=3)
            if patch_scores.shape[0]
            else patch_scores.new_empty((0, 32))
        )
    # endregion: teacher-targets
    global_cls = student_globals["cls"].reshape(2, batch, 64)
    dino = dino_loss(student_cls, cls_targets.split(batch), 0.1)
    ibot = ibot_loss(student_patches, patch_targets, masks, 0.1)
    koleo = koleo_loss(global_cls)
    return {
        "dino": dino,
        "ibot": ibot,
        "koleo": koleo,
        "total": dino + ibot + 0.1 * koleo,
        "global_cls": global_cls,
        "cls_targets": cls_targets,
        "patch_targets": patch_targets,
    }


@torch.no_grad()
def ema_update(
    teacher: nn.Module, student: nn.Module, momentum: float
) -> None:
    """Validate every named parameter before mutating any teacher parameter."""
    if isinstance(momentum, bool) or not isinstance(momentum, Real):
        raise TypeError("momentum must be a real number")
    if not math.isfinite(momentum) or not 0 <= momentum <= 1:
        raise ValueError("momentum must be finite and within [0,1]")
    teachers = dict(teacher.named_parameters())
    students = dict(student.named_parameters())
    if teachers.keys() != students.keys():
        raise ValueError("teacher/student parameter names must match")
    for name, parameter in teachers.items():
        counterpart = students[name]
        if (
            parameter.shape != counterpart.shape
            or parameter.dtype != counterpart.dtype
            or parameter.device != counterpart.device
        ):
            raise ValueError(f"teacher/student parameter mismatch: {name}")
    for name, parameter in teachers.items():
        parameter.mul_(momentum).add_(students[name], alpha=1 - momentum)


def _target_checks(targets: Tensor) -> dict:
    """Report sample normalization and approximate prototype balancing."""
    if targets.shape[0] == 0:
        return {
            "shape": list(targets.shape),
            "finite": True,
            "nonnegative": True,
            "requiresGrad": targets.requires_grad,
            "rowSumMaxError": 0.0,
            "prototypeMarginalMaxResidual": 0.0,
        }
    return {
        "shape": list(targets.shape),
        "finite": bool(torch.isfinite(targets).all()),
        "nonnegative": bool((targets >= 0).all()),
        "requiresGrad": targets.requires_grad,
        "rowSumMaxError": (targets.sum(1) - 1).abs().max().item(),
        "prototypeMarginalMaxResidual": (
            targets.mean(0) - 1 / targets.shape[1]
        )
        .abs()
        .max()
        .item(),
    }


def _gradient_norm(module: nn.Module) -> float:
    """Require connected finite parameter gradients before reporting their norm."""
    gradients = [parameter.grad for parameter in module.parameters()]
    if any(gradient is None for gradient in gradients):
        raise RuntimeError("a student parameter is missing its gradient")
    if any(not torch.isfinite(gradient).all() for gradient in gradients):
        raise RuntimeError("a student gradient is nonfinite")
    return math.sqrt(
        sum(gradient.square().sum().item() for gradient in gradients)
    )


def run_training(config: TrainingConfig) -> dict:
    """Run AdamW then full-model EMA and return verified numerical diagnostics."""
    torch.manual_seed(config.seed)
    model = DinoTrainingCore(config).train()
    views, masks = make_views_and_masks(config)
    optimizer = torch.optim.AdamW(
        model.student.parameters(),
        lr=1e-3,
        weight_decay=0.04,
        betas=(0.9, 0.999),
    )
    momentum = 0.994
    ema_max_error = 0.0
    for _ in range(config.steps):
        optimizer.zero_grad(set_to_none=True)
        objective = compute_objective(model, views, masks)
        if not all(
            torch.isfinite(objective[key])
            for key in ("dino", "ibot", "koleo", "total")
        ):
            raise RuntimeError("training loss is nonfinite")
        old_teacher = {
            name: p.detach().clone()
            for name, p in model.teacher.named_parameters()
        }
        # region: student-and-ema
        objective["total"].backward()
        optimizer.step()
        # Every backbone and head parameter: m*old_teacher + (1-m)*updated_student.
        ema_update(model.teacher, model.student, momentum)
        # endregion: student-and-ema
        gradient_norms = {
            name: _gradient_norm(module)
            for name, module in model.student.items()
        }
        gradient_norms["mask_token"] = (
            model.student["backbone"].mask_token.grad.norm().item()
        )
        students = dict(model.student.named_parameters())
        for name, actual in model.teacher.named_parameters():
            expected = (
                momentum * old_teacher[name]
                + (1 - momentum) * students[name].detach()
            )
            ema_max_error = max(
                ema_max_error, (actual - expected).abs().max().item()
            )
        if not all(
            math.isfinite(value) and value > 0
            for value in gradient_norms.values()
        ):
            raise RuntimeError(
                "expected finite nonzero student module gradients"
            )
    teacher_gradients = sum(
        parameter.grad is not None for parameter in model.teacher.parameters()
    )
    if teacher_gradients or ema_max_error > 1e-10:
        raise RuntimeError("teacher gradient/EMA verification failed")
    targets = {
        "cls": _target_checks(objective["cls_targets"]),
        "patch": _target_checks(objective["patch_targets"]),
    }
    if any(
        not checks["finite"]
        or not checks["nonnegative"]
        or checks["requiresGrad"]
        or checks["rowSumMaxError"] > 1e-10
        for checks in targets.values()
    ):
        raise RuntimeError("teacher target normalization failed")
    student_ids = ["global-0", "global-1"] + [
        f"local-{index}" for index in range(config.local_crops)
    ]
    losses = {
        key: objective[key].item()
        for key in ("dino", "ibot", "koleo", "total")
    }
    losses["koleoPerViewAverage"] = losses["koleo"] / 2
    return {
        "schemaVersion": 1,
        "sourceSha256": hashlib.sha256(
            Path(__file__).read_bytes()
        ).hexdigest(),
        "settings": {
            **asdict(config),
            "dtype": "float64",
            "global_crops": 2,
            "global_resolution": 64,
            "local_resolution": 32,
            "patch_size": 8,
            "feature_width": 64,
            "blocks": 2,
            "heads": 4,
            "dropout": 0.0,
            "prototype_count": 32,
            "bottleneck": 16,
            "student_temperature": 0.1,
            "teacher_temperature": 0.07,
            "sinkhorn_iterations": 3,
            "koleo_weight": 0.1,
            "momentum": momentum,
            "optimizer": "AdamW",
            "lr": 1e-3,
            "weight_decay": 0.04,
            "betas": [0.9, 0.999],
            "torch_version": torch.__version__,
        },
        "views": {"student": student_ids, "teacher": student_ids[:2]},
        "shapes": {
            "globalImages": [config.batch_size, 3, 64, 64],
            "localImages": [config.batch_size, 3, 32, 32],
            "globalCls": [config.batch_size, 64],
            "globalPatches": [config.batch_size, 64, 64],
            "localCls": [config.batch_size, 64],
            "localPatches": [config.batch_size, 16, 64],
            "globalClsForKoLeo": list(objective["global_cls"].shape),
            "masks": list(masks.shape),
        },
        "maskCounts": masks.sum(1).tolist(),
        "dinoPairs": [list(pair) for pair in dino_pairs(config.local_crops)],
        "targets": targets,
        "losses": losses,
        "diagnostics": {
            "gradientNorms": gradient_norms,
            "teacherGradientCount": teacher_gradients,
            "emaMaxError": ema_max_error,
            "emaTolerance": 1e-10,
            "lossStage": "last step before student update",
        },
    }


def main(argv: Sequence[str] | None = None) -> int:
    """Expose bounded numerical training settings and optional JSON output."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
    parser.add_argument("--seed", type=int, default=7)
    parser.add_argument("--steps", type=int, default=1)
    parser.add_argument("--batch-size", type=int, default=4)
    parser.add_argument("--local-crops", type=int, default=8)
    parser.add_argument("--report-json", type=Path)
    args = parser.parse_args(argv)
    try:
        config = TrainingConfig(
            args.device,
            args.seed,
            args.steps,
            args.batch_size,
            args.local_crops,
        )
        report = run_training(config)
        encoded = json.dumps(report, indent=2, allow_nan=False) + "\n"
        if args.report_json:
            args.report_json.parent.mkdir(parents=True, exist_ok=True)
            args.report_json.write_text(encoded, encoding="utf-8")
        else:
            print(encoded, end="")
    except (TypeError, ValueError, RuntimeError, OSError) as error:
        parser.error(str(error))
    return 0


if __name__ == "__main__":
    sys.exit(main())
