ConvNeXt Coin Retrieval

A truncated ConvNeXt‑Tiny trained as a metric‑learning embedding for ancient‑coin specimen retrieval and pairwise "same coin?" verification. Given a coin image it produces a 512‑dim L2‑normalized vector; two images of the same physical coin side land close in cosine space, different coins land far apart.

Trained on provenanced Roman Republican coin data: scanned die‑catalogue images, with a domain augmentation calibrated on coins of documented provenance (see Provenance‑calibrated MixStyle below). Evaluated across a domain gap onto photographs and print–scan reproductions.

For background on this work, see ICMLA paper accepted on the Recovering Sawhill blog.

Paper: N. R. Sprague, J. B. Forsyth, T. Schonbrun, and D. D. Atre, "Metric Learning for Ancient Coin Identification," in 2026 25th International Conference on Machine Learning and Applications (ICMLA), Rochester, MI, USA, 2026, pp. 546–553, doi: 10.1109/ICMLA69890.2026.00082.

  • Backbone: torchvision.models.convnext_tiny, features truncated after the 14×14×384 stage (index 6 of .features), so relief / wear / inscription detail that global pooling would destroy is preserved.
  • Head: 1×1 conv 384→32 → flatten (6272‑d) → Linear(6272, 512) → BatchNorm1d(512).
  • Output: 512‑d. The raw model output is BatchNorm‑scaled, not unit norm — you must L2‑normalize it yourself before comparing (the standalone class below does this for you).
  • Loss (training only): ArcFace additive‑angular‑margin softmax, one class per coin identity. The classifier head is not part of this checkpoint.

Files in this repo

File What it is
convnext_coin_embedding.pth Model weights (PyTorch state_dict)
config.json Architecture, preprocessing, and benchmark numbers in machine‑readable form

Preprocessing (exact — match this or results degrade)

import torchvision.transforms as T

IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD  = [0.229, 0.224, 0.225]

preprocess = T.Compose([
    T.Resize((224, 224)),                       # NON-aspect-preserving square resize — intentional, matches training
    T.ToTensor(),                               # -> float32 in [0, 1], CHW
    T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
])
# Always: Image.open(path).convert("RGB") first.

Details that matter:

  • Square resize to 224×224. Training resized every image to a literal 224×224 (aspect ratio not preserved). Do the same. Do not letterbox, do not center‑crop.

  • RGB. Convert palette / grayscale / RGBA inputs to RGB.

  • Background. Training applied a near‑white cleanup before resize: any pixel with R,G,B all > 250 was set to pure white ((255,255,255)). This is a denoise for clean catalogue scans, not a foreground segmenter — it does nothing to dark or textured photo backgrounds. The published benchmark numbers below were computed without even this step on the gallery side, so it is optional. If your images have bright near‑white borders / JPEG haze, applying it will match training slightly better:

    import numpy as np
    from PIL import Image
    
    def near_white_to_white(img: Image.Image, thr: int = 250) -> Image.Image:
        a = np.array(img.convert("RGB"))
        m = (a[..., 0] > thr) & (a[..., 1] > thr) & (a[..., 2] > thr)
        a[m] = 255
        return Image.fromarray(a)
    
  • No test‑time augmentation, no TTA flips. Single forward pass.


Standalone usage (torch + torchvision only)

Copy this class verbatim. It is byte‑for‑byte equivalent to the training model (verified: max abs difference 0.0 vs. the reference loader).

import torch, torch.nn as nn, torch.nn.functional as F
from torchvision.models import convnext_tiny
from huggingface_hub import hf_hub_download
from PIL import Image
import torchvision.transforms as T

class ConvNeXtCoinEmbedding(nn.Module):
    """Truncated ConvNeXt-Tiny -> 512-d L2-normalized coin embedding."""
    def __init__(self, reduced_channels: int = 32, embedding_size: int = 512):
        super().__init__()
        feats = list(convnext_tiny(weights=None).features.children())[:6]  # through 14x14x384
        self.features_until_14x14 = nn.Sequential(*feats)
        self.conv1x1 = nn.Conv2d(384, reduced_channels, kernel_size=1)
        self.flatten = nn.Flatten(start_dim=1)
        self.embedding_layer = nn.Linear(reduced_channels * 14 * 14, embedding_size)
        self.normalize = nn.BatchNorm1d(embedding_size)

    def forward(self, x):
        x = self.features_until_14x14(x)
        x = self.conv1x1(x)
        x = self.flatten(x)
        x = self.embedding_layer(x)
        x = self.normalize(x)
        return F.normalize(x, dim=1)   # <-- L2-normalized; cosine == dot product

