Back to paper library

SphereFace

Round Faces

Original paper

SphereFace: Deep Hypersphere Embedding for Face Recognition

Paper authors

Weiyang Liu · Yandong Wen · Zhiding Yu · Ming Li · Bhiksha Raj · Le Song

Publication
CVPR 2017Conference
First submitted to arXiv
arXiv:1704.08063
Cite this paper · BibTeX

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

@misc{facerecognitionsphereface2017,
  title = {{SphereFace: Deep Hypersphere Embedding for Face Recognition}},
  author = {Weiyang Liu and Yandong Wen and Zhiding Yu and Ming Li and Bhiksha Raj and Le Song},
  year = {2017},
  eprint = {1704.08063},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1704.08063}
}
On this page

This paper trains on CASIA-WebFace, which contains 10,575 people; the test sets, LFW and YouTube Faces, don't include a single one of them.

So the classifier with 10,575 outputs used in training is thrown away wholesale at test time, keeping only the 512-dimensional feature the layer before it spits out. The angle between two faces' features is computed, and a small angle means the same person. However well the classifier learns, it never gets used; what actually has to be delivered is the shape of the feature space.

The paper's second author, Yandong Wen, had published center loss only the year before, training softmax tied together with a Euclidean-distance loss that "pulls features toward their class centers." Yet the first section of this paper says that the features learned by softmax are inherently distributed by angle, and tying a Euclidean-distance loss onto them is not really a good fit.

Since the features are arranged by angle, the margin should be drawn on the angle too.

Defining the Problem

Open-set face recognition

Face recognition can be asked in two ways. Face verification (1:1) gives two faces and asks whether they belong to the same person; LFW's standard protocol gives 6,000 photo pairs and counts the fraction answered correctly. Identification (1:N) takes one face and looks up who it is in a list; MegaFace's list is mixed with a million unrelated distractor photos.

The paper then splits testing into two scenarios. If everyone at test time appears in the training set (closed-set), it can be treated directly as a classification problem, and verification just classifies the two faces separately and checks whether the labels match. Real applications are mostly the other kind (open-set): the test people don't overlap with the training set at all, the classifier's labels mean nothing, and only distances between features can be compared. At that point recognition becomes metric learning.

The authors write down the condition an ideal feature should satisfy: under the chosen metric, the maximal intra-class distance should be smaller than the minimal inter-class distance.

max⁡dintra<min⁡dinter\max d_{\text{intra}} < \min d_{\text{inter}}

The two most distant photos of the same person have to be closer than the two closest photos of different people. As long as this holds, the nearest neighbor never gets it wrong. The hard part is that faces vary a lot within a class (lighting, pose, expression, age), while the differences between classes are small.

What people did at the time

In 2017, the common approaches fell into three categories:

  • Softmax only: DeepFace and DeepID train recognition as multi-class classification. Softmax only requires the classes to be separable, not how far apart they are.
  • Softmax plus a Euclidean-distance loss: DeepID2 adds a contrastive loss, and Wen et al. add center loss. Center loss only cares about how compact each class is and doesn't directly push different classes apart.
  • Triplet loss: FaceNet uses groups of three, an anchor, a positive and a negative, and requires the negative to be farther than the positive by a margin. The cost is that triplets must be mined carefully, each step only takes care of a few representative groups, and how well the mining goes directly affects the result.

The authors' entry point is a small experimental plot. They set the CNN's final feature layer to 2 dimensions, trained it on just two people from CASIA-WebFace, and plotted the features:

The left half of the paper's Figure 2, three small plots. (a) 2D features of the original softmax in the original space: the yellow cluster stretches toward the upper left and the magenta cluster lies at the lower right, each radiating outward from near the origin. (b) The same features projected onto the unit circle: the two clusters mix over a stretch near the angle bisector, and the plot marks the weights W1, W2 and the biases b1, b2. (c) Features of the modified softmax in the original space, with the two clusters on either side of the y axis.
Original Figure 2 (a)–(c), Liu et al., from PDF page 2, arXiv license, scholarly quotation.

Look at (a) first. Each of the two clusters stretches outward from near the origin into a long strip, like two fans; the features of the same person point in roughly the same direction but differ a lot in length. (b) projects them onto the unit circle and looks only at direction, and the two clusters still overlap over a short stretch near the angle bisector in the middle, because the bias terms b1b_1 and b2b_2 keep the boundary from being decided purely by angle.

This plot led the authors to two decisions. First, since softmax features are radial to begin with, a Euclidean margin is not the natural choice; the margin should be added on the angle. Second, to make classification depend only on the angle, the weights and biases have to be cleaned up first.

Solving the Problem

Taking softmax apart first

