Skip to content

torch_world.metrics ​

Functions on plain tensors, so they apply to any model's features or predictions. torch_world.evaluation holds the protocols that run a model and score it.

Representation quality ​

function linear_probe ​

torch_world.metrics.linear_probe GitHub

python
linear_probe(
    train_x: Tensor,
    train_y: Tensor,
    test_x: Tensor,
    test_y: Tensor,
    ridge: float = 0.001,
    iterations: int = 100,
) -> Probe

Fit a linear map from frozen features (N, D) to targets and score it on the test split.

Integer targets (N,) are classes: multinomial logistic regression fit with full-batch L-BFGS, scored by accuracy. Float targets (N,) or (N, K) are regressed in closed form, scored by R². Features are standardized with the train statistics, and ridge is an L2 penalty on the weights. This is the linear evaluation of I-JEPA and LeJEPA, and the physical probing of LeWM.

Source code in torch_world/metrics/probes.py
python
def linear_probe(
    train_x: Tensor, train_y: Tensor, test_x: Tensor, test_y: Tensor, ridge: float = 1e-3, iterations: int = 100
) -> Probe:
    """Fit a linear map from frozen features ``(N, D)`` to targets and score it on the test split.

    Integer targets ``(N,)`` are classes: multinomial logistic regression fit with full-batch L-BFGS, scored by
    accuracy. Float targets ``(N,)`` or ``(N, K)`` are regressed in closed form, scored by R². Features are
    standardized with the train statistics, and ``ridge`` is an L2 penalty on the weights. This is the linear
    evaluation of I-JEPA and LeJEPA, and the physical probing of LeWM.
    """
    mean, std = train_x.mean(0), train_x.std(0).clamp_min(1e-6)
    x = F.pad((train_x.float() - mean) / std, (0, 1), value=1.0)
    t = F.pad((test_x.float() - mean) / std, (0, 1), value=1.0)
    if train_y.is_floating_point():
        y = train_y.reshape(len(x), -1).to(x)
        eye = torch.eye(x.size(1), dtype=x.dtype, device=x.device)
        with torch.no_grad():
            pred = (t @ torch.linalg.solve(x.T @ x + ridge * len(x) * eye, x.T @ y)).view_as(test_y)
        return Probe(r2_score(pred, test_y), pred)
    num_classes = int(max(train_y.max(), test_y.max())) + 1
    w = torch.zeros(x.size(1), num_classes, device=x.device, requires_grad=True)
    opt = torch.optim.LBFGS([w], max_iter=iterations, line_search_fn="strong_wolfe")

    def closure():
        opt.zero_grad()
        loss = F.cross_entropy(x @ w, train_y) + ridge * w[:-1].square().sum()
        loss.backward()
        return loss

    opt.step(closure)
    with torch.no_grad():
        pred = (t @ w).argmax(1)
    return Probe((pred == test_y).float().mean().item(), pred)

function knn_accuracy ​

torch_world.metrics.knn_accuracy GitHub

python
knn_accuracy(
    train_x: Tensor,
    train_y: Tensor,
    test_x: Tensor,
    test_y: Tensor,
    k: int = 20,
    temperature: float = 0.07,
    center: bool = False,
) -> Probe

Weighted k-nearest-neighbor classification on cosine similarity: each of the k nearest train features votes for its class with weight exp(similarity / temperature). Needs no training, as reported by DINO and LeJEPA. center subtracts the mean train feature first, so a component shared by every input does not dominate the cosine similarity.

Wu et al., "Unsupervised Feature Learning via Non-Parametric Instance Discrimination", CVPR 2018. Paper: https://arxiv.org/abs/1805.01978

