Module contents
Lesson 15 of 25Advanced 95 min

Recognition beyond classification: metric learning, verification and retrieval

Learn metric embeddings for verification, identification and retrieval; study contrastive, triplet and angular-margin losses, local features and evaluation across unseen classes.

After this lesson you can

  • Distinguish verification, identification and retrieval metrics.
  • Derive normalized embedding geometry and triplet gradients.
  • Implement batch-hard mining and analyze angular margins.
  • Build exact embedding retrieval with separate identities and evaluation splits.
  • Interpret uncertainty and group-level error under an explicit protocol.

Before you start

Recognizing without enumerating every class

A closed softmax head returns scores for classes on which it trained. If new species, products or people appear tomorrow, their columns do not exist. An alternative is to learn a function fθ(x)f_\theta(x) placing related examples nearby and others far apart. A query is compared with references that can be added after training. The representation does not turn distance into infallible identity: that interpretation depends on task, data and threshold.

Verification means deciding whether two examples correspond to the same identity: with distance dd, accept when d≤τd\le\tau. Identification compares a query with a gallery; rank 1 is the fraction whose first candidate has the correct identity. Retrieval concerns ranking relevant items, perhaps more than one per query. A classifier can reject unknown inputs, but a closed head without a rejection rule does not itself solve the open-set case.

In verification, FAR or false acceptance rate is the fraction of impostor pairs accepted; TAR is the fraction of genuine pairs accepted. Set τ\tau using validation and measure both rates on independent test. As τ\tau increases, both are nondecreasing, with jumps due to ties. With NIN_I impostor pairs, empirical resolution is 1/NI1/N_I; observing zero false acceptances does not prove the true rate is zero. Pairs sharing images are also correlated, so they are not NIN_I independent observations.

InteractiveThe verification threshold

A pair is accepted if its 1 − cosine dissimilarity is less than or equal to the threshold. The vertical line marks the cutoff. Bars show proportions within each group, not absolute counts.

0%20%40%0.00.51.01.52.0
  • Same class
  • Different class
  • Threshold

Dissimilarity ranges from 0 to 2 for unit vectors; it is not Euclidean distance. This split contains 50 queries, 150 gallery images, 300 same-class comparisons and 7200 different-class comparisons.

ROC obtained from these same pairs0.00.00.50.51.01.0FAR · different-class acceptanceTAR

TAR = accepted same-class pairs / same-class pairs; FAR = accepted different-class pairs / different-class pairs. The ROC sweeps this split’s thresholds and the point highlights the current threshold. Ties are accepted together.

The initial threshold 0.217199 was chosen on validation for FAR ≤ 5 %; test is shown with that same threshold. If you change it after looking at test, test ceases to be an independent evaluation. Reset restores the calibrated threshold and validation.

Flower category pairs from this lesson’s short run, not people: 20 steps and one seed, checkpoint 1. Source: Donghyun99/Oxford-Flower-102, revision 06fcc9a1, using extractor ResNet18_Weights.IMAGENET1K_V1. Comparisons share images and are not independent. Empirical FAR changes in steps of 1/7200; that granularity is not a confidence interval and does not guarantee an operational rate.

Displayed pairs
496
Distance threshold0.217199
TAR45.33 %
FAR5.00 %
Same-class pairs accepted136 / 300
Different-class pairs accepted360 / 7200
Move the distance threshold and compare validation and test counts on real embeddings from the lab's short run.

For retrieval, recall@k here means the fraction of queries with at least one relevant item among the first kk. A query’s average precision averages precision at each relevant position and divides by its gallery’s total relevant count; mAP averages across queries. Other publications use different definitions of recall and truncated AP, so state them. Exclude the query itself from the gallery and define how ties and queries without positives are handled. Musgrave and colleagues analyze how evaluation choices can alter metric-learning comparisons.

A shared geometry

A Siamese network applies the same parameters to each branch: za=fθ(xa)z_a=f_\theta(x_a) and zb=fθ(xb)z_b=f_\theta(x_b). Weight sharing allows comparison of coordinates in the same representation; it does not require a particular architecture. In deep metric learning, supervision acts on relationships between examples.

For nonzero vectors normalize u=z/∥z∥2u=z/\lVert z\rVert_2 and v=w/∥w∥2v=w/\lVert w\rVert_2. Then ∥u−v∥22=2−2uTv=2−2cos⁡θ\lVert u-v\rVert_2^2=2-2u^Tv=2-2\cos\theta. Ranking by descending cosine therefore equals ranking by ascending Euclidean distance. Without normalization, norm affects distance and that equivalence no longer holds. A zero vector has no direction: specify how to handle it rather than dividing by zero.

A pairwise contrastive loss with y=1y=1 for positives and Euclidean distance dd can be written L=yd2+(1−y)[max⁡(0,m−d)]2L=y d^2+(1-y)[\max(0,m-d)]^2. It pulls positives together and penalizes only negatives inside margin m>0m>0. Other conventions reverse labels or also use squared distances in the margin; check which each library implements.

InteractiveClasses on the hypersphere

The points are directly optimized unit vectors, not images or a CNN. Hollow circles are normalized class weights in softmax and ArcFace; for triplets they are normalized means. Central differences, a fixed step and renormalization after each update are used. A classical gradient may not exist at ties or corners of the loss. Mining uses the farthest positive and nearest negative in the batch; changing mode or margin resets the trajectory.

ArcFace uses the target logit cos(θ+m), scale 8 and the specified margin; no monotonic extension is applied here when θ+m exceeds π. Results depend on initialization and do not prove that one loss always separates classes better.

Step0
Loss0.1033
Minimum angle between centers66.1°
A directly optimized geometric model compares loss functions; it does not represent full CNN training.

Triplets and in-batch mining

For anchor aa, positive pp of the same class and negative nn of another, a triplet loss with squared distances is