Start with two classes. The weights of the final fully connected layer are W1W_1 and W2W_2, the biases are b1b_1 and b2b_2, and the feature is xx. The softmax posterior probability is:

p1=exp⁡(W1⊤x+b1)exp⁡(W1⊤x+b1)+exp⁡(W2⊤x+b2)p_1=\frac{\exp(W_1^\top x+b_1)}{\exp(W_1^\top x+b_1)+\exp(W_2^\top x+b_2)}

p2p_2 works the same way. If p1>p2p_1>p_2, the sample is assigned to class 1, so the decision boundary is (W1−W2)⊤x+b1−b2=0(W_1-W_2)^\top x+b_1-b_2=0.

Write the inner product as the lengths times the cosine of the angle, Wi⊤x+bi=∥Wi∥∥x∥cos⁡θi+biW_i^\top x+b_i=\|W_i\|\|x\|\cos\theta_i+b_i, where θi\theta_i is the angle between xx and WiW_i. If we require ∥Wi∥=1\|W_i\|=1 and bi=0b_i=0, the two scores become ∥x∥cos⁡θ1\|x\|\cos\theta_1 and ∥x∥cos⁡θ2\|x\|\cos\theta_2. ∥x∥\|x\| is shared and cancels out when comparing them, leaving the boundary as just:

cos⁡θ1−cos⁡θ2=0\cos\theta_1-\cos\theta_2=0

That is the angle bisector of W1W_1 and W2W_2.

Generalized to KK classes and NN samples, the modified softmax of the paper's Eq. (5) is:

Lmodified=1N∑i−log⁡e∥xi∥cos⁡(θyi,i)∑je∥xi∥cos⁡(θj,i)L_{\text{modified}}=\frac{1}{N}\sum_i-\log\frac{e^{\|x_i\|\cos(\theta_{y_i,i})}}{\sum_j e^{\|x_i\|\cos(\theta_{j,i})}}

yiy_i is the correct class of the ii-th sample, and θj,i\theta_{j,i} is the angle between xix_i and the weight WjW_j of the jj-th class. In practice, every WjW_j is normalized to unit length at every iteration.

Note that ∥xi∥\|x_i\| is still in the formula. SphereFace normalizes only the weights, not the features; the feature length still affects the size of the logits during training, just not "which class it goes to." CosFace and ArcFace both changed this later.

The right half of the paper's Figure 2, three small plots. (d) Modified softmax features projected onto the unit circle: yellow on the left, magenta on the right, cleanly split at the angle bisector, but the two clusters nearly touch at the border. (e) A-Softmax features in the original space, with the two clusters farther apart. (f) A-Softmax projected onto the unit circle: yellow is squeezed into a short arc on the left and magenta into a short arc at the upper right, leaving a large empty stretch in between.
Original Figure 2 (d)–(f), Liu et al., from PDF page 2, arXiv license, scholarly quotation.

(d) is the result of modified softmax. The two clusters are split at the angle bisector, but they sit very close at the border, so a new, unseen face could land on either side. Separated, but not yet far apart.

Multiplying the angle by mm

Take a concrete example. W1W_1 and W2W_2 are 90° apart, and there is a class-1 feature at 30° from W1W_1 and 60° from W2W_2. Modified softmax only requires cos⁡θ1>cos⁡θ2\cos\theta_1>\cos\theta_2, and since cos⁡30°=0.866>cos⁡60°=0.5\cos 30°=0.866>\cos 60°=0.5, the feature is already classified correctly.

A-Softmax changes the requirement to:

cos⁡(mθ1)>cos⁡θ2\cos(m\theta_1)>\cos\theta_2

m≥2m\ge 2 is an integer. Within θ1∈[0,π/m]\theta_1\in[0,\pi/m], cos⁡(mθ1)<cos⁡θ1\cos(m\theta_1)<\cos\theta_1, so this is a stricter condition. In terms of angles, it is mθ1<θ2m\theta_1<\theta_2.

Check the same feature with m=4m=4: cos⁡(4×30°)=cos⁡120°=−0.5\cos(4\times30°)=\cos 120°=-0.5, smaller than 0.50.5, so it fails. To pass, θ1\theta_1 must be smaller than θ2/4\theta_2/4; for a feature between the two weights, θ2=90°−θ1\theta_2=90°-\theta_1, which solves to θ1<18°\theta_1<18°. Where anything within 45° used to count as correct, the feature now has to squeeze within 18°.

Class 2 has its own condition, cos⁡(mθ2)>cos⁡θ1\cos(m\theta_2)>\cos\theta_1. The two boundaries don't coincide, leaving a band of angles in between where nobody is allowed to stay. When all samples are classified correctly, this band is:

m−1m+1 θ12\frac{m-1}{m+1}\,\theta_{12}

θ12\theta_{12} is the angle between W1W_1 and W2W_2. With 90° and m=4m=4, the empty band is 35×90°=54°\frac{3}{5}\times 90°=54°; 18° remains on each side, adding up to exactly 90°.

Written as a multi-class loss, this is the paper's Eq. (6):

Lang=1N∑i−log⁡e∥xi∥cos⁡(mθyi,i)ZiZi=e∥xi∥cos⁡(mθyi,i)+∑j≠yie∥xi∥cos⁡θj,i\begin{aligned} L_{\text{ang}}&=\frac{1}{N}\sum_i-\log\frac{e^{\|x_i\|\cos(m\theta_{y_i,i})}}{Z_i}\\ Z_i&=e^{\|x_i\|\cos(m\theta_{y_i,i})}+\sum_{j\neq y_i}e^{\|x_i\|\cos\theta_{j,i}} \end{aligned}

The margin is added only to the correct class; the other classes keep cos⁡θj\cos\theta_j.

ψ(θ)\psi(\theta): making cos⁡(mθ)\cos(m\theta) trainable

The trouble with Eq. (6) is that cos⁡(mθ)\cos(m\theta) is decreasing only on [0,π/m][0,\pi/m]. With m=4m=4, as θ\theta goes from 45° to 90°, cos⁡4θ\cos 4\theta climbs all the way back from −1-1 to 11.

For training, this is a disaster. Suppose a sample has θyi=60°\theta_{y_i}=60°, so cos⁡240°=−0.5\cos 240°=-0.5; if it drifts further in the wrong direction to 90°, cos⁡360°=1\cos 360°=1, and the correct-class logit actually gets larger while the loss gets smaller. The gradient pushes it away from the class center.

So the authors extend cos⁡(mθ)\cos(m\theta) into a function that decreases monotonically on [0,π][0,\pi], the paper's Eq. (7):

ψ(θ)=(−1)kcos⁡(mθ)−2kθ∈[kπm,(k+1)πm]\begin{aligned} \psi(\theta)&=(-1)^k\cos(m\theta)-2k\\ \theta&\in\left[\frac{k\pi}{m},\frac{(k+1)\pi}{m}\right] \end{aligned}

k=0,1,…,m−1k=0,1,\dots,m-1 is the segment that θ\theta falls in. Each time a segment is passed, cos⁡(mθ)\cos(m\theta) is flipped upside down (multiplied by (−1)k(-1)^k) and then shifted down by 2k2k, so that the start of each segment joins the end of the previous one.

A few points with m=4m=4:

θ\thetakkcos⁡4θ\cos 4\thetaψ(θ)\psi(\theta)
0°011
30°0−0.5−0.5
45°1−1−1
60°1−0.5−1.5
90°21−3
180°31−7

By 60°, cos⁡4θ\cos 4\theta has already turned back up while ψ\psi keeps going down; at 180°, ψ=1−2m=−7\psi=1-2m=-7. The final A-Softmax simply replaces cos⁡(mθyi,i)\cos(m\theta_{y_i,i}) in the numerator and denominator of Eq. (6) with ψ(θyi,i)\psi(\theta_{y_i,i}). With m=1m=1, ψ(θ)=cos⁡θ\psi(\theta)=\cos\theta, and it falls back to modified softmax.

Line chart. The horizontal axis is the angle θ between the feature and the correct-class weight, from 0° to 90°; the vertical axis is the correct-class logit divided by the feature length, from −3 to 1. The gray dashed line cos θ falls gently from 1 to 0. The orange dotted line cos 4θ drops to −1 at 45°, then turns back up and returns to 1 at 90°. The solid blue line ψ(θ) coincides with the orange line before 45° and keeps going down after it, reaching −3 at 90°. At 45° there is a vertical dashed line labeled θ = π/m.
Drawn for this note, computed from equations (5), (6) and (7) of the paper, m = 4.

Before 45°, the blue and orange lines coincide; after 45°, the orange cos⁡4θ\cos 4\theta curls upward while the blue ψ\psi keeps going down. The gray line is cos⁡θ\cos\theta with no margin, and the blue line stays below it the whole way, so at every angle the correct class has a harder time scoring than before.

There is one more implementation detail. To make backpropagation convenient, the paper uses the multiple-angle formula to write cos⁡(mθ)\cos(m\theta) as a polynomial in cos⁡θ\cos\theta, and cos⁡θ\cos\theta is computed directly from WW and xx, so the whole computation never needs θ\theta itself; this is also why mm has to be an integer. The m=4m=4 version of the official Caffe layer uses cos⁡4θ=8cos⁡4θ−8cos⁡2θ+1\cos 4\theta=8\cos^4\theta-8\cos^2\theta+1, then two sign functions to tell which segment θ\theta falls in. Translated into PyTorch, it is roughly:

python
import torch

def a_softmax_psi_m4(cos_t: torch.Tensor) -> torch.Tensor:
    """psi(theta) for m = 4, computed from cos(theta) only (official Caffe layer, QUADRUPLE)."""
    cos4 = 8 * cos_t**4 - 8 * cos_t**2 + 1
    sign0 = torch.sign(cos_t)                            # theta < 90 deg ?
    sign3 = sign0 * torch.sign(2 * cos_t**2 - 1)         # (-1)^k
    sign4 = 2 * sign0 + sign3 - 3                        # -2k
    return sign3 * cos4 + sign4

Plug it in segment by segment: with θ\theta in each of the four segments, sign3 is 1,−1,1,−11,-1,1,-1 in order and sign4 is 0,−2,−4,−60,-2,-4,-6, exactly (−1)k(-1)^k and −2k-2k. The correct-class logit is ∥x∥⋅ψ\|x\|\cdot\psi, and the other classes get ∥x∥cos⁡θj\|x\|\cos\theta_j.

Territory on the sphere

Once ∥Wi∥=1\|W_i\|=1 and bi=0b_i=0, classification depends only on the direction of xx. Project xx onto the unit hypersphere, and the angle θi\theta_i equals the arc length (the geodesic distance) traveled on the sphere from xx to WiW_i.

The paper's Figure 3, a schematic in two rows and three columns. The first row is 2D and the second 3D. The left column is the Euclidean margin loss, where each of the two classes is an ellipse or a ball inside a plane or a cube, with centers marked W1 and W2. The middle column is modified softmax, where the whole circle or sphere is cut into orange and green halves by a line or a plane through the center. The right column is A-Softmax: on the circle only two narrow sectors remain, near W1 and W2, with a feature x between them marked with its angles θ1, θ2 and arc lengths ω1, ω2 to the two sides; the 3D version shows two separate elliptical regions on the sphere.
Original Figure 3, Liu et al., from PDF page 4, arXiv license, scholarly quotation.

Read it from left to right. The Euclidean margin loss draws circles throughout the whole space; modified softmax cuts the sphere in half with a line through the center, and points on the cut can go either way; A-Softmax's decision boundary becomes mω1=ω2m\omega_1=\omega_2, and each class can only occupy a "hypercircle" around its own weight. The larger mm is, the smaller this patch of land, and the wider the empty zone in between.

That is why the authors call the learned features SphereFace, and the paper keeps stressing that this matches the prior that "faces also lie on a manifold." That is a geometric explanation; the experimental evidence has to wait for the mm ablation later on.

How large should mm be

The larger mm is, the stricter the condition, but how large does it have to be to guarantee that earlier criterion of "farthest intra-class < closest inter-class"? The paper's Properties 2 and 3 give lower bounds.

Start with two classes, measuring angles in the plane spanned by W1W_1 and W2W_2. Class 1's features start from W1W_1 and can extend in two directions:

  • Moving φ\varphi toward W2W_2: θ1=φ\theta_1=\varphi and θ2=θ12−φ\theta_2=\theta_{12}-\varphi, the condition is mφ<θ12−φm\varphi<\theta_{12}-\varphi, so it reaches at most φ=θ12/(m+1)\varphi=\theta_{12}/(m+1);
  • Moving φ\varphi the opposite way, getting ever farther from W2W_2: θ2=θ12+φ\theta_2=\theta_{12}+\varphi, the condition is mφ<θ12+φm\varphi<\theta_{12}+\varphi, so it reaches at most φ=θ12/(m−1)\varphi=\theta_{12}/(m-1).

So the largest angle class 1 can occupy is the sum of the two; class 2 is symmetric. The closest distance between the two classes is the span between W1W_1 and W2W_2 minus θ12/(m+1)\theta_{12}/(m+1) on each side. The paper's Eq. (8) writes this as:

θ12m−1+θ12m+1≤(m−1) θ12m+1\frac{\theta_{12}}{m-1}+\frac{\theta_{12}}{m+1}\le\frac{(m-1)\,\theta_{12}}{m+1}

The left side is the largest angle class 1 occupies, and the right side is the closest angle between the two classes. This inequality applies when θ12≤m−1mπ\theta_{12}\le\frac{m-1}{m}\pi, that is, when the outward-extending side hasn't yet wrapped around to the back of the sphere. Here it is drawn with θ12=90°\theta_{12}=90°:

Two circular diagrams, one above the other. In each circle, two arrows start from the center, W1 pointing right and W2 pointing up, 90° apart. Top, m = 2: the orange sector is the range of class 1, from −90° to 30°, spanning 120°; the green sector is class 2, from 60° to 180°; there is only a 30° gap between the two sectors, and the text on the right says intra-class 120° is greater than inter-class 30°, fail. Bottom, m = 4: the orange sector runs from −30° to 18°, spanning 48°; the green one from 72° to 120°; 54° is left open in between, and the text on the right says intra-class 48° is less than inter-class 54°, pass.
Drawn for this note from the two-class geometry of equation (8) of the paper.

With m=2m=2, class 1's outward side can extend a full 90°, so the class spans 120° on its own, while the two classes are only 30° apart; the condition fails. With m=4m=4, class 1 shrinks to 48° and the gap between the classes widens to 54°; the condition holds.

What about a general θ12\theta_{12}? Divide both sides of Eq. (8) by θ12\theta_{12}, then multiply by (m−1)(m+1)(m-1)(m+1):

(m+1)+(m−1)≤(m−1)2m2−4m+1≥0m≥2+3≈3.73\begin{aligned} (m+1)+(m-1)&\le(m-1)^2\\ m^2-4m+1&\ge 0\\ m&\ge 2+\sqrt3\approx 3.73 \end{aligned}

θ12\theta_{12} cancels out entirely, so as long as Eq. (8) applies, the conclusion doesn't depend on how far apart the two classes are. In the other case (Eq. (9), θ12>m−1mπ\theta_{12}>\frac{m-1}{m}\pi, where the outward side wraps around to the back), simplifying requires θ12≥2π/(m−1)\theta_{12}\ge 2\pi/(m-1). At exactly m=2+3m=2+\sqrt3, m−1mπ\frac{m-1}{m}\pi and 2πm−1\frac{2\pi}{m-1} are equal (their equality is equivalent to (m−1)2=2m(m-1)^2=2m, which is exactly the quadratic above), and for larger mm this condition is satisfied automatically. Put the two cases together and you get the paper's mmin⁡≥2+3m_{\min}\ge 2+\sqrt3.

For multiple classes, the authors assume k≥3k\ge3 weights evenly distributed in a 2D plane, with neighboring ones 2π/k2\pi/k apart. Now every class has a neighbor on each side, the outward-extension problem disappears, and each side can extend only 1m+1⋅2πk\frac{1}{m+1}\cdot\frac{2\pi}{k}. Eq. (10) writes:

θii+1m+1+θi−1im+1≤min⁡{(m−1) θii+1m+1,(m−1) θi−1im+1}\begin{aligned} &\frac{\theta_i^{i+1}}{m+1}+\frac{\theta_{i-1}^{i}}{m+1}\\ &\quad\le\min\left\{\frac{(m-1)\,\theta_i^{i+1}}{m+1},\frac{(m-1)\,\theta_{i-1}^{i}}{m+1}\right\} \end{aligned}

When the two angles are equal, this simplifies to 2≤m−12\le m-1, so mmin⁡≥3m_{\min}\ge 3.

Of the two lower bounds, one is 3.73 and the other 3, and the authors take m=4m=4. They also admit that these bounds aren't necessarily tight, and that they all rest on idealized assumptions such as "all training samples are classified correctly" and "the weights are evenly distributed."

Network and training setup

  • Data: CASIA-WebFace, after removing identities that overlap with the test sets, 494,414 images of 10,575 people, with horizontal flipping as the only augmentation. The paper makes a point of comparing scale: DeepFace uses 4M images, VGGFace 2M and FaceNet 200M, while this is only 0.49M.
  • Preprocessing: MTCNN finds five landmarks, a similarity transform aligns and crops the face (the official code crops it to 112×96), and the pixels have 127.5 subtracted and are then divided by 128.
  • Network: residual units stacked into five depths, 4, 10, 20, 36 and 64 layers, ending in a 512-dimensional FC1 as the feature. The official README adds that these networks have no BatchNorm and use PReLU instead of ReLU, unlike a standard ResNet; Appendix A also removes the last ReLU before FC1, since otherwise the features could only live in the non-negative orthant, losing a big chunk of the usable angular space.
  • Training: Caffe, m=4m=4; the paper says batch size 128 on four GPUs, learning rate 0.1, divided by 10 at 16K and 24K iterations, ending at 28K. The official setting is 256 per GPU on two GPUs, for a total batch of 512.
  • Testing: take the FC1 output, extract features from the original image and its horizontal flip and concatenate them, then compare with cosine similarity; identification takes the nearest neighbor, and verification uses a threshold.