Source code in torch_world/metrics/probes.py
python
@torch.no_grad()
def knn_accuracy(
    train_x: Tensor,
    train_y: Tensor,
    test_x: Tensor,
    test_y: Tensor,
    k: int = 20,
    temperature: float = 0.07,
    center: bool = False,
) -> Probe:
    """Weighted k-nearest-neighbor classification on cosine similarity: each of the ``k`` nearest train features votes
    for its class with weight ``exp(similarity / temperature)``. Needs no training, as reported by DINO and
    LeJEPA. ``center`` subtracts the mean train feature first, so a component shared by every input does not
    dominate the cosine similarity.

    Wu et al., "Unsupervised Feature Learning via Non-Parametric Instance Discrimination", CVPR 2018.
    Paper: https://arxiv.org/abs/1805.01978
    """
    num_classes = int(max(train_y.max(), test_y.max())) + 1
    mean = train_x.float().mean(0) if center else 0
    train, preds = F.normalize(train_x.float() - mean, dim=1), []
    for chunk in F.normalize(test_x.float() - mean, dim=1).split(1024):
        sim, idx = (chunk @ train.T).topk(min(k, len(train)), dim=1)
        votes = torch.zeros(len(chunk), num_classes, device=chunk.device)
        preds.append(votes.scatter_add_(1, train_y[idx], (sim / temperature).exp()).argmax(1))
    pred = torch.cat(preds)
    return Probe((pred == test_y).float().mean().item(), pred)

function attentive_probe ​

torch_world.metrics.attentive_probe GitHub

python
attentive_probe(
    train_x: Tensor,
    train_y: Tensor,
    test_x: Tensor,
    test_y: Tensor,
    epochs: int = 20,
    batch_size: int = 256,
    lr: float = 0.001,
    weight_decay: float = 0.01,
    num_heads: int = 8,
    generator: torch.Generator | None = None,
) -> Probe

Train an AttentiveProbe on frozen tokens (N, T, D) with class labels (N,) and report test accuracy, the evaluation of V-JEPA and V-JEPA 2. Unlike a linear probe on pooled features, it can read which tokens matter.

Source code in torch_world/metrics/probes.py
python
def attentive_probe(
    train_x: Tensor,
    train_y: Tensor,
    test_x: Tensor,
    test_y: Tensor,
    epochs: int = 20,
    batch_size: int = 256,
    lr: float = 1e-3,
    weight_decay: float = 0.01,
    num_heads: int = 8,
    generator: torch.Generator | None = None,
) -> Probe:
    """Train an ``AttentiveProbe`` on frozen tokens ``(N, T, D)`` with class labels ``(N,)`` and report test accuracy,
    the evaluation of V-JEPA and V-JEPA 2. Unlike a linear probe on pooled features, it can read which tokens
    matter."""
    num_classes = int(max(train_y.max(), test_y.max())) + 1
    probe = AttentiveProbe(train_x.size(-1), num_classes, num_heads).to(train_x.device)
    opt = torch.optim.AdamW(probe.parameters(), lr=lr, weight_decay=weight_decay)
    steps = epochs * -(-len(train_x) // batch_size)
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, lr, total_steps=steps, pct_start=0.1)
    for _ in range(epochs):
        order = torch.randperm(len(train_x), generator=generator).to(train_x.device)
        for idx in order.split(batch_size):
            loss = F.cross_entropy(probe(train_x[idx].float()), train_y[idx])
            opt.zero_grad()
            loss.backward()
            opt.step()
            sched.step()
    probe.eval()
    with torch.no_grad():
        pred = torch.cat([probe(chunk.float()).argmax(1) for chunk in test_x.split(batch_size)])
    return Probe((pred == test_y).float().mean().item(), pred)

class AttentiveProbe ​

torch_world.metrics.AttentiveProbe GitHub

python
AttentiveProbe(dim: int, num_classes: int, num_heads: int = 8)

A learned query token cross-attends to frozen tokens (B, N, D), followed by an MLP and a linear classifier.

Bardes et al., "Revisiting Feature Prediction for Learning Visual Representations from Video" (V-JEPA), 2024. Paper: https://arxiv.org/abs/2404.08471 Code: https://github.com/facebookresearch/jepa

Source code in torch_world/metrics/probes.py
python
class AttentiveProbe(nn.Module):
    """A learned query token cross-attends to frozen tokens ``(B, N, D)``, followed by an MLP and a linear classifier.

    Bardes et al., "Revisiting Feature Prediction for Learning Visual Representations from Video" (V-JEPA), 2024.
    Paper: https://arxiv.org/abs/2404.08471
    Code: https://github.com/facebookresearch/jepa
    """

    def __init__(self, dim: int, num_classes: int, num_heads: int = 8):
        super().__init__()
        self.query = nn.Parameter(torch.zeros(1, 1, dim))
        self.norm_x, self.norm_q, self.norm_mlp, self.norm_out = (nn.LayerNorm(dim) for _ in range(4))
        self.attn = nn.MultiheadAttention(dim, num_heads, batch_first=True)
        self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
        self.head = nn.Linear(dim, num_classes)
        nn.init.trunc_normal_(self.query, std=0.02)

    def forward(self, x: Tensor) -> Tensor:
        q, x = self.query.expand(len(x), -1, -1), self.norm_x(x)
        q = q + self.attn(self.norm_q(q), x, x, need_weights=False)[0]
        q = q + self.mlp(self.norm_mlp(q))
        return self.head(self.norm_out(q[:, 0]))