L(a,p,n)=max⁡{0,∥ua−up∥2−∥ua−un∥2+α}.L(a,p,n)=\max\{0,\lVert u_a-u_p\rVert^2-\lVert u_a-u_n\rVert^2+\alpha\}.

An easy negative already satisfies the margin and contributes zero loss. A hard one is at least as close to the anchor as the positive. A semi-hard one satisfies d2(a,p)<d2(a,n)<d2(a,p)+αd^2(a,p)<d^2(a,n)<d^2(a,p)+\alpha: it is farther than the positive but still violates the margin. If no candidate exists, define whether the pair is omitted or another policy used; the lab omits and reports how many remain. Mining depends on the batch, so composition and examples per class matter.

With the selected triplet fixed and hinge active, before propagating through normalization we obtain ∇uaL=2(un−up)\nabla_{u_a}L=2(u_n-u_p), ∇upL=2(up−ua)\nabla_{u_p}L=2(u_p-u_a) and ∇unL=2(ua−un)\nabla_{u_n}L=2(u_a-u_n). Their sum is zero: distance loss does not change under common translation of these three free vectors. Through normalization, the Jacobian projects each gradient onto the tangent plane of its direction and scales it by the inverse prior norm. Minimum or maximum selection changes branch at ties; there is no unique ordinary derivative there, and a finite difference can cross different branches.

FaceNet used unit embeddings, margin α=0,2\alpha=0{,}2 (0.2) and mining in large batches, approximately 1800 images with about 40 per identity. Its authors found that selecting the hardest negatives initially could lead to degenerate minima, including collapse. This is not a universal law: Hermans and colleagues studied batch-hard mining for reidentification under their own protocol. If all unit vectors coincide, collapse is a common direction, not necessarily the zero vector.

InteractiveChoose your triplets

Each point is a directly optimized 2D representation; it is not a network trained on images. The double circle marks the anchor. The solid line connects its positive and the dashed line its selected negative. The ordinary scenario starts from six distinct positions.

012345
  • Class 0
  • Class 1
  • Class 2
  • Positive pair
  • Negative

Anchor 0, positive 1, negative 2: d²(a,p) = 0.1300, d²(a,n) = 0.8500. The loss is max(0, d²(a,p) − d²(a,n) + margin).

Loss over descent01.1030Step

Thirty full-batch gradient descent steps are calculated with rate 0.08. Each class has two points, so each anchor has one positive. Random picks a negative from another class with the specified seed; hardest picks the nearest; semi-hard picks the nearest satisfying d²(a,p) < d²(a,n) < d²(a,p) + margin. Ties favor the lowest index.

The mean includes all selected triplets, even those with zero loss. In semi-hard mining, if there is no candidate the anchor is omitted; if all six are omitted, loss and gradient are zero, which does not prove the margin is satisfied. At this step 0 were omitted. Dispersion is the mean of ||zᵢ − mean(z)||², not a measure of retrieval quality. The result depends on selection and margin: this example does not show that a method always collapses.

Initial points
Mining
0
0
0.8
Random sampling seed
Mean batch loss0.3137
Selected triplet loss0.0800
Triplets used6 of 6
Squared dispersion0.5534
Dispersion / initial100.00 %
Select anchor, margin and mining in an explicit geometric batch; steps are calculated live.

From normalized softmax to angular margin

With normalized feature vectors uu and class weights vjv_j, softmax uses logits scos⁡θj=s uTvjs\cos\theta_j=s\,u^Tv_j, where s>0s>0 controls scale. Normalization removes the ability to arbitrarily increase norms to concentrate the distribution. NormFace studies this normalization; SphereFace introduces a multiplicative angular margin.

CosFace and ArcFace modify only the correct-class logit during training. CosFace uses s(cos⁡θy−m)s(\cos\theta_y-m); ArcFace uses scos⁡(θy+m)s\cos(\theta_y+m). At the boundary between two classes, ArcFace requires θy+m<θj\theta_y+m<\theta_j for the correct class to win, provided both angles are compared on an interval where cosine decreases. If θy+m>π\theta_y+m>\pi, the pure formula ceases to be monotonic; some implementations apply a piecewise extension. At inference embeddings are compared without adding a margin to the pair.

For c=uTvyc=u^Tv_y and −1<c<1-1<c<1, the derivative of cos⁡(arccos⁡c+m)\cos(\arccos c+m) with respect to cc is cos⁡m+csin⁡m/1−c2\cos m+c\sin m/\sqrt{1-c^2}. Normalization contributes the Jacobian (I−uuT)/∥z∥(I-uu^T)/\lVert z\rVert. The gradient with respect to zz is tangent to the sphere at uu; near c=±1c=\pm1 the angular derivative needs numerical care. The from-scratch lab rejects those extremes, while the PyTorch lab explains its protection and piecewise extension. Original papers use s=64s=64, with m=0,5m=0{,}5 (0.5) radians for ArcFace and m=0,35m=0{,}35 (0.35) in the CosFace protocol; these are not universally optimal values.

Searching without confusing splits

First split identities or categories into disjoint training, validation and test sets when the question is generalization to new classes. Within validation and test, separate query and gallery images and check duplicates. Select parameters and checkpoint on validation; evaluate once on test. Repeated decisions while looking at test make that reading exploratory. A pretrained extractor may have seen examples or classes related to test: declaring this is part of the protocol.

An exact index stores each normalized gallery vector and computes inner products with the normalized query. It sorts descending, breaks ties stably and returns identifiers and distances. At scale, an approximate index changes the memory, latency and recall tradeoff; measure recall against exact search. Reranking can reorder candidates with a more expensive model, but cannot recover a relevant item absent from the candidate list. Vector-search systems are studied later.

