Back to paper library
Paper notesarXiv 2015CVPR 2015

FaceNet

No Face Slips Through the Net

Original paper

FaceNet: A Unified Embedding for Face Recognition and Clustering

Paper authors

Florian Schroff · Dmitry Kalenichenko · James Philbin

Publication
CVPR 2015Conference
First submitted to arXiv
arXiv:1503.03832
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{facerecognitionfacenet2015,
  title = {{FaceNet: A Unified Embedding for Face Recognition and Clustering}},
  author = {Florian Schroff and Dmitry Kalenichenko and James Philbin},
  year = {2015},
  eprint = {1503.03832},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1503.03832}
}
On this page

Feed two face photos into FaceNet, and out comes a single number between 0 and 4.

Six face photos arranged in three rows and two columns. Each row holds two photos of the same person under a different pose and lighting, with their distance marked between them: 1.04, 0.78 and 0.99 from top to bottom. Distances between different people are marked between the rows: between rows one and two, 1.22 in the left column and 1.33 in the right; between rows two and three, 1.33 on the left and 1.26 on the right.
Original Figure 1, Schroff et al., from PDF page 1, arXiv license, scholarly quotation.

Each row in this figure is one person, with the left and right photos taken under a different pose and lighting. The number sitting between the two photos is the distance between two photos of the same person: 1.04, 0.78 and 0.99. The numbers written below the photos are the distances between two different people stacked in the same column: 1.22, 1.33, 1.33 and 1.26. According to the paper, with the threshold set at 1.1, all seven comparisons come out right.

This is what face verification does. Given two faces, it asks whether they belong to the same person, which is also called 1:1 matching. Unlocking a phone with your face is this kind: the face in front of the camera is compared only with the one face the owner enrolled.

Identification is 1:N. Say a company's door access system has 500 employees enrolled. Everyone coming through the door has to be compared against all 500 people to find the closest one, and that closest distance still has to fall below the threshold; otherwise the person is treated as a stranger. The third use is clustering: an album of several thousand photos without a single name, where the job is to sort each person's photos into the same pile.

FaceNet's claim is that all three tasks can share one and the same thing. As long as every face can be turned into a point in some space, with the points of the same person close together and the points of different people far apart, verification is just comparing a distance against a threshold, identification is finding the nearest neighbor (k-NN), and clustering goes straight to k-means or agglomerative clustering.

That number from 0 to 4 comes from FaceNet turning a face xx into a 128-dimensional vector f(x)f(x) and then rescaling its length to 1, which is L2 normalization, ∥f(x)∥2=1\|f(x)\|_2=1. All faces therefore land on the 128-dimensional unit hypersphere, and this vector is the face's embedding, often also called its feature vector.

The squared Euclidean distance between two unit vectors uu and vv expands like this:

∥u−v∥22=∥u∥2+∥v∥2−2 u⊤v=2−2cos⁡θ\begin{aligned} \|u-v\|_2^2&=\|u\|^2+\|v\|^2-2\,u^\top v\\ &=2-2\cos\theta \end{aligned}

θ\theta is the angle between the two vectors, and cos⁡θ\cos\theta is their cosine similarity. When they point in exactly the same direction, θ=0\theta=0 and the distance is 0; when they point in exactly opposite directions, θ=180∘\theta=180^\circ and the distance is 4. Converted back, the threshold of 1.1 in Figure 1 is cos⁡θ=0.45\cos\theta=0.45, an angle of about 63 degrees.

So after L2 normalization, squared distance and cosine similarity are two scales on the same ruler. FaceNet talks in distances, and most of the later margin-based losses switched to talking in angles, but they all describe positions on the same sphere.

All three authors of this paper were at Google. They trained on 100 to 200 million faces of about 8 million people, compressed each face into 128 numbers, and reached 99.63% on LFW, the most widely used face-verification benchmark at the time.

Defining the Problem

Borrowing features from a classifier's middle layer

Before FaceNet, the mainstream approach to deep face recognition was to train a classifier first.

Taigman et al.'s DeepFace aligns faces to a generic 3D face shape and then trains a network to tell apart more than four thousand identities; Sun et al.'s DeepID2+ trains with a classification loss and a verification loss together. After training, the final classification layer is thrown away, and the output of some earlier layer (the bottleneck layer) is taken as the representation of the face.