# --- load ---
device = "cuda" if torch.cuda.is_available() else "cpu"
weights = hf_hub_download("COIN-Research-Group/convnext-coin-embedding",
                          "convnext_coin_embedding.pth")
model = ConvNeXtCoinEmbedding().to(device).eval()
model.load_state_dict(torch.load(weights, map_location=device, weights_only=True))

# --- preprocess ---
preprocess = T.Compose([
    T.Resize((224, 224)),
    T.ToTensor(),
    T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])

@torch.no_grad()
def embed(paths, batch_size: int = 128) -> torch.Tensor:
    out = []
    for i in range(0, len(paths), batch_size):
        batch = torch.stack([preprocess(Image.open(p).convert("RGB"))
                             for p in paths[i:i + batch_size]]).to(device)
        out.append(model(batch).cpu())          # already L2-normalized
    return torch.cat(out)

# --- compare two images ---
e = embed(["coinA.jpg", "coinB.jpg"])
cosine = float(e[0] @ e[1])                      # in [-1, 1]; higher == more similar

torch>=2.0, torchvision>=0.15, huggingface_hub, pillow, numpy. GPU optional. convnext_tiny(weights=None) builds the graph without downloading ImageNet weights — the checkpoint fully overwrites them.


Pairwise "same coin?" verification — calibrated thresholds

This is the setting for "do these two images show the same coin?". Decision rule:

same_coin = (cosine_similarity(embed(imgA), embed(imgB)) >= THRESHOLD)

Compare like with like: obverse to obverse, reverse to reverse. An obverse and a reverse of the same physical coin are not expected to match. If you have both sides, score each side pair and combine (e.g. require both ≥ threshold, or average).

Two calibrations were run (cosine of L2‑normalized embeddings, preprocessing exactly as above, no query expansion):

A. Reproduction‑variant regime — digital renders & print–scan copies of the same photo

Sawhill dataset: 309 coin‑sides × 12 renderings, ~6.9 M pairs.

genuine (same side) impostor (different side)
mean 0.595, sd 0.115, p5 0.404, min 0.176 mean 0.112, sd 0.073, p95 0.235, p99 0.293

EER ≈ 0.62 % at cosine ≈ 0.31.

B. Cross‑source regime — the same coin photographed by two different auction houses

772 provenanced coin‑sides, each photographed independently in two different sales; impostors are different coins, same side.

genuine (same coin, 2 houses) impostor (different coin, same side)
mean 0.546, sd 0.161, p5 0.294, p1 0.139 mean 0.047, sd 0.072, p95 0.171, p99 0.248, p99.9 0.357

EER ≈ 2.1 % at cosine ≈ 0.21.

Operating points (regime B — use this one for real‑world cross‑source matching)

threshold FAR (different coins accepted) FRR (same coin missed) use when
0.30 0.33 % 5.7 % balanced default
0.35 0.12 % 9.7 % precision‑leaning (recommended for auto‑merge)
0.40 0.04 % 16 % high precision, manual review of near‑misses
0.25 0.95 % 2.9 % recall‑leaning (candidate generation)

Recommendation for a numismatic dedup / matching tool: flag a pair as same coin at cosine ≥ 0.35, and send 0.25 – 0.35 to human review. Below 0.25, treat as different. Regime A (screenshots / catalogue re‑scans of one photo) tolerates a higher bar (~0.40).