For NN vectors of dimension dd, an exact query needs on the order of NdNd similarity multiplications and storage for on the order of NdNd components, plus candidate sorting or selection. In a gallery with two relevant items at positions 1 and 4, recall@1 and recall@4 are both one under the above definition, but that query’s average precision is (1+2/4)/2=0,75(1+2/4)/2=0{,}75 (0.75). The metrics describe different aspects: finding at least one relevant item and ranking all relevant items. Matching multiple views of the same object can inflate measurement if query and gallery share an image or duplicate.

From whole images to local correspondences

A global embedding summarizes the whole image. To align views, reconstruct a scene or localize an object, you also need learned local features: point coordinates and neighborhood descriptors. SIFT builds a local-gradient descriptor with orientation and scale; ORB combines oriented FAST points and a rotated binary BRIEF descriptor. A common comparison uses Euclidean distance between SIFT descriptors and Hamming distance between binary ORB descriptors. Learned descriptors also need a distance rule compatible with their training.

Mutual-nearest-neighbor matching retains a↔ba\leftrightarrow b only if bb is aa‘s nearest neighbor and aa is bb‘s, under a stated tie rule. This reduces some ambiguities but does not guarantee geometrically correct correspondence or find all valid points. The ratio criterion compares distances to first and second neighbors to reject ambiguous candidates; its threshold also needs validation. Repeated patterns, occlusion and viewpoint changes can mislead both classical and learned methods.

HardNet learns patch descriptors using loss with hard in-batch negatives. SuperPoint jointly predicts points and descriptors; its homographic adaptation combines transformed predictions to create supervision on images without manual labels. SuperGlue uses attention and optimal transport to match two sets and reject unmatched points; LightGlue adapts compute to pair difficulty. None automatically replaces geometric verification: check correspondences and estimate transformation with a robust method when the task requires it.

SuperPoint table 4 compares HPatches using up to 1000 points per image, nearest neighbor and RANSAC. For homography estimation at 3-pixel tolerance it reports 0.684 for SuperPoint, 0.676 for SIFT and 0.395 for ORB; at 1-pixel tolerance it reports 0.310, 0.424 and 0.150 respectively. In the same table ORB repeatability is 0.641 versus 0.581 for SuperPoint. These are different metrics and protocols: detecting repeatable points does not by itself guarantee better matching or geometric estimation.

Group errors and consequences

Aggregate accuracy can hide differences in false acceptance or rejection across groups. In NIST FRVT Part 3, figure 12 and discussion on page 47, Imperial-002 had a false match rate of 0.0068 for women in the group the report calls “American Indian,” versus 0.0001 for white men, at the same threshold calibrated on the latter group using mugshots. The observed difference was 68-fold for that algorithm and dataset; NIST did not establish its cause. Threshold, pair composition, image quality and group size affect interpretation; do not turn an observed difference into a causal explanation without study. Sensitive applications require evaluation on relevant groups, uncertainty intervals respecting person-level dependence, alternatives and appropriate oversight. The lab’s flowers do not validate a biometric system.

Lab: losses from scratch

These cells use small explicit data. Start by implementing pairwise contrastive loss and check one positive and two negatives, one outside the margin:

[ ]Pairwise contrastive lossBrowser
import numpy as np

def contrastive_loss(left, right, same, margin=1.0):
    left, right = np.asarray(left, dtype=float), np.asarray(right, dtype=float)
    same = np.asarray(same, dtype=bool)
    if left.ndim != 2 or left.shape != right.shape or same.shape != (len(left),):
        raise ValueError('Se requiere un par de vectores y una etiqueta por fila')
    if len(left) == 0 or margin <= 0:
        raise ValueError('Se requiere un lote no vacío y margen positivo')
    distance = np.linalg.norm(left - right, axis=1)
    terms = np.where(same, distance**2, np.maximum(0, margin-distance)**2)
    return float(terms.mean()), terms

left = np.zeros((3, 2))
right = np.array([[0.3, 0.4], [2.0, 0.0], [0.4, 0.0]])
mean, terms = contrastive_loss(left, right, [True, False, False])
assert np.allclose(terms, [0.25, 0.0, 0.36])
assert np.isclose(mean, 0.61/3)
print('Términos:', terms, 'media:', mean)

The next cell selects the closest semi-hard negative for each anchor-positive pair, omits pairs without a candidate and calculates gradients with fixed selection. Finite differences check them away from ties and the margin boundary. The last checks the ArcFace derivative with fixed weights, avoiding angular extremes.

[ ]Semi-hard triplets from scratchBrowser
"""Distancias cuadradas, minería semidifícil y gradiente de tripletes.

Para cada par ancla-positivo distinto elegimos el negativo válido más cercano
que cumple d_ap² < d_an² < d_ap² + margen. Si no existe, omitimos ese par.
La pérdida promedia solo los tripletes seleccionados; si no hay ninguno,
devuelve cero y gradiente cero. El desempate usa el menor índice del lote.
"""
import numpy as np


def squared_distances(z):
    z = np.asarray(z, dtype=np.float64)
    if z.ndim != 2 or not z.size or not np.isfinite(z).all():
        raise ValueError('Se espera una matriz no vacía y finita')
    norm = np.sum(z * z, axis=1)
    result = np.maximum(norm[:, None] + norm[None, :] - 2 * (z @ z.T), 0.0)
    np.fill_diagonal(result, 0.0)
    return result


def semi_hard_triplets(z, labels, margin):
    d = squared_distances(z)
    labels = np.asarray(labels)
    if labels.shape != (len(d),) or not np.isfinite(margin) or margin <= 0:
        raise ValueError('Etiquetas o margen inválidos')
    selected, pairs, omitted = [], 0, 0
    for anchor in range(len(d)):
        positives = np.flatnonzero((labels == labels[anchor]) & (np.arange(len(d)) != anchor))
        negatives = labels != labels[anchor]
        for positive in positives:
            pairs += 1
            dap = d[anchor, positive]
            candidates = np.flatnonzero(negatives & (d[anchor] > dap) & (d[anchor] < dap + margin))
            if len(candidates):
                negative = candidates[np.argmin(d[anchor, candidates])]
                selected.append((anchor, int(positive), int(negative)))
            else:
                omitted += 1
    return np.asarray(selected, dtype=np.int64).reshape(-1, 3), {'pairs': pairs, 'omitted': omitted}