This has two problems. The classifier learns "which person in the training set is this face," yet at test time it faces people it has never seen, so all you can do is hope that what the bottleneck layer learned is general enough. On top of that, this layer usually has a thousand or more dimensions, followed by a whole chain of further processing. DeepID2+ uses 25 networks, each looking at a different region of the face, for 50 outputs in total from the original and flipped images, then PCA to reduce dimensionality and Joint Bayesian to compute similarity, reaching a best of 99.47% on LFW; DeepFace's best of 97.35% is also an ensemble of three networks, with the distances finally combined by a nonlinear SVM.

The authors name the downsides of this approach as "its indirectness and its inefficiency." PCA is just a linear transformation, which the network could learn on its own by adding one more layer. Rather than borrowing features from the middle of a classifier, make the network's output itself that 128-dimensional embedding and train it directly.

Which loss trains a distance

If the goal is "same person close, different people far," the most direct formulation is a pairwise loss. Two faces of the same person get their distance pulled in; two faces of different people get their distance pushed beyond some margin. DeepID2+'s verification loss belongs to this family.

The authors argue that such a loss encourages all photos of one person to crowd onto a single point in the embedding space. A person's profile and frontal shots, photos with glasses, photos at twenty and at forty would all have to collapse into one point, which asks too much of the network. What the authors wanted was a relative constraint, under which the photos of one person may spread out into a region (the paper uses the word manifold), as long as each of them is closer to that person's other photos than to any outsider. The paper also admits that it never actually compared against a pairwise loss.

That is the starting point of the triplet loss. The trouble that follows is how to pick groups of three when the training set holds over a hundred million faces.

Solving the Problem

Triplet loss

A batch of images goes into a deep CNN, the output is L2-normalized into embeddings, and during training a triplet loss is attached on top. The network itself is treated as a black box, and two architectures get swapped in later.

Left: the blue anchor is closer to the red negative than to the green positive; in the middle, a curved arrow labeled LEARNING; right: after learning, the anchor sits close to the positive and the negative has been pushed farther away.
Original Figure 3, Schroff et al., from PDF page 3, arXiv license, scholarly quotation.

A triplet consists of three faces. The anchor xiax_i^a is one photo of some person, the positive xipx_i^p is another photo of the same person, and the negative xinx_i^n is anyone else. The authors require that the squared distance from the anchor to the positive, plus a margin α\alpha, still be smaller than the squared distance from the anchor to the negative:

∥f(xia)−f(xip)∥22+α<∥f(xia)−f(xin)∥22\begin{aligned} &\|f(x_i^a)-f(x_i^p)\|_2^2+\alpha\\ &\quad<\|f(x_i^a)-f(x_i^n)\|_2^2 \end{aligned}

From here on, the two squared distances are abbreviated as dapd_{ap} and dand_{an}. The penalty is however much the constraint is violated, and 0 if it isn't violated; summing the penalties over all triplets gives the loss to minimize:

L=∑iN[ dap−dan+α ]+L=\sum_{i}^{N}\big[\,d_{ap}-d_{an}+\alpha\,\big]_+

[⋅]+[\cdot]_+ is max⁡(⋅,0)\max(\cdot,0), and NN is the number of triplets. The paper sets the margin to α=0.2\alpha=0.2.

To put numbers on it, suppose the squared distance between the anchor and the positive is dap=0.8d_{ap}=0.8, an angle of about 53 degrees. To satisfy the constraint, the negative's distance has to reach at least 0.8+0.2=1.00.8+0.2=1.0, which is 60 degrees. Now try three different negatives:

  • n1n_1 is at distance 0.6, closer than the positive; its loss is 0.8−0.6+0.2=0.40.8-0.6+0.2=0.4.
  • n2n_2 is at distance 0.9, farther than the positive but not yet at 1.0; its loss is 0.10.1.
  • n3n_3 is at distance 1.5, already beyond the margin; its loss is 0.