Verification caveats

  • Visually identical different coins read as "same." Coins struck from the same die pair, or the same high‑volume type in similar condition, can exceed any threshold (impostor max ≈ 0.997 in regime B). The model measures visual identity, not provenance. A high score means "these images are of the same or an indistinguishable coin," which for die studies is often what you want, but is not proof of one specimen.
  • The regime‑B impostor tail is slightly inflated: a few "different" lots are likely the same coin relisted.
  • Thresholds are for this checkpoint + this preprocessing. Changing the resize, skipping L2‑normalization, or using a different checkpoint invalidates them.
  • Both calibration sets are Roman Republican silver. Bronze, gold, Greek, or heavily toned/encrusted material is out of distribution — re‑calibrate on a held‑out sample of your own catalogue if you can.
  • These are image‑pair rates. Aggregating multiple images per coin (both sides, multiple photos) lowers both error rates substantially.

Retrieval benchmark

  • Query: all Sawhill reproduction variants, 3,708 images = 309 coin‑sides × (4 digital + 8 print–scan) renderings.
  • Gallery: the 3,708 query images + a fixed pool of 5,921 held‑out distractor coins = 9,629 images.
  • Positives: a query's positives are the other 11 renderings of its coin‑side (leave‑one‑out) → 40,788 query–target pairs.
  • Metrics: single‑match Recall@1/5/10 + multi‑positive mAP.
Configuration R@1 R@5 R@10 mAP
DINOv3 ViT‑L/16 zero‑shot (reference) 41.5 % 55.3 % 61.7 % 0.592
This model 95.3 % 98.2 % 99.0 % 0.984
This model + AQE k=5 99.1 % 99.7 % 99.9 % 0.997

Cross‑source retrieval

Matching the same physical coin across auction houses, 1,779 queries / 772 groups / ~31 k gallery: R@1 88.5 %, mAP 0.919 (obverse 86.1 %, reverse 90.9 %). This is the harder, more realistic task and the number to cite for provenance search.


What is provenance‑calibrated MixStyle?

Standard MixStyle regularizes by swapping per‑channel feature statistics (mean, std) between two random images in a batch — generic, arbitrary style noise. Here the random mix is replaced with style shifts sampled from a Gaussian mixture fit on provenanced coin pairs: the same coins photographed independently by different auction houses. The augmentation therefore reproduces the actual scan ↔ auction‑photo appearance gap the model meets at inference, rather than noise. Applied at ConvNeXt stages 1/3/5 with p=0.5, disabled for the last 2 of 20 epochs.


Alpha Query Expansion (retrieval only)

Inference‑time re‑ranking for multi‑image galleries: replace each query embedding with a weighted blend of itself and its top‑k gallery neighbours (k=5), then re‑rank. No retraining. Irrelevant to pairwise verification and to single‑image galleries.

import torch.nn.functional as F

def alpha_query_expand(query_embs, gallery_embs, k=5, alpha=1.0):
    sims = query_embs @ gallery_embs.T
    vals, idx = sims.topk(k, dim=1)
    w = F.softmax(vals * alpha, dim=1).unsqueeze(-1)
    expanded = query_embs + (w * gallery_embs[idx]).sum(dim=1)
    return F.normalize(expanded, dim=1)

Training summary

Data Provenanced Roman Republican coin data: scanned die‑catalogue images (99 identities), with within‑identity views synthesized by an augmentation pipeline (random resized crop, affine, perspective, colour jitter, Gaussian blur, random grayscale)
Preprocess square resize 224×224 → near‑white→white cleanup → white‑background composite → ImageNet normalize
Loss ArcFace over L2‑normalized 512‑d embedding
Domain reg. Provenance‑calibrated MixStyle, stages 1/3/5, p=0.5, GMM style sampler fit on provenanced cross‑source pairs, off for last 2 epochs
Schedule 20 epochs, batch 128, Adam lr 1e‑4, seed 42, best‑validation‑kNN checkpoint
Hardware single RTX A6000

Limitations

  • Domain: Roman Republican silver denarii, catalogue scans + reproductions. Bronze / gold / Greek / provincial / heavily worn material is out of distribution.
  • Checkpoint selection was on an in‑domain validation proxy; for a cross‑source deployment a cross‑source validation slice would be a better selector.
  • Square resize distorts non‑circular flans / fragments.
  • Not a substitute for physical examination, weight/die‑axis metadata, or provenance research.

Related

Downloads last month
38
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support