def triplet_loss_and_grad(z, triplets, margin):
    z = np.asarray(z, dtype=np.float64)
    t = np.asarray(triplets, dtype=np.int64).reshape(-1, 3)
    if z.ndim != 2 or not z.size or not np.isfinite(z).all() or not np.isfinite(margin) or margin <= 0:
        raise ValueError('Embeddings o margen inválidos')
    if np.any(t < 0) or np.any(t >= len(z)):
        raise ValueError('Índices fuera del lote')
    grad = np.zeros_like(z)
    if len(t) == 0:
        return 0.0, grad
    a, p, n = z[t[:, 0]], z[t[:, 1]], z[t[:, 2]]
    raw = np.sum((a - p)**2, axis=1) - np.sum((a - n)**2, axis=1) + margin
    active = (raw > 0)[:, None]
    np.add.at(grad, t[:, 0], active * 2 * (n - p) / len(t))
    np.add.at(grad, t[:, 1], active * 2 * (p - a) / len(t))
    np.add.at(grad, t[:, 2], active * 2 * (a - n) / len(t))
    return float(np.maximum(raw, 0).mean()), grad


z = np.array([[0., 0.], [1., 0.], [1.2, .2], [1.5, .1], [2.3, .5], [2.6, .7]])
labels = np.array([0, 0, 1, 1, 2, 2])
margin = 1.1
d = squared_distances(z)
reference = np.array([[np.sum((a - b)**2) for b in z] for a in z])
np.testing.assert_allclose(d, reference, atol=1e-12)
triplets, stats = semi_hard_triplets(z, labels, margin)
assert len(triplets) > 0
for a, p, n in triplets:
    assert labels[a] == labels[p] and a != p and labels[a] != labels[n]
    assert d[a, p] < d[a, n] < d[a, p] + margin
loss, analytic = triplet_loss_and_grad(z, triplets, margin)
eps = 1e-6
numeric = np.zeros_like(z)
for i in range(z.shape[0]):
    for j in range(z.shape[1]):
        plus, minus = z.copy(), z.copy()
        plus[i, j] += eps
        minus[i, j] -= eps
        assert np.array_equal(semi_hard_triplets(plus, labels, margin)[0], triplets)
        assert np.array_equal(semi_hard_triplets(minus, labels, margin)[0], triplets)
        numeric[i, j] = (triplet_loss_and_grad(plus, triplets, margin)[0]
                         - triplet_loss_and_grad(minus, triplets, margin)[0]) / (2 * eps)
error = np.max(np.abs(analytic - numeric))
assert error < 1e-7
empty, empty_stats = semi_hard_triplets(np.array([[0.], [.01], [2.], [2.01]]), [0, 0, 1, 1], .1)
empty_loss, empty_grad = triplet_loss_and_grad(np.array([[0.], [.01], [2.], [2.01]]), empty, .1)
assert len(empty) == 0 and empty_stats['omitted'] == 4 and empty_loss == 0 and not empty_grad.any()
print('Matriz de distancias cuadradas:\n', np.round(d, 3))
print('Tripletes (ancla, positivo, negativo):', triplets.tolist())
print('Pares:', stats['pairs'], 'omitidos:', stats['omitted'], 'pérdida:', round(loss, 8))
print('Error máximo del gradiente por diferencias finitas:', error)
print('Caso sin semidifíciles: 4 pares omitidos, pérdida y gradiente cero.')
[ ]ArcFace gradientBrowser
"""ArcFace con embeddings crudos y gradiente de la media respecto a ellos.

Usamos cos(θ+m) sin una rama de corrección y exigimos cosenos objetivo lejos
de ±1, donde la fórmula angular presenta una derivada singular. No se usa
clamp: esto permite comprobar la derivada de la misma función que evaluamos.
"""
import numpy as np


def unit_rows(a):
    a = np.asarray(a, dtype=np.float64)
    if a.ndim != 2 or not a.size or not np.isfinite(a).all():
        raise ValueError('Se espera una matriz finita no vacía')
    norms = np.linalg.norm(a, axis=1, keepdims=True)
    if np.any(norms <= 1e-12):
        raise ValueError('No se puede normalizar un vector nulo o casi nulo')
    return a / norms, norms


def arcface_loss_grad(z, weights, labels, scale=8., margin=.3):
    u, norms = unit_rows(z)
    v, _ = unit_rows(weights)
    labels = np.asarray(labels)
    if (v.shape[1] != u.shape[1] or labels.shape != (len(u),)
            or not np.issubdtype(labels.dtype, np.integer)
            or np.any(labels < 0) or np.any(labels >= len(v))
            or not np.isfinite(scale) or scale <= 0
            or not np.isfinite(margin) or margin < 0):
        raise ValueError('Dimensiones, etiquetas, escala o margen inválidos')
    cosine = u @ v.T
    idx = np.arange(len(u))
    target = cosine[idx, labels]
    if np.any(1 - target**2 <= 1e-12):
        raise ValueError('Coseno objetivo demasiado próximo a ±1')
    sine = np.sqrt(1 - target**2)
    phi = target * np.cos(margin) - sine * np.sin(margin)
    logits = scale * cosine
    logits[idx, labels] = scale * phi
    shifted = logits - logits.max(axis=1, keepdims=True)
    exp = np.exp(shifted)
    probabilities = exp / exp.sum(axis=1, keepdims=True)
    loss = np.mean(np.log(exp.sum(axis=1)) - shifted[idx, labels])
    coefficients = probabilities.copy()
    coefficients[idx, labels] -= 1
    coefficients *= scale / len(u)
    coefficients[idx, labels] *= np.cos(margin) + target * np.sin(margin) / sine
    grad_u = coefficients @ v
    grad_z = (grad_u - u * np.sum(u * grad_u, axis=1, keepdims=True)) / norms
    return float(loss), grad_z, logits