Line chart. The horizontal axis is the squared distance from the anchor to the negative, from 0 to 2; the vertical axis is the triplet loss, from 0 to 1. With an anchor–positive distance of 0.8 and a margin of 0.2, the loss falls in a straight line from 1.0 at distance 0 to 0 at distance 1.0, and stays at 0 after that. From 0 to 0.8 is the red "Hard" band, from 0.8 to 1.0 the orange semi-hard band, and above 1.0 the green "Easy: loss 0" band. Three points: n1 at 0.6 with loss 0.4; n2 at 0.9 with loss 0.1; n3 at 1.5 with loss 0.
Drawn for this note from equations (1), (3) and (4) of the paper, with the margin of 0.2 taken from Section 3.3; the three negative distances are this note's own example.

How does the network change in the right direction? Take the loss of a single triplet, Li=dap−dan+αL_i=d_{ap}-d_{an}+\alpha, and drop the subscript ii below. For the anchor, the derivative of dapd_{ap} with respect to f(xa)f(x^a) is 2(f(xa)−f(xp))2\big(f(x^a)-f(x^p)\big) and that of dand_{an} is 2(f(xa)−f(xn))2\big(f(x^a)-f(x^n)\big); subtract the two and f(xa)f(x^a) itself cancels out. When LiL_i is greater than 0, the gradients for the three embeddings are:

∂Li/∂f(xa)=2(f(xn)−f(xp))∂Li/∂f(xp)=2(f(xp)−f(xa))∂Li/∂f(xn)=2(f(xa)−f(xn))\begin{aligned} \partial L_i/\partial f(x^a)&=2\big(f(x^n)-f(x^p)\big)\\ \partial L_i/\partial f(x^p)&=2\big(f(x^p)-f(x^a)\big)\\ \partial L_i/\partial f(x^n)&=2\big(f(x^a)-f(x^n)\big) \end{aligned}

Moving along the negative gradient, the positive moves toward the anchor, the negative gets pushed away, and the anchor itself moves in the direction of "closer to the positive, farther from the negative," which is exactly the motion Figure 3 draws. These gradients then pass back through the L2 normalization layer into the network, so the points always stay on the sphere.

A triplet like n3n_3 has zero loss and zero gradient, yet it still costs a full forward pass over three images. After training for a while, the vast majority of randomly drawn triplets are like n3n_3: the network works hard, learns nothing, and convergence slows down.

Which triplets to pick

The easiest answer is to pick the hardest ones. For each anchor, find the farthest positive (the hard positive) and the closest negative (the hard negative); this is hard negative mining.

But computing the argmax and argmin over the whole training set isn't feasible. Worse, the hardest few are often mislabeled photos or badly captured faces, and letting them dominate training amounts to asking the model to memorize mistakes.

The authors came up with two routes:

  1. Offline: every nn steps, use the latest checkpoint to compute hard examples on a subset of the data.
  2. Online: pick directly within each mini-batch.

The paper mainly takes the online route, and there are four details.

How the batch is sampled. To find anchor–positive pairs within a batch, each identity needs enough faces in it. The authors give each person about 40 faces per batch, then add some randomly sampled negative faces; most experiments use batches of about 1,800 images. At roughly 40 per person, that works out to a bit over forty people per batch.