class Probe ​

torch_world.metrics.Probe GitHub

python
Probe(score: float, predictions: Tensor)

Test score of a probe (accuracy for classes, R² for regression) and its test predictions.

Source code in torch_world/metrics/probes.py
python
@dataclass
class Probe:
    """Test ``score`` of a probe (accuracy for classes, R² for regression) and its test ``predictions``."""

    score: float
    predictions: Tensor

function r2_score ​

torch_world.metrics.r2_score GitHub

python
r2_score(pred: Tensor, target: Tensor) -> float

Coefficient of determination of (N, K) predictions, averaged over the K targets.

Source code in torch_world/metrics/probes.py
python
def r2_score(pred: Tensor, target: Tensor) -> float:
    """Coefficient of determination of ``(N, K)`` predictions, averaged over the ``K`` targets."""
    pred, target = pred.reshape(len(pred), -1), target.reshape(len(target), -1).to(pred)
    residual = (target - pred).square().sum(0)
    total = (target - target.mean(0)).square().sum(0).clamp_min(1e-12)
    return (1 - residual / total).mean().item()

function rankme ​

torch_world.metrics.rankme GitHub

python
rankme(z: Tensor, center: bool = False, eps: float = 1e-07) -> float

Effective rank of embeddings (N, D): the exponential of the entropy of their normalized singular values.

Ranges from 1 (collapsed) to min(N, D), needs no labels, and tracks downstream accuracy across hyperparameters of one method. As in the paper, the embeddings are used as they are; center subtracts their mean first, for features dominated by one component shared by every input (pooled tokens of mostly-empty images), which would otherwise read as rank 1.

Garrido et al., "RankMe: Assessing the Downstream Performance of Pretrained Self-Supervised Representations by Their Rank", ICML 2023. Paper: https://arxiv.org/abs/2210.02885

Source code in torch_world/metrics/representation.py
python
@torch.no_grad()
def rankme(z: Tensor, center: bool = False, eps: float = 1e-7) -> float:
    """Effective rank of embeddings ``(N, D)``: the exponential of the entropy of their normalized singular values.

    Ranges from 1 (collapsed) to ``min(N, D)``, needs no labels, and tracks downstream accuracy across
    hyperparameters of one method. As in the paper, the embeddings are used as they are; ``center`` subtracts their
    mean first, for features dominated by one component shared by every input (pooled tokens of mostly-empty
    images), which would otherwise read as rank 1.

    Garrido et al., "RankMe: Assessing the Downstream Performance of Pretrained Self-Supervised Representations by
    Their Rank", ICML 2023.
    Paper: https://arxiv.org/abs/2210.02885
    """
    z = z.double()
    return _smooth_rank(torch.linalg.svdvals(z - z.mean(0) if center else z), eps)

function lidar ​

torch_world.metrics.lidar GitHub

python
lidar(z: Tensor, delta: float = 0.0001, eps: float = 1e-07) -> float

Effective rank of the linear discriminant analysis matrix of embeddings (N, Q, D): N surrogate classes (for example images) with Q >= 2 samples each (for example augmented views).

The between-class covariance is whitened by the within-class covariance, so only directions that separate classes count. Designed for JEPAs, where it predicts linear-probe accuracy better than RankMe.

Thilak et al., "LiDAR: Sensing Linear Probing Performance in Joint Embedding SSL Architectures", ICLR 2024. Paper: https://arxiv.org/abs/2312.04000