For fairness, the softmax, contrastive, triplet, center loss and L-Softmax baselines the paper implemented itself all use the same 64-layer network.

Appendix G: m=4m=4 is actually hard to train directly

Up to this point, the main text reads as if you could just plug in ψ\psi and train. Appendix G adds that A-Softmax has to be optimized with annealing, and that the correct-class logit is actually:

fyi=λ∥xi∥cos⁡θyi+∥xi∥ψ(θyi)1+λf_{y_i}=\frac{\lambda\|x_i\|\cos\theta_{y_i}+\|x_i\|\psi(\theta_{y_i})}{1+\lambda}

λ\lambda starts out very large, when fyif_{y_i} is almost exactly the ordinary ∥xi∥cos⁡θyi\|x_i\|\cos\theta_{y_i}, which amounts to starting training from softmax; then λ\lambda is gradually reduced so that ψ\psi gains weight. The authors say it could ideally go all the way down to 0, but "In most of our face experiments, decaying λ\lambda to 5 has already lead to impressive results"; smaller values might be better, and are also harder to train.

The official prototxt sets λ=max⁡(5, 1000 (1+0.12 t)−1)\lambda=\max\left(5,\ 1000\,(1+0.12\,t)^{-1}\right), where tt is the iteration count. At iteration 1, λ≈893\lambda\approx 893; from iteration 1,659 onward it stays fixed at 5, all the way to the end at iteration 28,000.

Plug in λ=5\lambda=5, and the correct-class logit is 56cos⁡θ+16ψ(θ)\frac{5}{6}\cos\theta+\frac{1}{6}\psi(\theta): five parts ordinary cosine to one part A-Softmax. Here it is drawn together with the earlier curves.

Line chart with the same axes as the previous one. The gray dashed line cos θ and the solid blue line ψ(θ) are as before; a solid purple line (5 cos θ + ψ(θ)) / 6 lies between them, close to the gray line, at about 0.42 at 45° and about −0.5 at 90°; a green dashed line cos 1.4θ almost overlaps the purple line.
Drawn for this note, computed from Appendix G of the paper and the λ settings in the official prototxt.

The purple line stays close to the gray one and far from the blue one. A few points:

θ\theta5cos⁡θ+ψ(θ)6\frac{5\cos\theta+\psi(\theta)}{6}Equivalent plain-cos⁡\cos angle
30°0.63850.3°
45°0.42365.0°
60°0.16780.4°
90°−0.500120.0°

Divide the angle in the right column by the θ\theta in the left column, and the effective multiplier comes out between 1.3 and 1.7, which is why the green dashed line cos⁡1.4θ\cos 1.4\theta almost overlaps the purple one. As early as August 2017, a user drew the same curve in issue #11 of the official repo and said it was roughly equivalent to m=1.5m=1.5; Weiyang Liu replied, "you are right in some senses," adding that lowering λmin⁡\lambda_{\min} further, even down to 0, remains a big optimization challenge. In 2022, the same group of authors wrote it down themselves in SphereFace Revived: the original SphereFace, minimized jointly with a standard softmax loss, "approximately yields an effective mm as 1.4."

So the m=4m=4 derived all the way through the main text, together with its lower bound of 3.73, describes an ideal target; a model trained with the official settings actually bears an angular margin of about 1.4 times (the menu says m = 4; what reaches the table is about 1.4). When ArcFace reimplemented SphereFace in 2018, it computed the angle directly with the arccosine, removing the requirement that mm be an integer, and found that m=1.35m=1.35 already performs on par with the original, with no convergence difficulties.

Discussion

The effect of mm

Start with the most direct experiment. The authors pick the 6 people with the most photos in CASIA-WebFace, set the feature to 3 dimensions and plot it on the unit sphere; the bottom row shows the angle distributions of positive pairs (same person) and negative pairs (different people) formed from two of them:

The paper's Figure 5, four columns for A-Softmax with m = 1, 2, 3 and 4. The top row shows unit spheres with the features of six people as point clusters of different colors on the surface; at m = 1 the clusters overlap heavily, and the larger m gets, the smaller and more separated the clusters become. The bottom row shows histograms of the angles of positive pairs (orange) and negative pairs (blue) in radians, and the upper right of each plot lists the maximum positive-pair angle, the minimum negative-pair angle and the angular margin between them.
Original Figure 5, Liu et al., from PDF page 7, arXiv license, scholarly quotation.

The three numbers in the upper right of each histogram are a direct measurement of that ideal criterion (in radians). The "angular margin" equals the minimum angle of the negative pairs minus the maximum angle of the positive pairs; a positive number means that even the farthest intra-class pair is closer than the closest inter-class pair:

mmMax pos. angleMin neg. angleMargin
11.710.30−1.41
20.940.82−0.12
30.541.070.53
40.481.140.66

Compiled from Figure 5 of the paper.

The margin turns positive at m=3m=3, which matches the multi-class lower bound mmin⁡≥3m_{\min}\ge3; but this is an illustrative experiment with 6 people and 3-dimensional features, trained with the annealing from the previous section, and the paper doesn't treat it as a proof of the lower bound.

For the formal evaluation, the authors compare different values of mm with the 64-layer network (LFW and YTF, accuracy in %):

SettingLFWYTF
softmax97.8893.1
m=1m=197.9093.2
m=2m=298.4093.8
m=3m=399.2594.4
m=4m=499.4295.0

Compiled from Table 3 of the paper.

In this 64-layer comparison, m=1m=1 (only weight normalization and zero bias) is almost identical to softmax; the improvement comes from the margin itself, and it keeps rising with every step up in mm.

Of LFW's 6,000 pairs, going from 98.40% to 99.42% means the errors drop from 96 pairs to about 35. YTF has 5,000 video pairs, so 95.0% still leaves about 250 pairs wrong; this dataset varies far more in pose and image quality.

Network depth

The authors compare A-Softmax (m=4m=4) with softmax at five depths:

LayersLFW A-SoftmaxLFW softmaxYTF A-SoftmaxYTF softmax
498.2096.6393.491.1
1099.0397.1293.792.0
2099.2697.5094.192.6
3699.3597.7594.392.9
6499.4297.8895.093.1

Compiled from Figure 6 of the paper.

A-Softmax leads at every depth, by 1.54 to 1.91 percentage points on LFW and 1.4 to 2.3 percentage points on YTF. The authors' reading is that the harder the task, the more use it makes of a deep network's capacity; softmax gains only 0.13 going from 36 to 64 layers.

Appendix F runs the same comparison on MegaFace, and the gap is larger. SphereFace with just 4 layers (Rank-1 57.529%) already beats 64-layer softmax (54.855%), and 64-layer SphereFace reaches 72.729%.

Appendix E: what each change is worth

The v4 appendix adds a step-by-step ablation. The authors first define an angular version of the Fisher score:

AFS=SwSb\mathrm{AFS}=\frac{S_w}{S_b}

Sw=∑i∑xj∈Xi(1−cos⁡⟨xj,mi⟩)S_w=\sum_i\sum_{x_j\in X_i}(1-\cos\langle x_j,m_i\rangle) is the angular spread of each sample around its own class mean vector mim_i, and Sb=∑ini(1−cos⁡⟨mi,m⟩)S_b=\sum_i n_i(1-\cos\langle m_i,m\rangle) is the angular spread of the class mean vectors around the overall mean vector mm, with nin_i the number of samples in class ii. The tighter each class and the farther apart the classes, the lower the score.

With a 4-layer network trained on CASIA and tested on LFW, adding one item at a time:

SettingLFWAFS
Original softmax95.130.3477
+ remove last ReLU96.370.2835
+ zero bias96.400.2815
+ weight normalization96.630.2462
+ A-Softmax, m=2m=297.670.2277
m=3m=397.820.1791
m=4m=498.200.1709

Compiled from Table 6 in the appendix of the paper.

Removing the ReLU alone is worth 1.24 percentage points, about as much as the 1.04 that A-Softmax gains going from nothing to m=2m=2; zeroing the bias has almost no effect, and Appendix C also shows that the biases of a trained model sit mostly near 0 anyway.

Appendix B gives one more reason for weight normalization. The authors tallied each class's weight length against that class's number of samples and found that classes with more samples have longer weights; this amounts to learning the class imbalance of the training set as a prior. Verification faces people never seen before, so carrying this prior over does no good, and normalizing the weights removes it.

LFW and YTF: against other methods

MethodTraining dataLFWYTF
softmaxWebFace97.8893.1
+ contrastiveWebFace98.7893.5
tripletWebFace98.7093.4
L-SoftmaxWebFace99.1094.0
+ center lossWebFace99.0594.4
SphereFaceWebFace99.4295.0
FaceNet200M99.6595.1
VGGFace2.6M98.9597.3

Compiled from Table 4 of the paper; the first six rows were implemented by the authors with the same 64-layer network.

With the same architecture and the same data, SphereFace is the highest in every column. L-Softmax is the same team's work from the year before, built on the same idea of a multiplicative margin; the difference lies in weight normalization and zero bias, and the two are 0.32 and 1.0 percentage points apart.

The main text goes on to say that SphereFace's "single model performance is only worse than Google FaceNet," which was trained on two hundred million photos (meanwhile, in the YTF column of that very table, VGGFace sits at 97.3). The sentence holds in the LFW column; in the YTF column, SphereFace is still 2.3 percentage points behind VGGFace.