Every positive gets used. The authors don't pick the hardest positive; they use every anchor–positive pair in the batch. One person's 40 photos give (402)=780\binom{40}{2}=780 pairs, and a bit over forty people add up to more than thirty thousand pairs (this note's rough estimate), so the same forward pass over 1,800 images yields tens of thousands of triplets. The authors never compared this side by side with "hardest positive only"; they only say that in practice using all pairs was more stable and also converged slightly faster early in training.

Negatives are picked semi-hard. Always picking the closest negative easily traps early training in a bad local minimum and, at worst, makes the model collapse. Every face gets mapped to the same point, every distance is 0, and every triplet's loss is stuck at α\alpha with nowhere to go. So the authors restrict the negatives to:

dap<dand_{ap}<d_{an}

Farther than the positive, but still within the margin α\alpha, which is the orange middle band in the figure above. The authors call these semi-hard: they still produce a loss, without being closer than the positive the way n1n_1 is.

Why are negatives closer than the positive dangerous? The paper only records the observation. Two years later, Wu et al. supplied an explanation in "Sampling Matters in Deep Embedding Learning." The direction of the negative's gradient depends on f(xa)−f(xn)f(x^a)-f(x^n). When the two points are very close, this is a difference of two nearly identical vectors, and with even a little noise in the embeddings, the direction is almost random.

The tug-of-war over batch size. Small batches usually help SGD converge, and in practice batches of tens to hundreds of images are the most efficient; yet to find useful triplets within a batch, the batch has to be large enough. 1,800 images is where this tug-of-war settled. The authors also tried combining offline and online mining, which might allow somewhat smaller batches, but the experiments were inconclusive.

In code

The paper released no code. Below, equations (3) and (4) and the procedure above are written in PyTorch, using every anchor–positive pair in the batch and, for each pair, picking "the closest of the negatives that are farther than the positive":

python
import torch
import torch.nn.functional as F


def triplet_semihard_loss(emb, labels, alpha=0.2):
    """emb: [B, 128], already L2-normalized; labels: [B], the identity ID of each face."""
    d = (2 - 2 * emb @ emb.T).clamp(min=0)          # squared distance = 2 − 2cosθ, [B, B]
    same = labels[:, None] == labels[None, :]
    eye = torch.eye(len(labels), dtype=torch.bool, device=emb.device)

    a, p = (same & ~eye).nonzero(as_tuple=True)       # every anchor–positive pair in the batch
    d_ap = d[a, p]                                    # [P]
    d_an = d[a]                                       # [P, B]: each anchor's distance to the whole batch

    # semi-hard: only negatives farther than the positive, and the closest of those
    semi = ~same[a] & (d_an > d_ap[:, None])
    d_an = d_an.masked_fill(~semi, float('inf')).min(dim=1).values
    found = torch.isfinite(d_an)                      # skip pairs with no semi-hard negative for now

    loss = F.relu(d_ap[found] - d_an[found] + alpha)
    return loss.sum() / found.sum().clamp(min=1)

The input is already normalized, so the distance matrix comes straight from the 2−2cos⁡θ2-2\cos\theta of the opening. The paper leaves two points unclear, and you have to decide them yourself. One is which semi-hard negative to pick when there are several; here, as in TensorFlow's implementation, it is the closest one. The other is what to do when there is no semi-hard negative; here the pair is simply skipped, whereas the TensorFlow Addons version falls back to the farthest negative.

Training setup

The training data are 100 to 200 million face thumbnails of about 8 million identities. Each image first goes through face detection, a tight box around the face is cropped, and the crop is resized to the network's input size (96×96 to 224×224). Beyond scaling and translation, there is no 2D or 3D alignment at all, the opposite extreme from DeepFace's 3D alignment.

Optimization uses SGD with AdaGrad, with the learning rate mostly starting at 0.05 and lowered toward the end. The networks start from random initialization and train on a CPU cluster for 1,000 to 2,000 hours, roughly 42 to 83 days. The authors say the loss decreases very slowly after 500 hours, but continued training still improves results noticeably.

Two networks

The paper tries two kinds of network.

NN1 is based on ZFNet (the network of Zeiler and Fergus), with 1×1 convolutions inserted between the regular convolution layers, an idea taken from Network in Network. It has a 220×220 input, is 22 layers deep, has 140 million parameters, and costs about 1.6 billion FLOPs per image. Laying out NN1's parameters layer by layer, the first fully connected layer alone holds 103 million of them. This layer flattens the 7×7×256 features and connects them to 4,096 maxout units, each with two sets of weights, and it makes up roughly three quarters of all the parameters.

NN2 is based on GoogLeNet's Inception, with a 224×224 input, and is almost exactly the original GoogLeNet. The difference is that some pooling layers become L2 pooling, which takes the L2 norm of the values in a region instead of the maximum. Average pooling at the end gives 1,024 dimensions, followed by a 1,024-to-128 fully connected layer (130,000 parameters) and then L2 normalization. The whole network has only 7.5 million parameters, with about 1.6 billion FLOPs, the same as NN1.

Several smaller ones are shrunk down from NN2. NN3 lowers the input to 160×160; NN4 goes down to 96×96 and 285 million FLOPs, and also drops the 5×5 convolutions in the higher layers, because the receptive field is already too small by then. NNS1 and NNS2 are mini versions for phones, at about 220 million and 20 million FLOPs respectively; NNS2 has only 4.3 million parameters and takes 30 ms per image on a phone.

Discussion

How it's measured

LFW and YouTube Faces (YTF) report pair-classification accuracy; all the other test sets use a set of verification metrics. All image pairs of the same person are written Psame\mathcal P_{\text{same}} and those of different people Pdiff\mathcal P_{\text{diff}}; given a squared-distance threshold dd, a pair whose distance is at most dd is judged to be the same person. The pairs judged to be the same person fall into two piles:

TA(d)={(i,j)∈Psame, D(xi,xj)≤d}FA(d)={(i,j)∈Pdiff, D(xi,xj)≤d}\begin{aligned} \mathrm{TA}(d)&=\{(i,j)\in\mathcal P_{\text{same}},\ D(x_i,x_j)\le d\}\\ \mathrm{FA}(d)&=\{(i,j)\in\mathcal P_{\text{diff}},\ D(x_i,x_j)\le d\} \end{aligned}

TA are the genuine same-person pairs (true accept), and FA are the different people let in by mistake (false accept). The two ratios are then:

VAL(d)=∣TA(d)∣∣Psame∣FAR(d)=∣FA(d)∣∣Pdiff∣\begin{aligned} \mathrm{VAL}(d)&=\frac{|\mathrm{TA}(d)|}{|\mathcal P_{\text{same}}|}\\ \mathrm{FAR}(d)&=\frac{|\mathrm{FA}(d)|}{|\mathcal P_{\text{diff}}|} \end{aligned}

VAL (validation rate) is mostly called TAR (true accept rate) in later literature. Loosening the threshold raises VAL and FAR together, so results are usually written as "VAL with FAR fixed at some value." For example, VAL@FAR=10−310^{-3} means first adjusting the threshold until only one in every thousand pairs of strangers is wrongly let in, then seeing what fraction of the same-person pairs get recognized.

The same 10−310^{-3} weighs completely differently in 1:1 and in 1:N. When unlocking a phone, a stranger who tries their own face once has a one-in-a-thousand chance of being let in. Switch to that 500-person door system from earlier, and a stranger's face gets compared against each of the 500 people; roughly treating each comparison as an independent event, the probability of being mistaken for at least one of them is 1−(1−10−3)500≈39%1-(1-10^{-3})^{500}\approx 39\%. Only when FAR drops to 10−610^{-6} does this figure fall to about 0.05%. Later benchmarks such as IJB-B and IJB-C push FAR down to 10−410^{-4} or even lower when reporting results.

The paper uses four test sets:

  • Hold-out: about 1 million images with the same distribution as the training set and completely disjoint identities. It is split into 5 parts of 200,000 images each; VAL and FAR are computed on 100,000 × 100,000 image pairs, and the standard error over the 5 parts is reported.
  • Personal Photos: three personal photo albums, about 12,000 images in total, with labels checked by hand, evaluated on all 12,000 × 12,000 pairs.
  • LFW: the standard verification benchmark in academia, 6,000 photo pairs split into 10 folds, reporting classification accuracy.
  • YTF: a setup similar to LFW, but comparing pairs of videos.

The first two are Google-internal data, so outsiders have no way to use them for reproduction.

Compute decides accuracy

Scatter plot. The horizontal axis is multiply-adds per image on a log scale, from about two million to two billion; the vertical axis is VAL@FAR=10⁻³, from 20% to 95%. Blue dots are the various models tried, lined up roughly along a diagonal band toward the upper right. Red dots mark NNS2 (about 20 million, around 66%), NNS1 (about 220 million, around 84%), NN4 (about 285 million, around 82%), NN3 (about 800 million, around 88%), NN1 (about 1.6 billion, around 89%) and NN2 (about 1.6 billion, around 93%).
Original Figure 4, Schroff et al., from PDF page 5, arXiv license, scholarly quotation.

The horizontal axis is multiply-adds per image (log scale), and the vertical axis is VAL@FAR=10−310^{-3} on Personal Photos. Each dot is a model that was tried, and the red dots are the ones the paper discusses in detail. The dots form one diagonal band: the more compute, the higher the accuracy. From NNS2's 20 million to NN2's 1.6 billion, VAL climbs from a bit over 60% to over 90%.

Parameter count shows no such clear relationship. NN2 and NN1 have similar FLOPs and comparable accuracy, yet NN2 has only one twentieth of NN1's parameters; most of NN1's extra parameters are piled into that fully connected layer.

On the hold-out set, the VAL@FAR=10−310^{-3} of the six models is:

ModelInputFLOPsVAL
NN1220×2201.6B87.9%
NN2224×2241.6B89.4%
NN3160×160—88.3%
NN496×96285M82.0%
NNS1165×165220M82.4%
NNS2140×11620M51.9%

Compiled from Table 3 of the paper; FLOPs from Section 3.3 of the paper, which gives no FLOPs for NN3.

The standard errors of the models range from ±1.6 to ±2.9, and the gaps among NN1, NN2 and NN3 all fall within the error range. NN3's input area is only about half of NN2's, yet its score barely drops; only NN4 at 96×96 falls off clearly. NNS2's VAL is down to about half, which the authors still consider good enough for album clustering.

Compression, resolution, dimensionality and data size

The next few experiments all answer questions that come up in deployment.

The image-quality experiments test NN1 on the first hold-out split, again looking at VAL@FAR=10−310^{-3}. At JPEG quality 10 it drops to 67.3%, at quality 20 it recovers to 81.4%, and at quality 90 it is 86.5%. Face resolution matters more: 40×40 leaves only 37.8%, 80×80 gets 79.5%, 120×120 is 84.5%, and 256×256 is 86.4%. NN1 was trained at 220×220; at 120×120 and above there is almost no difference, 80×80 is still usable, and anything smaller falls apart. The authors also say that training on low-resolution faces should push this range further down.

Embedding dimensionality was also compared with NN1. VAL for 64, 128, 256 and 512 dimensions is 86.8%, 87.9%, 87.7% and 85.6%; the authors say the differences are not statistically significant, and larger dimensions might need longer training to catch up. After training, the 128-dimensional float vector can be quantized into 128 bytes without losing accuracy. A float32 128-dimensional vector takes 512 bytes, and quantization cuts that to a quarter; this is the "128-bytes per face" the abstract makes a point of.

The training-data experiment switched to a smaller model (96×96 input, similar to NN2 but without 5×5 convolutions), trained for 700 hours per setting and measured on Personal Photos:

Training imagesVAL
2.6 million76.3%
26 million85.1%
52 million85.1%
260 million86.2%

Compiled from Table 6 of the paper.

From a few million images to a few tens of millions, the error rate falls from 23.7% to 14.9%; adding another order of magnitude, to 260 million images, gains only 1.1 percentage points. The authors say they used a small model because of time constraints, and the gap might be larger for a big model. For comparison, CASIA-WebFace, released at the end of 2014, has about 10,000 people and 500,000 images, and its abstract says outright that in face recognition "data is more important than algorithm." Even the smallest row of this table is five times that size.

LFW and YTF

The standard LFW protocol splits the 6,000 photo pairs into 10 folds, picks the threshold on 9 of them and tests on the remaining one, rotating 10 times. The squared-distance threshold FaceNet picks is 1.242, except in the 8th fold, where it is 1.256; as an angle, that is about 68 degrees.

The authors ran NN1 in two modes:

  1. A fixed center crop taken straight from the thumbnails LFW provides: 98.87% ± 0.15.
  2. First re-detecting the faces with a proprietary face detector (the paper says it is similar to the one Picasa uses), and falling back to LFW's own alignment for the two images where detection fails: 99.63% ± 0.09.

The two modes differ by 0.76 percentage points, and the only difference is how the face is found and cropped.

99.63% means only 22 mistakes among the 6,000 pairs: 9 pairs of different people taken as the same person, and 13 pairs of the same person judged to be different people. The authors point out that 5 of those 13 pairs are actually labeling errors in LFW itself, and the model's call was the right one.

Against earlier work, DeepFace's 97.35% is an error rate of 2.65%, while FaceNet's is 0.37%, only about one seventh of it; DeepID2+'s error rate is 0.53%, and FaceNet cuts it by another 30%. The much smaller NN3 shows no statistically significant difference from NN1 on LFW.

YTF compares pairs of videos. FaceNet takes the first 100 frames in which a face is detected in each video, computes the similarity of every frame pair across the two videos and averages them, getting 95.12% ± 0.39; using the first 1,000 frames gives 95.18%. DeepFace, also with 100 frames, gets 91.4%, and DeepID2+ gets 93.2%.

Album clustering

The paper gives only qualitative examples for clustering. Agglomerative clustering groups one user's personal album, and one of the clusters contains photos spanning occlusion, lighting, pose and even age. This section has no clustering metrics at all; read it as a feature demo.

Swap the model, keep the database

v3 adds an appendix that tackles a very engineering-minded problem.

Suppose the database already holds embeddings computed with a v1 model for a large set of images, and now a better v2 has been trained. The usual approach is to recompute every image with v2, because the two models' embedding spaces have nothing to do with each other and their distances can't be compared. What the authors want is a harmonic embedding, so that v2 embeddings can be compared by distance directly against the old v1 embeddings.

Legend: open circles are v7 templates, filled circles are v8 templates. Below, three boxes each draw one triplet, with arrows from the anchor to the positive and to the semi-hard negative. In the first box the anchor and the positive are both filled; in the second the anchor is open and the positive filled; in the third the anchor is filled and the positive open. In all three boxes the negative is drawn half filled, half open.
Original Figure 9, Schroff et al., from PDF page 9, arXiv license, scholarly quotation.

The method mixes v1 embeddings into the triplet loss. In the figure, open points are the old model's embeddings (the legend says v7), and filled points are the new model being trained (the legend says v8). Besides triplets made entirely of new embeddings, two more combinations are added, "old anchor, new positive" and "new anchor, old positive"; the semi-hard negative is picked from all embeddings on both sides, old and new, which is why it is drawn half filled. The old embeddings stay fixed and only the new model learns, so the new model is forced to place each person near where the old model put them.

Training takes two steps. v2 is first initialized from an independently trained NN2, with the final embedding layer randomly reset, and only this last layer is trained with the mixed loss; after that, the whole network is unfrozen and trained together.

In the results, NN2 against NN2 is the best and NN1 against NN1 the worst; comparing NN2 embeddings against NN1 embeddings lands in between, and is still better than NN1 on its own. The authors' reading is that most v2 embeddings land near their corresponding v1 embeddings, while faces that v1 had put in the wrong place get nudged in v2 to somewhat more correct places, which is why mixing them still improves things. The authors themselves write that it is "somewhat surprising that it works so well," and speculate that there should be a limit to how much v2 can improve over v1 while staying compatible.

Five years later, Shen et al.'s BCT addressed the same need, which BCT calls backward-compatible representation: when a new model goes live, there should be no need to go back and recompute the entire gallery.

What became of triplets

FaceNet published only the paper, with no code and none of those 200 million training images. The best-known reproduction in the community is davidsandberg/facenet, with over fourteen thousand stars on GitHub.

The repo's README is blunt about it, stating that "Currently, the best results are achieved by training the model using softmax loss." Both pretrained models (LFW 0.9905 on CASIA-WebFace, 0.9965 on VGGFace2) are Inception-ResNet-v1 plus softmax. When someone asked in issue #435 which triplet selection to use, David Sandberg answered in October 2017, "All pretrained model so far have been trained using softmax loss." (A repo named facenet, and not a single model in it trained with FaceNet's loss.)