Source code in torch_world/metrics/representation.py
python
@torch.no_grad()
def lidar(z: Tensor, delta: float = 1e-4, eps: float = 1e-7) -> float:
    """Effective rank of the linear discriminant analysis matrix of embeddings ``(N, Q, D)``: ``N`` surrogate classes
    (for example images) with ``Q >= 2`` samples each (for example augmented views).

    The between-class covariance is whitened by the within-class covariance, so only directions that separate
    classes count. Designed for JEPAs, where it predicts linear-probe accuracy better than RankMe.

    Thilak et al., "LiDAR: Sensing Linear Probing Performance in Joint Embedding SSL Architectures", ICLR 2024.
    Paper: https://arxiv.org/abs/2312.04000
    """
    z = z.double()
    n, q, d = z.shape
    means = z.mean(1)
    between = torch.cov(means.T, correction=1).view(d, d)
    centered = (z - means[:, None]).reshape(-1, d)
    within = centered.T @ centered / (n * (q - 1)) + delta * torch.eye(d, dtype=z.dtype, device=z.device)
    values, vectors = torch.linalg.eigh(within)
    inv_sqrt = vectors @ torch.diag(values.rsqrt()) @ vectors.T
    return _smooth_rank(torch.linalg.eigvalsh(inv_sqrt @ between @ inv_sqrt).clamp_min(0), eps)

Prediction quality ​

function rollout_error ​

torch_world.metrics.rollout_error GitHub

python
rollout_error(pred: Tensor, target: Tensor, p: int = 1) -> Tensor

Mean L_p error per step between predicted and encoded latents (B, T, ...); returns (T,).

Open-loop prediction error grows with the horizon; its curve compares world models on the same encoder. V-JEPA 2-AC trains and evaluates with p = 1; p = 2 gives the mean squared error of DINO-WM and LeWM. Spikes of the one-step error measure surprise, as in LeWM's violation-of-expectation tests.

Source code in torch_world/metrics/prediction.py
python
def rollout_error(pred: Tensor, target: Tensor, p: int = 1) -> Tensor:
    """Mean ``L_p`` error per step between predicted and encoded latents ``(B, T, ...)``; returns ``(T,)``.

    Open-loop prediction error grows with the horizon; its curve compares world models on the same encoder. V-JEPA 2-AC
    trains and evaluates with ``p = 1``; ``p = 2`` gives the mean squared error of DINO-WM and LeWM. Spikes of the
    one-step error measure surprise, as in LeWM's violation-of-expectation tests.
    """
    diff = (pred - target).flatten(2).abs()
    return diff.pow(p).mean((0, 2))

function ssim ​

torch_world.metrics.ssim GitHub

python
ssim(
    pred: Tensor,
    target: Tensor,
    data_range: float = 1.0,
    window: int = 11,
    sigma: float = 1.5,
) -> Tensor

Structural similarity of images (..., C, H, W) with a Gaussian window, one value per image, as DINO-WM reports for decoded predictions.

Wang et al., "Image Quality Assessment: From Error Visibility to Structural Similarity", IEEE TIP 2004. Paper: https://doi.org/10.1109/TIP.2003.819861