z = np.array([[.7, .4, -.2], [-.3, .8, .4], [.2, -.5, .9]])
w = np.array([[.1, .9, .3], [-.4, .2, .7], [.8, -.3, .1]])
labels = np.array([0, 1, 2])
loss, analytic, logits = arcface_loss_grad(z, w, labels)
eps = 1e-6
numeric = np.zeros_like(z)
for i in range(z.shape[0]):
    for j in range(z.shape[1]):
        plus, minus = z.copy(), z.copy()
        plus[i, j] += eps
        minus[i, j] -= eps
        numeric[i, j] = (arcface_loss_grad(plus, w, labels)[0]
                         - arcface_loss_grad(minus, w, labels)[0]) / (2 * eps)
error = np.max(np.abs(analytic - numeric))
assert error < 1e-7
np.testing.assert_allclose(np.sum(analytic * z, axis=1), 0, atol=1e-12)
angle = np.pi / 3
print('Logits ArcFace:\n', np.round(logits, 6))
print('Pérdida media:', round(loss, 8))
print('Error máximo del gradiente por diferencias finitas:', error)
print('Producto gradiente·embedding crudo:', np.round(np.sum(analytic*z, axis=1), 12))
print('Ejemplo s=64, m=0.5, angulo=60 grados:', 64 * np.cos(angle + .5),
      '; sin margen:', 64 * np.cos(angle))

Lab: a flower search engine

The local lab uses Flowers-102 from a pinned-revision mirror, groups images into 51 training, 25 validation and 26 test categories, and separates queries from gallery. This is not the official classification split. Combining the mirror’s three splits, the check found four exact duplicate files, all with the same label: the first copy is retained and discards reported; conflicting labels stop execution. A pretrained ResNet-18 and projection learn with ArcFace; checkpoint is selected by validation recall@1. Full reader mode runs 4000 steps; the short check uses one seed, 20 steps and eight images per class. Pretrained weights may share data or categories with evaluation; hashes detect only identical bytes in the collection.

In the short run, the selected checkpoint was step 1. On test it obtained recall@1 of 73.08%, recall@5 of 96.15% and mAP of 51.80%. These figures describe only that run with pretrained features and do not demonstrate convergence or improvement caused by ArcFace. A threshold chosen on validation at 5% FAR produced 52.88% TAR and 6.90% FAR on test; pairs share images and are not independent. The search engine returns exact cosine neighbors and retains identifiers. Repeating with seeds, more data and external protocols is needed to assess stability.

To query your own image, set environment variable ORYON_QUERY_IMAGE to its path before running the cell. Code applies the same preprocessing and searches the test gallery: it returns five neighbors and excludes files with a hash identical to the query’s. This exclusion does not detect recodings or near-duplicates. Repeatedly querying the test gallery to decide the model would also compromise its use as final evaluation.

[ ]Train and query a flower indexLocal GPU
"""ArcFace y recuperación de categorías de flores que no se entrenaron.

Requiere torch, torchvision, numpy, pyarrow, Pillow, huggingface_hub y CUDA.
Usa las imágenes de Flowers-102 de un espejo con revisión fija. Las clases
se dividen en 51/25/26 ANTES de entrenar; este protocolo NO es el split
oficial de clasificación. La tarea usa categorías, no identidades humanas.
Separa consulta y galería por imagen. Se conservan los primeros bytes únicos
y se rechazan etiquetas contradictorias para imágenes idénticas. Los hashes
no detectan recodificaciones ni posible solapamiento con ImageNet.
Selecciona el checkpoint por recall@1 de categorías de validación. El test
se calcula una vez tras seleccionar; inspeccionar resultados de muchos
modelos lo convertiría en exploratorio. ORYON_VERIFY_SHORT=1 solo verifica
el circuito. Salidas: ORYON_METRIC_OUTPUT, ORYON_METRIC_GALLERY_OUTPUT y
ORYON_METRIC_PAIRS_OUTPUT. ORYON_QUERY_IMAGE admite una ruta opcional de
imagen para buscar en la galería de test, excluyendo copias de bytes exactos.
"""
import base64
import gc
import hashlib
import io
import json
import math
import os
from pathlib import Path

os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import numpy as np
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from torchvision.models import ResNet18_Weights, resnet18

torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda':
    raise RuntimeError('Este laboratorio requiere CUDA')
amp = torch.cuda.is_bf16_supported()
steps = 20 if short else 4000
batch_size = 16 if short else 64
seed = 16151
repo = 'Donghyun99/Oxford-Flower-102'
revision = '06fcc9a13ee3f84cc7f36fa0eef10df2c7f8750f'
files = {
    'train': 'data/train-00000-of-00001-95813d8dab877ff5.parquet',
    'validation': 'data/validation-00000-of-00001-a2ccf8138610462c.parquet',
    'test': 'data/test-00000-of-00001-1cc6f065cd5391ec.parquet',
}
weights = ResNet18_Weights.IMAGENET1K_V1
# La resolución se reduce deliberadamente respecto al preprocesado oficial.
preprocess = transforms.Compose([transforms.Resize(128), transforms.CenterCrop(112), transforms.ToTensor(),
    transforms.Normalize(mean=(.485, .456, .406), std=(.229, .224, .225))])


