AI Logic

Loss Functions

SphereFace (A-Softmax)

Updated:

Diagram of SphereFace. The left side shows two classes with unit-length class weights W1 and W2 (90° apart) and the decision regions on the unit circle, shading the directions classified as class 1, as class 2, and as neither (a 54° margin at the top), and marking the angles θ1 and θ2 between a class-1 feature x and W1, W2. The right side plots the logit against the angle θ to the target class, overlaying cos θ (no margin), SphereFace's ψ(θ) (m = 4), and the annealed curve (λ = 5). The legend is on the far right

Background and Overview

SphereFace is a loss function that normalizes the weights of the final fully connected classification layer to unit length and multiplies the angle θ\theta between the target-class weight and the feature by mm, creating an angular gap (margin) between classes. The loss itself is called the A-Softmax (angular softmax) loss, and the face features learned with it are called SphereFace. It was proposed by Liu et al. in 2017 for face recognition.

With θyi\theta_{y_i} denoting the angle between the weight of the target class yiy_i and the feature xix_i, the A-Softmax loss is given by the following equation (NN is the number of training examples and θj\theta_{j} is the angle to the weight of class jj).

L=1N∑i−log⁡e∥xi∥ψ(θyi)e∥xi∥ψ(θyi)+∑j≠yie∥xi∥cos⁡θjL = \frac{1}{N} \sum_{i} -\log \frac{e^{\lVert x_i \rVert \psi(\theta_{y_i})}}{e^{\lVert x_i \rVert \psi(\theta_{y_i})} + \sum_{j \neq y_i} e^{\lVert x_i \rVert \cos\theta_{j}}}

ψ(θ)\psi(\theta) is a function equal to cos⁡(mθ)\cos(m\theta) for 0≤θ≤π/m0 \le \theta \le \pi/m (details in the next section). Compared with cos⁡θ\cos\theta without a margin, only the target-class logit becomes smaller, so the angle must be smaller for the prediction to count as correct.

The motivation lies in the difference between two uses of face recognition.

  • Distinguishing only people seen in training (closed set): If every test identity appears in the training data, the task can be solved as ordinary classification.
  • Distinguishing people unseen in training (open set): Real face verification is this case: the features of two face images are compared to decide whether they belong to the same person. Ideally, the maximum distance between features of the same person is smaller than the minimum distance to a different person.

Training classification with cross-entropy alone (which the paper calls the softmax loss) separates the features but does not push them far enough apart to meet this condition. Earlier methods added Euclidean-distance margins, as in Contrastive Loss, Triplet Loss, and Center loss. The paper showed that features learned with the softmax loss are inherently spread radially from the origin (by angle), and argued that it is natural to put the margin on the angle rather than on Euclidean distance.

The left side of the figure at the top places two class weights W1W_1 and W2W_2 90° apart and shades which class each direction on the circle is assigned to. With m=4m = 4, a 54° band between W1W_1 and W2W_2 is assigned to neither class.

Theory (How the Loss Is Computed)

The A-Softmax loss is computed in the following steps.

  1. Extract features: A CNN extracts a feature xix_i from a face image. The paper uses as the feature the 512-dimensional vector output by the last fully connected layer (FC1) of a network built from the same residual units as ResNet. The ReLU on the FC1 output is removed (it would confine features to the non-negative range and narrow the usable angles).
  2. Normalize the weights to unit length and set the bias to 0: The weights WjW_j of the classification layer are normalized to ∥Wj∥=1\lVert W_j \rVert = 1 at every iteration, and the bias is removed. Then Wj⊤xi=∥xi∥cos⁡θjW_j^{\top} x_i = \lVert x_i \rVert \cos\theta_{j}, and the class is determined by the angle θj\theta_{j} alone. The paper calls this the "modified softmax loss." The norm of the feature xix_i is not normalized.
  3. Multiply the target-class angle by mm: For the target-class logit only, cos⁡θyi\cos\theta_{y_i} is replaced with ψ(θyi)\psi(\theta_{y_i}). Because cos⁡(mθ)\cos(m\theta) starts increasing for θ>π/m\theta > \pi/m and is no longer monotonic, a function ψ(θ)\psi(\theta) that is pieced together to decrease monotonically over the whole range of θ\theta (the equation below) is used.
  4. Turn it into a loss with softmax and cross-entropy: Compute LL in the equation above. With m=1m = 1, ψ(θ)=cos⁡θ\psi(\theta) = \cos\theta, which reduces to the modified softmax loss without a margin.
  5. Compute the gradient: The paper rewrites cos⁡θ\cos\theta and cos⁡(mθ)\cos(m\theta) in terms of WW and xx only and differentiates. Because it uses the multiple-angle formula that expresses cos⁡(mθ)\cos(m\theta) as a polynomial in cos⁡θ\cos\theta, mm is an integer.