Source code in torch_world/metrics/prediction.py
python
def ssim(pred: Tensor, target: Tensor, data_range: float = 1.0, window: int = 11, sigma: float = 1.5) -> Tensor:
    """Structural similarity of images ``(..., C, H, W)`` with a Gaussian window, one value per image, as DINO-WM reports
    for decoded predictions.

    Wang et al., "Image Quality Assessment: From Error Visibility to Structural Similarity", IEEE TIP 2004.
    Paper: https://doi.org/10.1109/TIP.2003.819861
    """
    shape = pred.shape[:-3]
    x, y = pred.reshape(-1, *pred.shape[-3:]).float(), target.reshape(-1, *target.shape[-3:]).float()
    c = x.size(1)
    g = torch.exp(-(torch.arange(window, device=x.device) - window // 2).float().square() / (2 * sigma**2))
    g = g / g.sum()
    kernel = (g[:, None] * g[None]).expand(c, 1, window, window)
    blur = lambda t: F.conv2d(t, kernel, groups=c)
    mx, my = blur(x), blur(y)
    vx, vy, cov = blur(x * x) - mx.square(), blur(y * y) - my.square(), blur(x * y) - mx * my
    c1, c2 = (0.01 * data_range) ** 2, (0.03 * data_range) ** 2
    s = (2 * mx * my + c1) * (2 * cov + c2) / ((mx.square() + my.square() + c1) * (vx + vy + c2))
    return s.flatten(1).mean(1).view(shape)

function psnr ​

torch_world.metrics.psnr GitHub

python
psnr(pred: Tensor, target: Tensor, data_range: float = 1.0) -> Tensor

Peak signal-to-noise ratio in dB of images (..., C, H, W), one value per image.

Source code in torch_world/metrics/prediction.py
python
def psnr(pred: Tensor, target: Tensor, data_range: float = 1.0) -> Tensor:
    """Peak signal-to-noise ratio in dB of images ``(..., C, H, W)``, one value per image."""
    mse = (pred - target).square().flatten(-3).mean(-1).clamp_min(1e-12)
    return 10 * torch.log10(data_range**2 / mse)

function chamfer_distance ​

torch_world.metrics.chamfer_distance GitHub

python
chamfer_distance(x: Tensor, y: Tensor) -> Tensor

Symmetric Chamfer distance between point sets (B, N, D) and (B, M, D): the mean squared distance from each point to its nearest neighbor in the other set, summed over both directions. DINO-WM scores its deformable tasks (rope, granular) with it.

Source code in torch_world/metrics/prediction.py
python
def chamfer_distance(x: Tensor, y: Tensor) -> Tensor:
    """Symmetric Chamfer distance between point sets ``(B, N, D)`` and ``(B, M, D)``: the mean squared distance from
    each point to its nearest neighbor in the other set, summed over both directions. DINO-WM scores its deformable
    tasks (rope, granular) with it."""
    d = torch.cdist(x.float(), y.float()).square()
    return d.min(2).values.mean(1) + d.min(1).values.mean(1)

Calibration ​

function crps ​

torch_world.metrics.crps GitHub

python
crps(samples: Tensor, target: Tensor, fair: bool = False) -> Tensor

Continuous ranked probability score of an ensemble (B, S, ...) against target (B, ...), one value per element of target (lower is better).

CRPS = E|X - y| - E|X - X'| / 2 over the S samples. A point forecast (S = 1) scores its absolute error, so deterministic and stochastic models share one scale. fair uses the unbiased E|X - X'|, which divides by S (S - 1) instead of S^2 and does not reward small ensembles.

Gneiting and Raftery, "Strictly Proper Scoring Rules, Prediction, and Estimation", JASA 2007. Paper: https://doi.org/10.1198/016214506000001437

Source code in torch_world/metrics/calibration.py
python
def crps(samples: Tensor, target: Tensor, fair: bool = False) -> Tensor:
    """Continuous ranked probability score of an ensemble ``(B, S, ...)`` against ``target`` ``(B, ...)``, one value
    per element of ``target`` (lower is better).

    ``CRPS = E|X - y| - E|X - X'| / 2`` over the ``S`` samples. A point forecast (``S = 1``) scores its absolute error,
    so deterministic and stochastic models share one scale. ``fair`` uses the unbiased ``E|X - X'|``, which divides by
    ``S (S - 1)`` instead of ``S^2`` and does not reward small ensembles.

    Gneiting and Raftery, "Strictly Proper Scoring Rules, Prediction, and Estimation", JASA 2007.
    Paper: https://doi.org/10.1198/016214506000001437
    """
    x, S = samples.movedim(1, -1).sort(-1).values, samples.size(1)
    skill = (x - target[..., None]).abs().mean(-1)
    weights = 2 * torch.arange(1, S + 1, device=x.device, dtype=x.dtype) - S - 1
    spread = 2 * (x * weights).sum(-1) / (S * (S - 1) if fair and S > 1 else S * S)
    return skill - 0.5 * spread

function energy_score ​

torch_world.metrics.energy_score GitHub

python
energy_score(
    samples: Tensor, target: Tensor, event_dims: int = 1, fair: bool = False
) -> Tensor

Energy score, the multivariate CRPS, of an ensemble (B, S, ...) against target (B, ...); the last event_dims dimensions form one vector, so (B, S, T, D) gives (B, T) (lower is better).

ES = E||X - y|| - E||X - X'|| / 2; a point forecast scores its Euclidean error. fair as in crps.

Gneiting and Raftery, "Strictly Proper Scoring Rules, Prediction, and Estimation", JASA 2007. Paper: https://doi.org/10.1198/016214506000001437

Source code in torch_world/metrics/calibration.py
python
def energy_score(samples: Tensor, target: Tensor, event_dims: int = 1, fair: bool = False) -> Tensor:
    """Energy score, the multivariate CRPS, of an ensemble ``(B, S, ...)`` against ``target`` ``(B, ...)``; the last
    ``event_dims`` dimensions form one vector, so ``(B, S, T, D)`` gives ``(B, T)`` (lower is better).

    ``ES = E||X - y|| - E||X - X'|| / 2``; a point forecast scores its Euclidean error. ``fair`` as in ``crps``.

    Gneiting and Raftery, "Strictly Proper Scoring Rules, Prediction, and Estimation", JASA 2007.
    Paper: https://doi.org/10.1198/016214506000001437
    """
    S = samples.size(1)
    x = samples.flatten(-event_dims).movedim(1, -2)  # (B, ..., S, E)
    y = target.flatten(-event_dims)[..., None, :]
    skill = (x - y).norm(dim=-1).mean(-1)
    spread = torch.cdist(x.flatten(0, -3), x.flatten(0, -3)).unflatten(0, x.shape[:-2]).sum((-1, -2))
    return skill - 0.5 * spread / (S * (S - 1) if fair and S > 1 else S * S)

function interval_coverage ​

torch_world.metrics.interval_coverage GitHub

python
interval_coverage(
    samples: Tensor,
    target: Tensor,
    levels: Sequence[float] = (0.5, 0.8, 0.9, 0.95),
) -> Tensor

Whether target (B, ...) falls in the central interval of the ensemble (B, S, ...) at each nominal level: (len(levels), B, ...) of 0 and 1. A calibrated ensemble covers each level's share of the targets; less means it is overconfident, more that it is underconfident.

The interval of level l runs between the (1 - l) / 2 and (1 + l) / 2 quantiles of the samples, interpolated linearly. A point forecast covers nothing.

Source code in torch_world/metrics/calibration.py
python
def interval_coverage(samples: Tensor, target: Tensor, levels: Sequence[float] = (0.5, 0.8, 0.9, 0.95)) -> Tensor:
    """Whether ``target`` ``(B, ...)`` falls in the central interval of the ensemble ``(B, S, ...)`` at each nominal
    level: ``(len(levels), B, ...)`` of 0 and 1. A calibrated ensemble covers each level's share of the targets; less
    means it is overconfident, more that it is underconfident.

    The interval of level ``l`` runs between the ``(1 - l) / 2`` and ``(1 + l) / 2`` quantiles of the samples,
    interpolated linearly. A point forecast covers nothing.
    """
    x, S = samples.movedim(1, -1).sort(-1).values, samples.size(1)

    def quantile(q: float) -> Tensor:
        pos = q * (S - 1)
        lo, frac = int(pos), pos - int(pos)
        return x[..., lo] + frac * (x[..., min(lo + 1, S - 1)] - x[..., lo])

    inside = [(quantile((1 - l) / 2) <= target) & (target <= quantile((1 + l) / 2)) for l in levels]
    return torch.stack(inside).to(samples.dtype)

function spread_skill ​

torch_world.metrics.spread_skill GitHub

python
spread_skill(
    samples: Tensor, target: Tensor, dim: int | tuple[int, ...] | None = None
) -> tuple[Tensor, Tensor]

Spread and skill of an ensemble (B, S, ...) against target (B, ...), averaged over dim of the target (all of it by default): spread is the root mean ensemble variance, scaled by (S + 1) / S for the finite ensemble, and skill the root mean squared error of the ensemble mean. A calibrated ensemble has a ratio spread / skill near 1 at every horizon; below 1 it is overconfident. A point forecast has zero spread.

Fortin et al., "Why Should Ensemble Spread Match the RMSE of the Ensemble Mean?", J. Hydrometeorology 2014. Paper: https://doi.org/10.1175/JHM-D-14-0008.1

Source code in torch_world/metrics/calibration.py
python
def spread_skill(samples: Tensor, target: Tensor, dim: int | tuple[int, ...] | None = None) -> tuple[Tensor, Tensor]:
    """Spread and skill of an ensemble ``(B, S, ...)`` against ``target`` ``(B, ...)``, averaged over ``dim`` of the
    target (all of it by default): ``spread`` is the root mean ensemble variance, scaled by ``(S + 1) / S`` for the
    finite ensemble, and ``skill`` the root mean squared error of the ensemble mean. A calibrated ensemble has a ratio
    ``spread / skill`` near 1 at every horizon; below 1 it is overconfident. A point forecast has zero spread.

    Fortin et al., "Why Should Ensemble Spread Match the RMSE of the Ensemble Mean?", J. Hydrometeorology 2014.
    Paper: https://doi.org/10.1175/JHM-D-14-0008.1
    """
    S = samples.size(1)
    var = samples.var(1, correction=1) * (S + 1) / S if S > 1 else torch.zeros_like(target)
    error = (samples.mean(1) - target).square()
    if dim is None:
        return var.mean().sqrt(), error.mean().sqrt()
    return var.mean(dim).sqrt(), error.mean(dim).sqrt()

function gaussian_nll ​

torch_world.metrics.gaussian_nll GitHub

python
gaussian_nll(
    mean: Tensor, var: Tensor, target: Tensor, eps: float = 1e-06
) -> Tensor

Negative log-likelihood of target under N(mean, var), one value per element, in nats (lower is better).

For an ensemble, pass its mean and variance over the samples: the score of the Gaussian that matches its first two moments.

Source code in torch_world/metrics/calibration.py
python
def gaussian_nll(mean: Tensor, var: Tensor, target: Tensor, eps: float = 1e-6) -> Tensor:
    """Negative log-likelihood of ``target`` under ``N(mean, var)``, one value per element, in nats (lower is better).

    For an ensemble, pass its mean and variance over the samples: the score of the Gaussian that matches its first two
    moments.
    """
    var = var.clamp_min(eps)
    return 0.5 * (math.log(2 * math.pi) + var.log() + (target - mean).square() / var)

Robotics and control ​

function success_rate ​

torch_world.metrics.success_rate GitHub

python
success_rate(success: Tensor, confidence: float = 0.95) -> Rate

Fraction of successful episodes (N,) with its Wilson score interval, which stays inside [0, 1] and is reliable at the few dozen episodes robot evaluations afford (16 episodes at 50% give [28%, 72%]).

Wilson, "Probable Inference, the Law of Succession, and Statistical Inference", JASA 1927.

Source code in torch_world/metrics/control.py
python
def success_rate(success: Tensor, confidence: float = 0.95) -> Rate:
    """Fraction of successful episodes ``(N,)`` with its Wilson score interval, which stays inside ``[0, 1]`` and is
    reliable at the few dozen episodes robot evaluations afford (16 episodes at 50% give ``[28%, 72%]``).

    Wilson, "Probable Inference, the Law of Succession, and Statistical Inference", JASA 1927.
    """
    n, k = success.numel(), success.float().sum().item()
    p = k / n
    z = math.sqrt(2) * torch.erfinv(torch.tensor(confidence, dtype=torch.float64)).item()
    center = (p + z**2 / (2 * n)) / (1 + z**2 / n)
    half = z / (1 + z**2 / n) * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2))
    return Rate(p, max(0.0, center - half), min(1.0, center + half), n)