def read_images():
    by_class = [[] for _ in range(102)]
    seen = {}
    duplicates = {split: {'total': 0, 'by_class': {}} for split in files}
    # La comprobación breve toma ocho imágenes por clase del split train.
    # El modo completo une los splits oficiales y vuelve a dividir por clases.
    source_splits = ['train'] if short else ['train', 'validation', 'test']
    for split in source_splits:
        path = hf_hub_download(repo_id=repo, repo_type='dataset', filename=files[split], revision=revision)
        parquet = pq.ParquetFile(path)
        offset = 0
        for batch in parquet.iter_batches(batch_size=32, columns=['image', 'label']):
            for image, label in zip(batch.column(0).to_pylist(), batch.column(1).to_pylist()):
                label = int(label)
                if short and len(by_class[label]) >= 8:
                    offset += 1
                    continue
                raw = image['bytes']
                digest = hashlib.sha256(raw).hexdigest()
                if digest in seen:
                    if seen[digest]['label'] != label:
                        raise ValueError('Imagen idéntica con etiquetas distintas: ' + digest)
                    duplicates[split]['total'] += 1
                    key = str(label)
                    duplicates[split]['by_class'][key] = duplicates[split]['by_class'].get(key, 0) + 1
                    offset += 1
                    continue
                item = {'split': split, 'row': offset, 'label': label, 'bytes': raw, 'sha256': digest}
                seen[digest] = item
                by_class[label].append(item)
                offset += 1
    if any(len(items) < 4 for items in by_class):
        raise ValueError('Una clase tiene menos de cuatro imágenes')
    print('Duplicados exactos omitidos por split y clase:', duplicates, flush=True)
    return by_class, duplicates


def partition(by_class):
    rng = np.random.default_rng(16150)
    ids = rng.permutation(102).tolist()
    classes = {'train': ids[:51], 'validation': ids[51:76], 'test': ids[76:]}
    assert not (set(classes['train']) & set(classes['validation']) or set(classes['train']) & set(classes['test']) or set(classes['validation']) & set(classes['test']))
    subsets = {'train': [], 'validation_query': [], 'validation_gallery': [], 'test_query': [], 'test_gallery': []}
    for name, group in classes.items():
        for label in group:
            rows = by_class[label]
            order = np.random.default_rng(17000 + label).permutation(len(rows))
            chosen = [rows[int(i)] for i in order]
            if name == 'train':
                subsets['train'].extend(chosen)
            else:
                count = min(2 if short else 5, len(chosen)-1)
                subsets[name + '_query'].extend(chosen[:count])
                subsets[name + '_gallery'].extend(chosen[count:])
    hashes = [{x['sha256'] for x in subset} for subset in subsets.values()]
    assert all(hashes[i].isdisjoint(hashes[j]) for i in range(len(hashes)) for j in range(i))
    return classes, subsets


def load_batch(items, flip_rng=None):
    xs = []
    for row in items:
        with Image.open(io.BytesIO(row['bytes'])) as image:
            xs.append(preprocess(image.convert('RGB')))
    x = torch.stack(xs)
    if flip_rng is not None:
        flip = torch.rand(len(x), generator=flip_rng) < .5
        x = torch.where(flip[:, None, None, None], x.flip(-1), x)
    return x.to(device, memory_format=torch.channels_last)


class Embedder(nn.Module):
    def __init__(self):
        super().__init__()
        self.base = resnet18(weights=weights)
        dim = self.base.fc.in_features
        self.base.fc = nn.Identity()
        self.projection = nn.Linear(dim, 128)
        for p in self.base.parameters():
            p.requires_grad_(False)
        for p in self.base.layer4.parameters():
            p.requires_grad_(True)

    def forward(self, x):
        return F.normalize(self.projection(self.base(x)).float(), dim=1)


class ArcHead(nn.Module):
    def __init__(self, classes):
        super().__init__()
        self.weight = nn.Parameter(torch.empty(classes, 128))
        nn.init.xavier_uniform_(self.weight)

    def forward(self, z, y, margin=.3, scale=16.):
        cosine = F.linear(z.float(), F.normalize(self.weight.float(), dim=1)).clamp(-1 + 1e-7, 1 - 1e-7)
        sine = torch.sqrt((1 - cosine.square()).clamp_min(1e-7))
        phi = cosine * math.cos(margin) - sine * math.sin(margin)
        # Extensión monótona para theta > pi - m; en el resto es cos(theta + m).
        phi = torch.where(cosine > math.cos(math.pi - margin), phi, cosine - math.sin(math.pi - margin)*margin)
        chosen = F.one_hot(y, cosine.shape[1]).bool()
        return scale * torch.where(chosen, phi, cosine)


def embed(model, items):
    model.eval()
    vectors = []
    with torch.no_grad():
        for start in range(0, len(items), batch_size):
            x = load_batch(items[start:start + batch_size])
            with torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
                vectors.append(model(x).cpu())
    vectors = torch.cat(vectors)
    if not bool(torch.isfinite(vectors).all()):
        raise FloatingPointError('Embedding no finito')
    return F.normalize(vectors, dim=1)


def score(query, gallery, qitems, gitems):
    # Búsqueda exacta por coseno. La consulta nunca está en la galería.
    similarity = query @ gallery.T
    ranks = torch.argsort(similarity, dim=1, descending=True, stable=True)
    targets = torch.tensor([x['label'] for x in qitems])
    labels = torch.tensor([x['label'] for x in gitems])
    relevant = labels[ranks] == targets[:, None]
    counts = relevant.sum(1)
    if not bool((counts > 0).all()):
        raise ValueError('Consulta sin positivo en la galería')
    ks = (1, 5, 10)
    recalls = {str(k): float(relevant[:, :min(k, relevant.shape[1])].any(1).float().mean()) for k in ks}
    precision = relevant.cumsum(1) / torch.arange(1, relevant.shape[1] + 1)
    per_query_ap = (precision * relevant).sum(1) / counts
    return {'queries': len(qitems), 'gallery': len(gitems), 'recall_at_k': recalls,
            'map': float(per_query_ap.mean())}, ranks, similarity