The triplet training script is still there, but its default negative selection isn't semi-hard. In select_triplets, the line marked "FaceNet selection" is commented out, and what actually runs is the approach from the VGG-Face paper by Oxford's VGG group: pick one at random from all negatives that violate the margin, including those even closer than the positive.

Following the wiki's procedure to train triplets on CASIA-WebFace, issue #403 (July 2017) reports LFW accuracy of around 88%, another user reports 89%, and the maintainer never replied. In issue #1012 (April 2019), a user who trained triplets from scratch got about 92.5% LFW accuracy and a VAL of only 35% to 40% after 800,000 steps; after switching back to the paper's semi-hard selection and adding a cyclic learning rate and 512-dimensional embeddings, they ran about 1 million steps and reported 97.1% accuracy and 81.2% VAL in July 2019. (The paper: 99.63%. The community, after a million steps: 97.1%. To be fair, the paper also brought along 200 million faces and a CPU cluster.)

In issue #124 (January 2017), David Sandberg's view was that "the main difference is that the facenet paper uses huge batch size (1800 examples)," with a guess that FaceNet could afford such a large batch because it ran on CPUs rather than GPUs.

timesler/facenet-pytorch (over five thousand stars) ports davidsandberg's two softmax models to PyTorch and outputs 512-dimensional embeddings by default. So what pip install facenet-pytorch gets you is an Inception-ResNet-v1, 512-dimensional, softmax-trained model; backbone, dimensionality and loss all differ from this paper.