class Rate ​

torch_world.metrics.Rate GitHub

python
Rate(value: float, low: float, high: float, n: int)

A success rate over n episodes with its Wilson score interval [low, high].

Source code in torch_world/metrics/control.py
python
@dataclass(frozen=True)
class Rate:
    """A success rate over ``n`` episodes with its Wilson score interval ``[low, high]``."""

    value: float
    low: float
    high: float
    n: int

    def __float__(self) -> float:
        return self.value

    def __str__(self) -> str:
        return f"{self.value:.0%} [{self.low:.0%}, {self.high:.0%}]"

function first_success ​

torch_world.metrics.first_success GitHub

python
first_success(success: Tensor) -> Tensor

Index of the first successful step of each episode (N, T), or -1 for episodes that never succeed.

Source code in torch_world/metrics/control.py
python
def first_success(success: Tensor) -> Tensor:
    """Index of the first successful step of each episode ``(N, T)``, or ``-1`` for episodes that never succeed."""
    hit = success.bool()
    first = hit.int().argmax(1)
    return torch.where(hit.any(1), first, torch.full_like(first, -1))

function progress ​

torch_world.metrics.progress GitHub

python
progress(distances: Tensor) -> Tensor

Fraction of the initial distance to the goal closed by the end of each episode (N, T): 1 at the goal, 0 when no closer than at the start, negative when farther, and NaN for episodes that start at the goal.