ψ(θ)\psi(\theta) in step 3 is given by the following equation (mm is an integer of 1 or more).

ψ(θ)=(−1)kcos⁡(mθ)−2k,θ∈[kπm, (k+1)πm], k∈{0,1,…,m−1}\psi(\theta) = (-1)^k \cos(m\theta) - 2k, \qquad \theta \in \left[\frac{k\pi}{m},\ \frac{(k+1)\pi}{m}\right],\ k \in \{0, 1, \dots, m-1\}

Comparing the decision boundaries for two classes makes the difference clear (Table 1 in the paper).

LossBoundary for class 1Boundary for class 2
Softmax loss(W1−W2)⊤x+b1−b2=0(W_1 - W_2)^{\top} x + b_1 - b_2 = 0(same boundary)
Modified softmax loss∥x∥(cos⁡θ1−cos⁡θ2)=0\lVert x \rVert (\cos\theta_1 - \cos\theta_2) = 0(same boundary)
A-Softmax loss∥x∥(cos⁡mθ1−cos⁡θ2)=0\lVert x \rVert (\cos m\theta_1 - \cos\theta_2) = 0∥x∥(cos⁡θ1−cos⁡mθ2)=0\lVert x \rVert (\cos\theta_1 - \cos m\theta_2) = 0

With the A-Softmax loss, being classified as class 1 requires mθ1<θ2m\theta_1 < \theta_2, that is, θ1<θ2/m\theta_1 < \theta_2 / m. The boundary splits into two, one per class, with an angular margin between them. For example, when the angle between W1W_1 and W2W_2 is θ12=90°\theta_{12} = 90° and m=4m = 4, a feature lying between the two weights is accepted as class 1 only if it is within 90°/(m+1)=18°90° / (m+1) = 18° of W1W_1. The same holds for class 2, leaving a margin of m−1m+1 θ12=54°\frac{m-1}{m+1}\,\theta_{12} = 54° in between (left side of the figure at the top).

The right side of the figure at the top plots the target-class logit (before multiplying by ∥x∥\lVert x \rVert) as a function of the angle θ\theta. ψ(θ)\psi(\theta) falls much more steeply than cos⁡θ\cos\theta, so at the same angle the target-class score is lower, and the only way to reduce the loss is to make the angle smaller.

Why It Yields Discriminative Features

Features learned with the A-Softmax loss also work for matching people unseen in training for three reasons.

  • Decisions depend only on the angle: Because the weights are normalized and the bias is removed, the class is determined solely by the angle between the feature and the weight. At test time, two features are matched by cosine similarity, so the training objective and the test-time measure agree.
  • A stricter condition for correctness shrinks the regions: Satisfying mθ1<θ2m\theta_1 < \theta_2 requires pulling the feature much closer to its own class weight. The paper describes this as each class region shrinking into a circle-like shape on the unit hypersphere (the unit circle in 2D, the unit sphere in 3D). The larger mm is, the narrower the regions, the wider the margin, and the harder the training.
  • No need to select sample combinations: Contrastive Loss and Triplet Loss require effort to find pairs or triplets useful for training, and the results depend on how they are chosen. The A-Softmax loss, like ordinary classification, constrains the whole mini-batch, so no combinations need to be chosen.

The paper also derives a lower bound on how large mm must be to satisfy "maximum angle within the same person < minimum angle to a different person." For two classes, mmin⁡≥2+3m_{\min} \ge 2 + \sqrt{3} (about 3.73), and for multiple classes, assuming the weights are evenly spaced on a plane, mmin⁡≥3m_{\min} \ge 3. Based on this, the experiments use m=4m = 4.