One example that trains with triplets and also releases its models is CMU's OpenFace. Its setup is 128 dimensions, α=0.2\alpha=0.2, 15 people × 20 images for 300 images per batch, and FaceScrub plus CASIA-WebFace as training data; its model names nn2 and nn4 even match the paper's NN2 and NN4. The default model nn4.small2.v1 scores 92.92% on LFW, and the documentation lists the FaceNet paper's 99.63% as a reference in the same table.

The academic response split into two paths.

One kept the triplets but improved the sampling. In 2017, Hermans et al. proposed batch hard for person re-identification: each batch samples PP people with KK images each (for example 18 × 4 = 72 images), and each anchor directly takes the hardest positive and the hardest negative within the batch. In Hermans et al.'s words, "FaceNet uses a huge batch with moderate mining, which can only be done on the CPU"; hard mining within a small batch can reach a similar effect and also fits on a GPU. The same year, Sampling Matters pointed out that on a high-dimensional unit sphere, the squared distance between two random points concentrates around 2. Against FaceNet's LFW threshold of 1.242, most randomly drawn negatives are already beyond the margin; semi-hard picks only a narrow band in the middle, and once the samples in that band are used up, training stalls. Wu et al. also cite FaceNet's own remark that progress "slows down drastically after 500h of training" as evidence, and switched to distance-weighted sampling.