Source code in torch_world/metrics/control.py
python
def progress(distances: Tensor) -> Tensor:
    """Fraction of the initial distance to the goal closed by the end of each episode ``(N, T)``: 1 at the goal,
    0 when no closer than at the start, negative when farther, and NaN for episodes that start at the goal."""
    start = distances[:, 0]
    return (1 - distances[:, -1] / start).where(start > 0, torch.nan)

function path_length ​

torch_world.metrics.path_length GitHub

python
path_length(positions: Tensor) -> Tensor

Length of each path of positions (N, T, D).

Source code in torch_world/metrics/control.py
python
def path_length(positions: Tensor) -> Tensor:
    """Length of each path of positions ``(N, T, D)``."""
    return (positions[:, 1:] - positions[:, :-1]).norm(dim=-1).sum(1)

function spl ​

torch_world.metrics.spl GitHub

python
spl(success: Tensor, positions: Tensor, goal: Tensor) -> float

Success weighted by path length: the mean of success * shortest / max(path, shortest) over episodes, with the straight line from the start position to the goal position (N, D) as the shortest path. A success by a detour twice too long counts one half.

Anderson et al., "On Evaluation of Embodied Navigation Agents", 2018. Paper: https://arxiv.org/abs/1807.06757

Source code in torch_world/metrics/control.py
python
def spl(success: Tensor, positions: Tensor, goal: Tensor) -> float:
    """Success weighted by path length: the mean of ``success * shortest / max(path, shortest)`` over episodes, with
    the straight line from the start position to the ``goal`` position ``(N, D)`` as the shortest path. A success by
    a detour twice too long counts one half.

    Anderson et al., "On Evaluation of Embodied Navigation Agents", 2018.
    Paper: https://arxiv.org/abs/1807.06757
    """
    shortest = (goal - positions[:, 0]).norm(dim=-1)
    taken = path_length(positions)
    return (success.float() * shortest / torch.maximum(taken, shortest).clamp_min(1e-9)).mean().item()

