Ternary ArcFace R100
A 38.2 MB research checkpoint derived from the official InsightFace MS1MV2
ArcFace R100: 6.83 times smaller than the exact converted FP32 checkpoint,
with 80.16% of model parameters represented by symmetric ternary codes.
The remaining tensors are stored in FP16 (and integer buffers in int64).
This release is the fixed distill_codes_g64 candidate, not a model trained
from scratch.
Pretrained weights are for non-commercial research only. The MIT license for inference code does not grant commercial rights to these weights. See LICENSE, LICENSE-CODE, and InsightFace's original licensing statement.
Measured verification accuracy
These are measurements of the fixed research checkpoint and the exact original checkpoint converted and independently validated against MXNet. The release removes local paths from the packed file's metadata. The complete tensor payload and inference descriptors are byte-identical to the measured checkpoint; independent loader checks reproduce its outputs bit for bit. The file checksum changes because its metadata changed. evaluation.json records both checksums and the payload equivalence proof. Accuracy is percent; ± is population standard deviation across ten folds.
| Benchmark | Original FP32 | Released ternary | FP32 minus ternary, percentage points |
|---|---|---|---|
| LFW | 99.7667 ± 0.2809 | 99.7833 ± 0.2693 | -0.0167 |
| CFP-FP | 98.2286 ± 0.5721 | 97.5143 ± 0.8111 | 0.7143 |
| AgeDB-30 | 98.2333 ± 0.7157 | 97.6167 ± 0.9748 | 0.6167 |
| CALFW | 96.1000 ± 1.0960 | 95.7500 ± 1.1625 | 0.3500 |
| CPLFW | 92.7833 ± 1.4511 | 92.0833 ± 1.1932 | 0.7000 |
Each fold chooses its squared-unit-L2 threshold on the other nine folds:
grid [0, 4), step 0.01, strict <, no PCA. Embeddings sum **raw original
and horizontal-flip outputs in float64 before L2 normalization**.
The evaluation uses immutable pixels from the original MXNet RGB decoder.
Numeric fold evidence and dataset hashes are in evaluation.json.
The predefined good accuracy limits are met on LFW/CFP-FP/AgeDB-30; the stricter excellent limits remain unmet. The small LFW increase is one pair relative to FP32 and does not establish superiority. CALFW and CPLFW were previously unused in this project but share LFW identities; they do not establish generalization to entirely new people. No benchmark faces or labels entered compression fitting or checkpoint selection. Exact content checks found zero overlap with retained calibration/diagnostic faces; transformed copies and identity overlap with original pretraining are not ruled out.
Install and load
Python 3.10 or newer. The wheel contains the inference code and dependencies metadata; the packed model is downloaded separately and hash-checked.
python -m pip install "https://huggingface.co/shlummi/arcface-r100-ternary/resolve/main/ternary_arcface_inference-0.3.0-py3-none-any.whl"
import torch
from ternary_arcface.hub import TernaryArcFace, load_aligned_face
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
model = TernaryArcFace.from_pretrained(
"shlummi/arcface-r100-ternary",
device="cpu", # use "cuda" with a compatible PyTorch/CUDA installation
)
pixels = torch.stack([
load_aligned_face("aligned_face_a.png"),
load_aligned_face("aligned_face_b.png"),
])
embeddings = model.embed(pixels) # shape [2, 512], float64, unit length
cosine = (embeddings[0] * embeddings[1]).sum().item()
print(cosine)
Inputs must be already aligned 112x112 RGB crops, supplied as raw uint8
or raw floating-point pixels in [0, 255]. The model performs normalization
internally. load_aligned_face checks crop size; it does not detect, align,
or resize faces. The model is a face embedding network, not a face detector.
Use your own consented inputs and a separately validated application threshold.
No universal verification threshold or production suitability is claimed.
For repeatable remote loading, pass revision="<Hub commit SHA>". To use a
complete downloaded release offline, pass its directory to from_pretrained.
You can also run example.py:
python example.py --model . --images aligned_face_a.png aligned_face_b.png --output embeddings.npy
model(pixels) returns raw features; model.embed(pixels, flip=False)
normalizes a single view. The reported five benchmark numbers use flip testing.
The JPEG decoder in a consumer pipeline may differ from the locked benchmark
decoder, so this example is not a substitute for reproducing the benchmark.
What is compressed
| Quantity | Exact value |
|---|---|
| Total model parameters | 65,156,160 |
| Ternary parameters | 52,228,096 (80.1583%) |
| Packed model file | 38,201,664 bytes |
| Exact converted FP32 model | 260,988,528 bytes |
| Codes + FP16 scales per ternary weight | 1.850006 bits |
| Entire model file per model parameter | 4.690475 bits |
| SHA256 of model.tarc | 0b78825277f92c864564ac738774473a9ab8a49d5a28c75eb504167e85c4668c |
Base-3 packing stores five ternary digits per byte. Group-64 nonnegative FP16 scales are included in the 1.8500-bit figure. The whole-file figure also includes dense exclusions, buffers, and metadata. First convolution and final FC weights are dense. There are no optimizer latents or floating shadow copies of ternary weights in the model file.
The default backend="unpacked" expands weights to FP32 and uses PyTorch
Conv2d/Linear. Version 0.2.0 adds backend="packed-cuda", which keeps the
ternary convolution weights in base-3 bytes with FP16 scales, and the excluded
convolution/FC weights in FP16 during execution. Normalization remains FP32.
The CUDA kernels decode at most a 32x32 weight tile per thread block into shared
memory, with no complete floating weight matrix or im2col allocation.
model = TernaryArcFace.from_pretrained(
"shlummi/arcface-r100-ternary", device="cuda", backend="packed-cuda"
)
embeddings = model.embed(pixels)
Version 0.3.0 also adds backend="packed-cuda-fast". It keeps the same
38.38 MB of model tensors, temporarily decodes one convolution layer to FP16
(maximum 4.72 MB), uses channels-last cuDNN convolutions and cuBLAS for the FC,
and replays one CUDA graph. Activations use mixed FP16; BatchNorm parameters
and statistics remain FP32 and the FC accumulates and returns FP32. This is
an explicit speed/precision tradeoff. The original packed-cuda backend
remains available for its higher precision behavior.
model = TernaryArcFace.from_pretrained(
"shlummi/arcface-r100-ternary", device="cuda", backend="packed-cuda-fast"
)
The fast backend retains at most one graph shape per model. A different batch
size replaces the previous graph, with first-call warmup/capture cost. Pass
cuda_graph=False for eager fast execution when batch sizes change frequently.
Outputs are cloned so later original/flip or concurrent stream calls cannot
overwrite returned features. CUDA graph pools retain physical memory even
when their intermediate tensors are logically inactive.
The packed backend requires CUDA PyTorch with NVRTC, a CUDA Toolkit providing
mma.h/cuda_fp16.h, and an NVIDIA GPU with compute capability 7.0 or newer.
It was tested on native Windows 10 with PyTorch 2.8.0+cu128, bundled NVRTC 12.8,
CUDA 12.1 headers, and an RTX 5070 Ti. Other platforms/GPUs are unverified.
It compiles on first load and needs no host C++ compiler or extra Python package.
CPU inference continues to use the unpacked backend.
| Measured quantity | Unpacked FP32 | Accurate packed CUDA | Fast packed CUDA |
|---|---|---|---|
| Resident model tensors | 260.90 MB | 38.38 MB | 38.38 MB |
| Peak allocated GPU bytes including capture, batch 1 | 324.54 MB | 48.28 MB | 50.06 MB |
| Peak reserved GPU bytes after warmup, batch 1 | 383.78 MB | 65.01 MB | 90.18 MB |
| Forward latency, batch 1 | 12.25 ms | 19.02 ms | 2.54 ms |
| Peak allocated GPU bytes including capture, batch 32 | 657.06 MB | 351.60 MB | 209.69 MB |
| Peak reserved GPU bytes after warmup, batch 32 | 864.03 MB | 371.20 MB | 266.34 MB |
| Forward latency, batch 32 | 26.92 ms | 91.52 ms | 13.65 ms |
Memory uses decimal MB. Peak GPU allocation includes model, inputs, activations, and temporary workspaces tracked by PyTorch; it excludes CUDA context/code, driver memory, and other processes. Timing uses one network view, resident GPU inputs, five warmups, twenty synchronized iterations, and fresh processes for each backend. Image decoding, transfers, and horizontal-flip augmentation are outside the forward timing. The original packed implementation saves memory with slower forward execution. The fast option improves speed, with slightly different accuracy below. Graph capture peaks are included; reserved memory counts the retained graph pool. Replay-only allocated bytes omit its inactive blocks and must not be treated as complete runtime memory. Driver/context memory and other processes remain outside these measurements. The fast option uses more memory than the original packed option at batch 1 and less at batch 32 in this test.
The default packed activation precision split represents an FP32 input as two
FP16 parts and accumulates in FP32 using Tensor Cores. This is an approximation;
its outputs are close to FP32, rather than bitwise identical. The optional
packed_precision="half" uses one FP16 part and has not received the complete
five-benchmark validation. These kernels use floating arithmetic.
| Benchmark | Unpacked ternary accuracy (%) | Fast packed CUDA accuracy (%) |
|---|---|---|
| LFW | 99.7833 | 99.7833 |
| CFP-FP | 97.5143 | 97.5143 |
| AgeDB-30 | 97.6167 | 97.6167 |
| CALFW | 95.7500 | 95.7500 |
| CPLFW | 92.0833 | 92.0167 |
The fast precision/layout policy passed numerical QA on 192 retained CASIA diagnostic faces before its benchmark accuracy run. Four benchmark means match the original ternary model; CPLFW loses 0.0667 percentage points (four of 6,000 pairs). The fixed acceptance tolerance was 0.10 percentage points. No runtime settings were changed in response to benchmark accuracy.
The packed checks use the same locked pixels, folds, and flip protocol, with no weight updates or benchmark fitting. runtime.json records exact resident bytes, allocation peaks, timing, folds, and embedding comparisons.
Method and reproducibility
The source checkpoint was the official legacy MXNet model-r100-ii, trained
on MS1MV2, converted to the official iResNet100 topology [3, 13, 30, 3].
The adapter preserves legacy normalization, BN epsilon 2e-5, fixed final
BN gamma, and 512-dimensional output. Compression uses grouped activation
initialization, joint residual-block reconstruction, and a fixed 600-step
teacher embedding refinement on separately sampled CASIA-WebFace faces.
BN, PReLU, biases, first convolution, and final FC stay frozen.
The final refinement uses 960 fitting faces and 64 calibration selection faces, batch 8, Adam learning rate 0.0003, seed 20261001, and audits every 50 steps. The selection faces were used during earlier block fitting and are not an independent holdout. A separate 192-face diagnostic subset stayed outside fitting and selection. All 102 packed ternary tensors and preserved dense tensors passed bitwise export checks. Both fixed refinement candidates and unsuccessful earlier experiments are documented in the research snapshot.
research-source.zip contains the research scripts,
methods, tests, configs, reports, and numeric evidence, including source
attribution and the recorded unsuccessful candidates. Data and model files
must be obtained separately under their original terms to rerun training or
verification. release.json records file hashes and provenance.
Public evidence copies replace local absolute paths with relative paths or
generic local-home placeholders, and test reports use a generic hostname.
Numeric measurements and original evidence hashes are preserved; the release
inventory records which archived files were sanitized. Original local research
records remain unchanged.
The installable source in src/ reuses the tested packed reader and R100
architecture. It is not a Transformers AutoModel checkpoint.
Uses and limitations
Intended for non-commercial research in face embedding compression and verification. The five pair-accuracy benchmarks do not establish demographic fairness, robustness to arbitrary cameras or adversarial inputs, liveness, or suitability for consequential identity decisions. No demographic audit or evaluation at deployment-specific false accept rates was performed. Use of biometric data requires appropriate consent and applicable permissions.
Attribution
Released by shlummi. Base architecture and pretrained model: InsightFace / deepinsight. ArcFace: Deng et al., CVPR 2019. The original model provenance and checksum are in config.json and manifest.json. Vendored source retains its original notices in THIRD_PARTY_NOTICES.md.
- Downloads last month
- 13