MegaFace

MegaFace Challenge 1 uses celebrity photos from FaceScrub as probes, mixed in with a million distractor photos. There are two metrics:

  • Rank-1: search for the probe among more than a million photos and check whether the top-ranked one is the same person.
  • TAR@FAR=10−610^{-6}: set the threshold so that only one in a million pairs of different people may be wrongly judged as the same person, and at that threshold, see what fraction of same-person pairs are accepted.

Training data under 500,000 images falls under the small protocol. SphereFace's results here (%):

MethodRank-1TAR
softmax54.85565.925
L-Softmax67.12880.423
+ center loss65.49480.146
SphereFace single model72.72985.561
SphereFace 3-patch75.76689.142
Deepsense (small, 2nd place)70.98382.851

Compiled from Table 5 of the paper.

The paper says it beats the second place of the small protocol by 4.8 and 6.3 percentage points, with a 3-patch ensemble that concatenates features from three face regions; for the single model, the gaps are 1.7 and 2.7. It also says it beats the large-protocol teams, but Rank-1 is compared against Vocord (75.127) and TAR against Deepsense Large (87.764), a different opponent picked for each column.

The official repo initially released only a 20-layer model. Someone retrained it accordingly, got only 67.35% on MegaFace, and asked about it in issue #8 (August 2017); the authors replied that MegaFace used neither the 20-layer architecture nor another 28-layer one. The 64-layer prototxt was only added in February 2018.

Community reproductions

The LFW part reproduces well. The README lists five reruns of the 20-layer model with the official pipeline, with LFW between 99.13% and 99.30%; the 20-layer entry in the depth table above is 99.26%. The early pipeline had several preprocessing bugs; users in issue #3 fixed their way up from 62% to over 98%, and the authors patched it in August 2017. In the same thread, Yandong Wen warned that a smaller batch keeps the loss from coming down, and recommended staying at 512.

Moving to large data didn't go as smoothly. In issue #14, someone training on MS-Celeb-1M could get neither 28 nor 64 layers to converge; the authors suggested tuning λ\lambda, or training with softmax first and then switching to A-Softmax for fine-tuning. The README's convergence advice also says the most effective thing is to tune λmin⁡\lambda_{\min}, λ\lambda and the decay speed. How hard a multiplicative margin is to train is a problem the community ran into again and again.

What came after

After SphereFace, this line quickly changed direction. Note 3 of the README itself says that also normalizing the features and multiplying them by a tunable scale ss can significantly improve SphereFace's performance on MegaFace. CosFace and ArcFace, both appearing in January 2018, fix ∥x∥\|x\| to ss and make the margin additive, with CosFace subtracting mm from the cosine and ArcFace adding mm to the angle, and training no longer needs annealing. CosFace also points out that A-Softmax's margin shrinks as θ\theta gets smaller and vanishes entirely at θ=0\theta=0.

The original authors later came back to tidy up as well. The 2022 SphereFace Revived states that the original SphereFace suffers from severe training instability, "typically requiring a number of bells and whistles to stabilize its training," and argues that the artificially stitched-together ψ\psi for θ>π/m\theta>\pi/m doesn't fit what a multiplicative margin is meant to do, and may be one of the causes. They propose two new ways to write the multiplicative margin, one redesigning ψ\psi and one rewriting the function for the non-target classes, and then cut off the gradient of the margin term (characteristic gradient detachment), getting far more stable training in return. SphereFace2, from the same year, goes further and replaces softmax with one-vs-all binary classification, on the grounds that verification at test time is a binary problem to begin with. The code for both papers was folded into OpenSphere, the official PyTorch reimplementation, which the README linked in April 2022.

Conclusion

SphereFace proved two things. A classifier that looks only at angles, plus an angular margin, reaches 99.42% on LFW, 95.0% on YTF and 72.729% for a single model on the MegaFace small protocol with only 490,000 training photos, beating softmax, contrastive, triplet, center loss and L-Softmax under the same architecture; and the ablation from m=1m=1 to m=4m=4 shows that the improvement really does come from the margin.

If you want to try a multiplicative angular margin on your own data, read Appendix G and the official prototxt first. Trained with the official settings, five sixths of the correct-class logit is still the ordinary cos⁡θ\cos\theta, and the effective margin is about 1.4 times; if you want to push λ\lambda lower, keeping the total batch at 512 and pretraining with softmax before fine-tuning makes convergence easier. If all you want is an angular margin that trains easily, ArcFace's additive margin is far more direct.

In 2022, the original authors went back and redid this loss, and put the word Revived right in the paper's title.