function smoothness ​

torch_world.metrics.smoothness GitHub

python
smoothness(actions: Tensor) -> Tensor

Mean size of the change between consecutive actions (N, T, A) per episode; lower is smoother. Jerky commands that flip direction every step, typical of sampling-based planners, score high.

Source code in torch_world/metrics/control.py
python
def smoothness(actions: Tensor) -> Tensor:
    """Mean size of the change between consecutive actions ``(N, T, A)`` per episode; lower is smoother. Jerky
    commands that flip direction every step, typical of sampling-based planners, score high."""
    return (actions[:, 1:] - actions[:, :-1]).norm(dim=-1).mean(1)

Retrieval ​

function recall_at_k ​

torch_world.metrics.recall_at_k GitHub

python
recall_at_k(
    similarity: Tensor,
    k: int | tuple[int, ...] = (1, 5, 10),
    targets: Tensor | None = None,
)

Retrieval recall@k for a query-by-candidate similarity (Q, C): the fraction of queries whose correct candidate (targets (Q,), by default the diagonal) ranks among the top k. Returns a float, or a dict for several k, as VL-JEPA reports for text-to-video and video-to-text retrieval (transpose for the other way).

Source code in torch_world/metrics/retrieval.py
python
def recall_at_k(similarity: Tensor, k: int | tuple[int, ...] = (1, 5, 10), targets: Tensor | None = None):
    """Retrieval recall@k for a query-by-candidate ``similarity`` ``(Q, C)``: the fraction of queries whose correct
    candidate (``targets`` ``(Q,)``, by default the diagonal) ranks among the top ``k``. Returns a float, or a dict for
    several ``k``, as VL-JEPA reports for text-to-video and video-to-text retrieval (transpose for the other way).
    """
    targets = torch.arange(len(similarity), device=similarity.device) if targets is None else targets
    correct = similarity.gather(1, targets[:, None])
    rank = (similarity > correct).sum(1)
    if isinstance(k, int):
        return (rank < k).float().mean().item()
    return {f"R@{n}": (rank < n).float().mean().item() for n in k}

function topk_accuracy ​

torch_world.metrics.topk_accuracy GitHub

python
topk_accuracy(logits: Tensor, labels: Tensor, k: int = 1) -> float

Fraction of rows of logits (N, C) whose k highest scores include the label, as in zero-shot classification.

Source code in torch_world/metrics/retrieval.py
python
def topk_accuracy(logits: Tensor, labels: Tensor, k: int = 1) -> float:
    """Fraction of rows of ``logits`` ``(N, C)`` whose ``k`` highest scores include the label, as in zero-shot
    classification."""
    return (logits.topk(k, dim=1).indices == labels[:, None]).any(1).float().mean().item()