The paper notes that normalizing the weights to unit length also reduces the effect of class imbalance in the training data. With the softmax loss, classes with more samples tend to get weights with larger norms, which is a bias specific to the training data. For face verification, which matches people unseen in training, it is considered better not to carry this bias over.

As an analogy, the softmax loss is like "just drawing one line between you and your neighbor," whereas the A-Softmax loss demands "sitting a fixed distance away from that line." If there is space between seats, then even when a stranger arrives, it is easy to tell which seat they are closest to.

Experimental Results

The paper trained on the public CASIA-WebFace dataset (about 10,000 identities, 490,000 images) and evaluated on face verification with LFW (photos) and YTF (videos), and on MegaFace at the scale of 1 million identities.

First, verification accuracy for different values of mm (64-layer CNN):

DatasetSoftmax lossm=1m = 1m=2m = 2m=3m = 3m=4m = 4
LFW97.88%97.90%98.40%99.25%99.42%
YTF93.1%93.2%93.8%94.4%95.0%

Accuracy rises as mm grows, showing that a wider margin makes features easier to discriminate. With m=1m = 1 (no margin), the result barely differs from the softmax loss.

Next, a comparison with the same 64-layer CNN and the same training data, changing only the loss:

LossLFWYTFMegaFace (identification, rank-1 rate among 1 million identities)MegaFace (verification, acceptance rate at a false accept rate of 10−610^{-6})
Softmax loss97.88%93.1%54.855%65.925%
Softmax loss + Contrastive Loss98.78%93.5%65.219%78.865%
Triplet Loss98.70%93.4%64.797%78.322%
L-Softmax loss99.10%94.0%67.128%80.423%
Softmax loss + Center loss99.05%94.4%65.494%80.146%
A-Softmax loss (SphereFace)99.42%95.0%72.729%85.561%

In the appendix comparison (a small 4-layer CNN, LFW), accuracy rose with each added change: removing the ReLU on the FC1 output (95.13% → 96.37%), removing the bias (96.40%), normalizing the weights (96.63%), and using the A-Softmax loss with m=4m = 4 (98.20%).

The highest MegaFace values (identification 75.766%, verification 89.142%) come from an ensemble that concatenates three features extracted from three crops of the face. To see the effect of the loss alone, use the values in the table above, where only the loss is changed on the same network.

Practical Considerations

The A-Softmax loss alone can be hard to get training started. The paper's appendix replaces the target-class logit with λ∥x∥cos⁡θ+∥x∥ψ(θ)1+λ\dfrac{\lambda \lVert x \rVert \cos\theta + \lVert x \rVert \psi(\theta)}{1 + \lambda}, starting with a very large λ\lambda (almost the same as the ordinary softmax loss) and decreasing it during training, an annealing strategy. It states that for most face experiments lowering λ\lambda to 5 is enough, and that going smaller may improve performance but makes training harder. The dashed line on the right side of the figure at the top is the curve for λ=5\lambda = 5, whose margin is much weaker than ψ(θ)\psi(\theta) itself.

Keep the following points in mind as well.

  • mm is an integer: Because differentiation uses the multiple-angle formula, mm in the paper is an integer. The later ArcFace paper reports that by computing θ=arccos⁡(cos⁡θ)\theta = \arccos(\cos\theta) and working with the angle directly, SphereFace with a non-integer m=1.35m = 1.35 could be trained without convergence problems.
  • The feature norm is not normalized: SphereFace normalizes only the weights, and the logit is multiplied by the feature norm ∥x∥\lVert x \rVert. The later CosFace and ArcFace also normalize features to unit length and multiply by a constant ss.
  • The margin size depends on the angle between class weights: The two-class margin m−1m+1 θ12\frac{m-1}{m+1}\,\theta_{12} is proportional to the angle θ12\theta_{12} between the weights. The CosFace paper cites as weaknesses of the A-Softmax loss that the margin becomes smaller for similar-looking classes (classes whose weights are at a small angle) and that the piecewise function ψ\psi is needed.
  • The classification layer is not used at test time: Verification uses only the FC1 feature and compares the cosine similarity of the features of two faces. The paper concatenates the features of the original image and its horizontally flipped version into a single feature. The classification-layer weights WW are discarded at test time.
  • PyTorch has no built-in version: torch.nn has no A-Softmax loss, so it must be written by hand (see the implementation example below).