def evaluate(model, subsets, split):
    queries, gallery = subsets[split+'_query'], subsets[split+'_gallery']
    q, g = embed(model, queries), embed(model, gallery)
    metrics, ranks, similarities = score(q, g, queries, gallery)
    return metrics, ranks, similarities


def thumb(row):
    with Image.open(io.BytesIO(row['bytes'])) as image:
        image = image.convert('RGB')
        image.thumbnail((96, 96))
        output = io.BytesIO()
        image.save(output, format='PNG')
    return 'data:image/png;base64,' + base64.b64encode(output.getvalue()).decode('ascii')


def source(row):
    return {'source_split': row['split'], 'source_row': row['row'], 'class_id': row['label'], 'sha256': row['sha256']}


def verification_pairs(subsets, split, similarity):
    qitems, gitems = subsets[split+'_query'], subsets[split+'_gallery']
    distance = np.clip(1. - similarity.numpy().astype(np.float64), 0., 2.)
    qlabels = np.asarray([x['label'] for x in qitems])
    glabels = np.asarray([x['label'] for x in gitems])
    genuine = qlabels[:, None] == glabels[None, :]
    return {'queries': [source(x) for x in qitems], 'gallery': [source(x) for x in gitems],
            'distances': distance.tolist()}, distance, genuine


def verification_counts(distance, genuine, threshold):
    accepted = distance <= threshold
    return {'genuine_total': int(genuine.sum()), 'impostor_total': int((~genuine).sum()),
            'true_accept': int((accepted & genuine).sum()), 'false_accept': int((accepted & ~genuine).sum()),
            'tar': float((accepted & genuine).sum() / genuine.sum()),
            'far': float((accepted & ~genuine).sum() / (~genuine).sum())}


def select_threshold(distance, genuine, target=.05):
    # Selección solo con pares de validación; la regla acepta distancia <= umbral.
    negatives = np.sort(distance[~genuine])
    allowed = math.floor(target * len(negatives))
    values, counts = np.unique(negatives, return_counts=True)
    cumulative = np.cumsum(counts)
    feasible = values[cumulative <= allowed]
    threshold = float(feasible[-1]) if len(feasible) else float(np.nextafter(values[0], -np.inf))
    assert verification_counts(distance, genuine, threshold)['far'] <= target
    return threshold


def export_gallery(subsets, ranks, sims):
    queries, gallery = subsets['test_query'], subsets['test_gallery']
    # Índices equiespaciados elegidos sin mirar predicciones.
    sample = np.linspace(0, len(queries)-1, min(12, len(queries)), dtype=int)
    output = []
    for q in sample:
        indices = ranks[int(q), :5].tolist()
        row = {'query': {**source(queries[int(q)]), 'image': thumb(queries[int(q)])}, 'neighbors': []}
        for i in indices:
            row['neighbors'].append({**source(gallery[i]), 'image': thumb(gallery[i]),
                                     'cosine': float(sims[int(q), i]),
                                     'relevant': queries[int(q)]['label'] == gallery[i]['label']})
        output.append(row)
    return output


def search_image(model, image_path, gallery, count=5):
    # Misma transformación y embedding que el resto del índice; la salida
    # ordena distancias 1-coseno y excluye todas las copias de bytes exactos.
    raw = Path(image_path).read_bytes()
    digest = hashlib.sha256(raw).hexdigest()
    candidates = [item for item in gallery if item['sha256'] != digest]
    if not candidates:
        raise ValueError('No quedan candidatos tras excluir la consulta')
    q = embed(model, [{'bytes': raw}])
    vectors = embed(model, candidates)
    sims = (q @ vectors.T)[0]
    order = torch.argsort(sims, descending=True, stable=True)[:min(count, len(candidates))]
    return {'query_sha256': digest, 'excluded_exact_copies': len(gallery)-len(candidates),
            'neighbors': [{**source(candidates[int(i)]), 'cosine': float(sims[int(i)]),
                           'cosine_distance': max(0., min(2., 1.-float(sims[int(i)])))} for i in order]}