The other path stopped picking triplets altogether. SphereFace puts the margin inside the angles of the softmax. Each identity has a class center (the weight vector of the classification layer), and every face is compared against all class centers, so there is no need to assemble combinations within a batch anymore. CosFace and ArcFace then moved the margin again, CosFace subtracting it from the cosine and ArcFace adding it to the angle. The introduction of the ArcFace paper states the trouble with triplets bluntly: the number of triplets explodes combinatorially on large datasets, the number of iteration steps rises sharply, and semi-hard mining is itself hard to get right.

Conclusion

FaceNet turns every face into a 128-dimensional point on the unit sphere, trains the distances directly with the triplet loss, and relies on in-batch semi-hard mining to make training run on over a hundred million faces. It makes only 22 mistakes on LFW, and the experiments on the hold-out set and the albums measure, one by one, how compute, resolution, dimensionality and data size affect accuracy. The price is a 1,800-image batch, a CPU cluster running for over a thousand hours, and 200 million faces nobody outside can get; the triplet part was later mostly handed over to margin-based softmax.

When you pick up an off-the-shelf "FaceNet" model, first check whether the embedding is 128- or 512-dimensional, whether it compares squared distance or cosine, and what data the threshold was picked on. The paper's 1.242 is a squared distance NN1 picked on LFW, which as a cosine is 1−1.242/2≈0.381-1.242/2\approx 0.38; with a different model or different data, pick it again on your own data, and pick it directly at the FAR you need. If you really want to train with triplets, put enough images of each identity in the batch, make the batch large enough, and keep an eye on the fraction of triplets with a loss above 0 during training.

The paper closes by saying the authors tried similarity-transform alignment, which helped slightly, but they weren't sure it was worth the extra complexity. Three years later, ArcFace applies a similarity transform using the two eye centers, the nose tip and the two mouth corners before anything goes into the network, turning every face upright at 112×112.