Comparison with Other Methods

The figure below shows, for the same two classes (with an angle of 90° between the class weights W1W_1 and W2W_2), which feature directions each of the three losses accepts as correct. The graph at the bottom shows how wide the gap (margin) between the two decision boundaries becomes as the angle between W1W_1 and W2W_2 changes, computed from each paper's formula and settings.

Comparison of SphereFace, CosFace, and ArcFace. The top row shows the same two classes, shading the directions on the unit circle classified as class 1, as class 2, and as neither, for SphereFace (m = 4), CosFace (m = 0.35), and ArcFace (m = 0.5) from left to right. The bottom graph plots the angle between class weights on the horizontal axis and the margin width on the vertical axis: SphereFace grows in proportion to the angle, CosFace narrows as the angle grows, and ArcFace stays constant at m

All three losses normalize the weights to unit length and reduce only the target-class logit; they differ in where the margin goes, in the angle or in the cosine.

Loss functionTarget-class logitHow the margin is appliedFeature normCondition for class 1 (2 classes)Margin width (2 classes)Paper setting
No margin (softmax with normalized weights)∥x∥cos⁡θ\lVert x \rVert \cos\theta or scos⁡θs \cos\thetaNone—θ1<θ2\theta_1 < \theta_20 (a single boundary)—
SphereFace∥x∥ ψ(θ)\lVert x \rVert\, \psi(\theta), ψ(θ)=cos⁡(mθ)\psi(\theta) = \cos(m\theta)Multiply the angle by mmNot normalizedmθ1<θ2m\theta_1 < \theta_2m−1m+1 θ12\frac{m-1}{m+1}\,\theta_{12} (proportional to the angle between weights)m=4m = 4
CosFaces (cos⁡θ−m)s\,(\cos\theta - m)Subtract mm from the cosineFixed to sscos⁡θ1−m>cos⁡θ2\cos\theta_1 - m > \cos\theta_2Varies with the angle between weights (narrower at larger angles)m=0.35m = 0.35, s=64s = 64
ArcFacescos⁡(θ+m)s \cos(\theta + m)Add mm to the angleFixed to ssθ1+m<θ2\theta_1 + m < \theta_2Always mmm=0.5m = 0.5, s=64s = 64

In the table, θ1\theta_1 and θ2\theta_2 are the angles between the feature xx and the class weights W1W_1 and W2W_2, and θ12\theta_{12} is the angle between W1W_1 and W2W_2.

It differs from losses that use Euclidean-distance margins (Triplet Loss, Contrastive Loss, Center loss) in that no sample combinations need to be selected and features are compared by angle.

Rules of thumb for choosing:

  • For new use today, start with ArcFace or CosFace: In the ArcFace paper, with the same network and training data, CosFace and ArcFace achieved higher accuracy than SphereFace (m=1.35m = 1.35). Neither needs a piecewise function or annealing, and both are simple to implement.
  • To understand the idea of margins, read SphereFace first: SphereFace was the first to bring angular margins into face recognition and explain them as geometry on the unit hypersphere. CosFace and ArcFace replace this idea with forms that are easier to handle.
  • If you can afford the effort of selecting combinations, Triplet Loss is also a candidate: Triplet Loss has no classification layer, so the size of the weights WW does not grow even with a very large number of classes.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F


class AngleLinear(nn.Module):
    """SphereFace classification layer: weights normalized to unit length, no bias"""

    def __init__(self, in_features, num_classes):
        super().__init__()
        self.weight = nn.Parameter(torch.empty(num_classes, in_features))
        nn.init.xavier_uniform_(self.weight)

    def forward(self, x):
        w = F.normalize(self.weight, dim=1)                  # ‖W_j‖ = 1
        cos = F.linear(F.normalize(x, dim=1), w)             # cos θ_j
        return cos.clamp(-1 + 1e-7, 1 - 1e-7), x.norm(dim=1, keepdim=True)


