SphereFace: Deep Hypersphere Embedding for Face Recognition
- 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}
}
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.
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:

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 and 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 and , the biases are and , and the feature is . The softmax posterior probability is:
works the same way. If , the sample is assigned to class 1, so the decision boundary is .
Write the inner product as the lengths times the cosine of the angle, , where is the angle between and . If we require and , the two scores become and . is shared and cancels out when comparing them, leaving the boundary as just:
That is the angle bisector of and .
Generalized to classes and samples, the modified softmax of the paper's Eq. (5) is:
is the correct class of the -th sample, and is the angle between and the weight of the -th class. In practice, every is normalized to unit length at every iteration.
Note that 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.

(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
Take a concrete example. and are 90° apart, and there is a class-1 feature at 30° from and 60° from . Modified softmax only requires , and since , the feature is already classified correctly.
A-Softmax changes the requirement to:
is an integer. Within , , so this is a stricter condition. In terms of angles, it is .
Check the same feature with : , smaller than , so it fails. To pass, must be smaller than ; for a feature between the two weights, , which solves to . Where anything within 45° used to count as correct, the feature now has to squeeze within 18°.
Class 2 has its own condition, . 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:
is the angle between and . With 90° and , the empty band is ; 18° remains on each side, adding up to exactly 90°.
Written as a multi-class loss, this is the paper's Eq. (6):
The margin is added only to the correct class; the other classes keep .
: making trainable
The trouble with Eq. (6) is that is decreasing only on . With , as goes from 45° to 90°, climbs all the way back from to .
For training, this is a disaster. Suppose a sample has , so ; if it drifts further in the wrong direction to 90°, , 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 into a function that decreases monotonically on , the paper's Eq. (7):
is the segment that falls in. Each time a segment is passed, is flipped upside down (multiplied by ) and then shifted down by , so that the start of each segment joins the end of the previous one.
A few points with :
| 0° | 0 | 1 | 1 |
| 30° | 0 | −0.5 | −0.5 |
| 45° | 1 | −1 | −1 |
| 60° | 1 | −0.5 | −1.5 |
| 90° | 2 | 1 | −3 |
| 180° | 3 | 1 | −7 |
By 60°, has already turned back up while keeps going down; at 180°, . The final A-Softmax simply replaces in the numerator and denominator of Eq. (6) with . With , , and it falls back to modified softmax.

Before 45°, the blue and orange lines coincide; after 45°, the orange curls upward while the blue keeps going down. The gray line is 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 as a polynomial in , and is computed directly from and , so the whole computation never needs itself; this is also why has to be an integer. The version of the official Caffe layer uses , then two sign functions to tell which segment falls in. Translated into PyTorch, it is roughly:
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 in each of the four segments, sign3 is in order and sign4 is , exactly and . The correct-class logit is , and the other classes get .
Territory on the sphere
Once and , classification depends only on the direction of . Project onto the unit hypersphere, and the angle equals the arc length (the geodesic distance) traveled on the sphere from to .

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 , and each class can only occupy a "hypercircle" around its own weight. The larger 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 ablation later on.
How large should be
The larger 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 and . Class 1's features start from and can extend in two directions:
- Moving toward : and , the condition is , so it reaches at most ;
- Moving the opposite way, getting ever farther from : , the condition is , so it reaches at most .
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 and minus on each side. The paper's Eq. (8) writes this as:
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 , that is, when the outward-extending side hasn't yet wrapped around to the back of the sphere. Here it is drawn with :

With , 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 , class 1 shrinks to 48° and the gap between the classes widens to 54°; the condition holds.
What about a general ? Divide both sides of Eq. (8) by , then multiply by :
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), , where the outward side wraps around to the back), simplifying requires . At exactly , and are equal (their equality is equivalent to , which is exactly the quadratic above), and for larger this condition is satisfied automatically. Put the two cases together and you get the paper's .
For multiple classes, the authors assume weights evenly distributed in a 2D plane, with neighboring ones apart. Now every class has a neighbor on each side, the outward-extension problem disappears, and each side can extend only . Eq. (10) writes:
When the two angles are equal, this simplifies to , so .
Of the two lower bounds, one is 3.73 and the other 3, and the authors take . 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, ; 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: is actually hard to train directly
Up to this point, the main text reads as if you could just plug in and train. Appendix G adds that A-Softmax has to be optimized with annealing, and that the correct-class logit is actually:
starts out very large, when is almost exactly the ordinary , which amounts to starting training from softmax; then is gradually reduced so that gains weight. The authors say it could ideally go all the way down to 0, but "In most of our face experiments, decaying to 5 has already lead to impressive results"; smaller values might be better, and are also harder to train.
The official prototxt sets , where is the iteration count. At iteration 1, ; from iteration 1,659 onward it stays fixed at 5, all the way to the end at iteration 28,000.
Plug in , and the correct-class logit is : five parts ordinary cosine to one part A-Softmax. Here it is drawn together with the earlier curves.