def main():
    by_class, duplicates = read_images()
    classes, subsets = partition(by_class)
    del by_class
    torch.manual_seed(seed)
    model = Embedder().to(device=device, memory_format=torch.channels_last)
    head = ArcHead(len(classes['train'])).to(device)
    mapping = {label: i for i, label in enumerate(classes['train'])}
    groups = [{'params': [p for p in model.parameters() if p.requires_grad], 'lr': .0001},
              {'params': head.parameters(), 'lr': .001}]
    opt = torch.optim.AdamW(groups, weight_decay=.0001)
    batch_rng = np.random.default_rng(seed+1000)
    flip_rng = torch.Generator().manual_seed(seed+2000)
    points = sorted(set((1, steps//4, steps//2, 3*steps//4, steps)))
    history, best, best_state = [], None, None
    for step in range(1, steps+1):
        model.train()
        for module in model.modules():
            if isinstance(module, nn.modules.batchnorm._BatchNorm):
                module.eval()
        indices = batch_rng.integers(0, len(subsets['train']), size=batch_size)
        items = [subsets['train'][int(i)] for i in indices]
        x = load_batch(items, flip_rng)
        y = torch.tensor([mapping[item['label']] for item in items], device=device)
        opt.zero_grad(set_to_none=True)
        with torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
            loss = F.cross_entropy(head(model(x), y), y)
        if not bool(torch.isfinite(loss)):
            raise FloatingPointError(f'Pérdida no finita en paso {step}')
        loss.backward()
        params = [p for group in opt.param_groups for p in group['params']]
        if any(p.grad is None or not bool(torch.isfinite(p.grad).all()) for p in params):
            raise FloatingPointError(f'Gradiente ausente o no finito en paso {step}')
        opt.step()
        if step in points:
            validation, _, _ = evaluate(model, subsets, 'validation')
            row = {'step': step, 'batch_loss': float(loss.detach()), 'validation': validation}
            history.append(row)
            if best is None or validation['recall_at_k']['1'] > best['validation']['recall_at_k']['1']:
                best = row
                best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
            print('paso', step, 'validación', validation, flush=True)
    model.load_state_dict(best_state)
    selected_validation, _, val_sims = evaluate(model, subsets, 'validation')
    test, ranks, sims = evaluate(model, subsets, 'test')
    val_pairs, val_distances, val_genuine = verification_pairs(subsets, 'validation', val_sims)
    test_pairs, test_distances, test_genuine = verification_pairs(subsets, 'test', sims)
    threshold = select_threshold(val_distances, val_genuine)
    verification = {'target_far': .05, 'threshold_distance': threshold,
                    'validation': verification_counts(val_distances, val_genuine, threshold),
                    'test': verification_counts(test_distances, test_genuine, threshold),
                    'note': 'Umbral elegido en validación: distancias menores o iguales se aceptan. Los pares comparten imágenes; no son observaciones independientes. No es una evaluación biométrica.'}
    # Rangos completos de los positivos permiten recalcular recall@k y mAP.
    labels = torch.tensor([x['label'] for x in subsets['test_gallery']])
    audit = []
    for qi, item in enumerate(subsets['test_query']):
        relevant = labels[ranks[qi]] == item['label']
        audit.append({'query': source(item), 'positive_ranks': (torch.where(relevant)[0]+1).tolist()})
    protocol = {'short': short, 'seed': seed, 'class_seed': 16150, 'class_ids': classes,
        'data_repo': repo, 'data_revision': revision, 'duplicates_removed': duplicates,
        'source_splits': ['train'] if short else ['train', 'validation', 'test'],
        'counts': {k: len(v) for k, v in subsets.items()}, 'steps': steps, 'batch_size': batch_size,
        'weights': 'ResNet18_Weights.IMAGENET1K_V1', 'preprocess': 'resize 128, crop 112, normalización ImageNet',
        'embedding_dim': 128, 'margin': .3, 'scale': 16., 'batchnorm': 'estadísticas congeladas',
        'trainable': 'layer4 y proyección; cabeza angular solo durante entrenamiento',
        'selection': 'máximo recall@1 en clases de validación, primer empate',
        'retrieval': 'coseno exacto; recall@k es proporción de consultas con al menos un positivo entre k; mAP media por consulta',
        'limitations': 'categorías de flores, no personas; separación por bytes exactos, no descarta casi duplicados ni solapamiento con ImageNet',
        'gpu': torch.cuda.get_device_name(device), 'torch': str(torch.__version__), 'cuda': str(torch.version.cuda)}
    result = {'protocol': protocol, 'history': history, 'best_step': best['step'],
              'selected_validation': selected_validation, 'test_after_selection': test,
              'test_ranking_audit': audit, 'verification': verification}
    query_path = os.environ.get('ORYON_QUERY_IMAGE')
    if query_path:
        result['external_query'] = search_image(model, query_path, subsets['test_gallery'])
        print('consulta externa:', json.dumps(result['external_query'], ensure_ascii=False), flush=True)
    gallery = {'protocol': protocol, 'selected_step': best['step'], 'items': export_gallery(subsets, ranks, sims)}
    pairs = {'protocol': protocol, 'selected_step': best['step'], 'verification': verification,
             'validation': val_pairs, 'test': test_pairs}
    out = Path(os.environ.get('ORYON_METRIC_OUTPUT', 'metric-retrieval.json'))
    imgout = Path(os.environ.get('ORYON_METRIC_GALLERY_OUTPUT', 'metric-gallery.json'))
    pairsout = Path(os.environ.get('ORYON_METRIC_PAIRS_OUTPUT', 'metric-pairs.json'))
    out.write_text(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
    imgout.write_text(json.dumps(gallery, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
    pairsout.write_text(json.dumps(pairs, ensure_ascii=False, separators=(',', ':'), allow_nan=False), encoding='utf-8')
    print('test tras selección:', test, 'verificación:', verification, 'archivos:', out, imgout, pairsout, flush=True)
    del model, head, opt
    gc.collect()
    torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofTwo forms of a margin
Prove: For unit embeddings prove the relationship between squared Euclidean distance and cosine, and translate a distance margin α into a cosine inequality.
0
Let a, p and n be real unit vectors and α positive. Use squared distances, not unsquared distances.

Step 1 of 2. What results from expanding the squared norm between a and p?

CodeVectorized batch-hard mining
Implement batch_hard_triplet_loss(emb, labels, margin) with NumPy and squared Euclidean distances. For each anchor with another positive and at least one negative, choose the farthest positive and nearest negative, calculate max(0, d²(ap)−d²(an)+margin) and return the mean over valid anchors. If there are no valid anchors return 0. Do not include the point itself as a positive.
import numpy as np

def batch_hard_triplet_loss(emb, labels, margin):
  pass
Shift+Enter to run
NumericA margin in radians
In ArcFace, calculate the correct-class logit for s=64, margin 0.5 radians and angle 60°. Give the result to three decimal places.
QuizAn access control
The cost of accepting an impostor is high. Which evaluation best informs threshold choice?
QuizNew identities
An embedding scores very well on new images of the same people used in training. What can be concluded about unseen people?
QuizNeighbor order
When do descending cosine and ascending Euclidean distance guarantee the same candidate order?
QuizA batch without candidates
An implementation omits anchor-positive pairs when it finds no semi-hard negative in the batch. Displayed loss is zero. What can you say?
Key idea
Learning a distance requires defining relevance, how examples are selected and which classes stay outside training. An aggregate metric does not replace evaluation protocol or error analysis.