def psi(theta, m):
    """Eq. (7): ψ(θ) = (−1)^k cos(mθ) − 2k, θ ∈ [kπ/m, (k+1)π/m]"""
    k = torch.floor(theta * m / math.pi).clamp(max=m - 1)
    sign = 1.0 - 2.0 * torch.remainder(k, 2)                # (−1)^k
    return sign * torch.cos(m * theta) - 2.0 * k


class ASoftmaxLoss(nn.Module):
    def __init__(self, m=4):
        super().__init__()
        self.m = m

    def forward(self, cos, x_norm, labels, lam=0.0):
        # The paper computes cos(mθ) with the multiple-angle formula; here it is computed from θ = arccos(cos θ) (same value)
        cos_t = cos.gather(1, labels[:, None])
        theta_t = torch.acos(cos_t)
        # Annealing from Appendix G: (λ cos θ + ψ(θ)) / (1 + λ). Larger λ is closer to the ordinary softmax
        target = (lam * cos_t + psi(theta_t, self.m)) / (1.0 + lam)
        logits = cos.scatter(1, labels[:, None], target) * x_norm   # multiply by the feature norm ‖x‖
        return F.cross_entropy(logits, labels)


# Feature network (no ReLU after the last layer) and the classification layer
backbone = nn.Sequential(nn.Flatten(), nn.Linear(3 * 112 * 96, 512), nn.PReLU(), nn.Linear(512, 512))
head = AngleLinear(512, num_classes=10575)
criterion = ASoftmaxLoss(m=4)
optimizer = torch.optim.SGD(list(backbone.parameters()) + list(head.parameters()), lr=0.1, momentum=0.9)

backbone.train()
for it in range(3):
    images = torch.randn(8, 3, 112, 96)
    labels = torch.randint(0, 10575, (8,))
    # Lower λ from a large value down to 5 (the paper gives no schedule formula; this is one example)
    lam = max(5.0, 1000.0 / (1 + 0.1 * it))
    cos, x_norm = head(backbone(images))
    loss = criterion(cos, x_norm, labels, lam=lam)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Test: skip the classification layer and verify by cosine similarity of features
backbone.eval()
with torch.no_grad():
    a, b = backbone(torch.randn(1, 3, 112, 96)), backbone(torch.randn(1, 3, 112, 96))
    score = F.cosine_similarity(a, b)   # same person if above a threshold

FAQ

Q. Why is m an integer in SphereFace?
A.

Because the paper rewrites cos⁡(mθ)\cos(m\theta) as a polynomial in cos⁡θ\cos\theta using the multiple-angle formula and differentiates an expression in the weights WW and the feature xx only. The multiple-angle formula works only for integer mm. The later ArcFace paper reports that SphereFace could be trained with a non-integer mm (for example 1.35) by computing the angle directly with arccos⁡\arccos.

Q. How do SphereFace and the L-Softmax loss differ?
A.

Both put a margin on the angle, but the L-Softmax loss does not normalize the weights and was proposed as a regularizer for classification with a fixed set of classes. SphereFace (the A-Softmax loss) normalizes the weights to unit length and removes the bias so that decisions depend only on the angle, and it learns features for face recognition that matches people unseen in training. In the paper's comparison (LFW), SphereFace scored 99.42% against 99.10% for the L-Softmax loss.

Q. How is face verification done after training?
A.

The classification layer is discarded, and only the feature output by the network (the 512-dimensional FC1 output in the paper) is used. The cosine similarity between the features of two faces is computed, and they are judged to be the same person if it exceeds a threshold. To identify someone, the person with the highest similarity among the enrolled faces is chosen.

References

  1. W. Liu, Y. Wen, Z. Yu, M. Li, B. Raj, and L. Song, "SphereFace: Deep Hypersphere Embedding for Face Recognition," CVPR, 2017.
  2. H. Wang, Y. Wang, Z. Zhou, X. Ji, D. Gong, J. Zhou, Z. Li, and W. Liu, "CosFace: Large Margin Cosine Loss for Deep Face Recognition," CVPR, 2018.
  3. J. Deng, J. Guo, N. Xue, and S. Zafeiriou, "ArcFace: Additive Angular Margin Loss for Deep Face Recognition," CVPR, 2019.