The purple line stays close to the gray one and far from the blue one. A few points:
| Equivalent plain- angle | ||
|---|---|---|
| 30° | 0.638 | 50.3° |
| 45° | 0.423 | 65.0° |
| 60° | 0.167 | 80.4° |
| 90° | −0.500 | 120.0° |
Divide the angle in the right column by the in the left column, and the effective multiplier comes out between 1.3 and 1.7, which is why the green dashed line 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 ; Weiyang Liu replied, "you are right in some senses," adding that lowering 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 as 1.4."
So the 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 be an integer, and found that already performs on par with the original, with no convergence difficulties.
Discussion
The effect of
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 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:
| Max pos. angle | Min neg. angle | Margin | |
|---|---|---|---|
| 1 | 1.71 | 0.30 | −1.41 |
| 2 | 0.94 | 0.82 | −0.12 |
| 3 | 0.54 | 1.07 | 0.53 |
| 4 | 0.48 | 1.14 | 0.66 |
Compiled from Figure 5 of the paper.
The margin turns positive at , which matches the multi-class lower bound ; 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 with the 64-layer network (LFW and YTF, accuracy in %):
| Setting | LFW | YTF |
|---|---|---|
| softmax | 97.88 | 93.1 |
| 97.90 | 93.2 | |
| 98.40 | 93.8 | |
| 99.25 | 94.4 | |
| 99.42 | 95.0 |
Compiled from Table 3 of the paper.
In this 64-layer comparison, (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 .
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 () with softmax at five depths:
| Layers | LFW A-Softmax | LFW softmax | YTF A-Softmax | YTF softmax |
|---|---|---|---|---|
| 4 | 98.20 | 96.63 | 93.4 | 91.1 |
| 10 | 99.03 | 97.12 | 93.7 | 92.0 |
| 20 | 99.26 | 97.50 | 94.1 | 92.6 |
| 36 | 99.35 | 97.75 | 94.3 | 92.9 |
| 64 | 99.42 | 97.88 | 95.0 | 93.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:
is the angular spread of each sample around its own class mean vector , and is the angular spread of the class mean vectors around the overall mean vector , with the number of samples in class . 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:
| Setting | LFW | AFS |
|---|---|---|
| Original softmax | 95.13 | 0.3477 |
| + remove last ReLU | 96.37 | 0.2835 |
| + zero bias | 96.40 | 0.2815 |
| + weight normalization | 96.63 | 0.2462 |
| + A-Softmax, | 97.67 | 0.2277 |
| 97.82 | 0.1791 | |
| 98.20 | 0.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 ; 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
| Method | Training data | LFW | YTF |
|---|---|---|---|
| softmax | WebFace | 97.88 | 93.1 |
| + contrastive | WebFace | 98.78 | 93.5 |
| triplet | WebFace | 98.70 | 93.4 |
| L-Softmax | WebFace | 99.10 | 94.0 |
| + center loss | WebFace | 99.05 | 94.4 |
| SphereFace | WebFace | 99.42 | 95.0 |
| FaceNet | 200M | 99.65 | 95.1 |
| VGGFace | 2.6M | 98.95 | 97.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=: 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 (%):
| Method | Rank-1 | TAR |
|---|---|---|
| softmax | 54.855 | 65.925 |
| L-Softmax | 67.128 | 80.423 |
| + center loss | 65.494 | 80.146 |
| SphereFace single model | 72.729 | 85.561 |
| SphereFace 3-patch | 75.766 | 89.142 |
| Deepsense (small, 2nd place) | 70.983 | 82.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 , 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 , 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 can significantly improve SphereFace's performance on MegaFace. CosFace and ArcFace, both appearing in January 2018, fix to and make the margin additive, with CosFace subtracting from the cosine and ArcFace adding to the angle, and training no longer needs annealing. CosFace also points out that A-Softmax's margin shrinks as gets smaller and vanishes entirely at .
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 for 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 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 to 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 , and the effective margin is about 1.4 times; if you want to push 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.