AI Logic

Loss Functions

ArcFace

Updated:

Diagram of ArcFace. The left panel 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 (an upper margin of 29°), together with a class-1 feature x and its angles θ1 and θ2 to W1 and W2. The right panel plots the logit against the angle θ to the target class, overlaying cos θ (no margin) and cos(θ + m) (m = 0.5); an arrow shows that adding m to θ shifts the curve to the left, and a band marks the range of θ during training (about 30° to 90°). A legend is on the far right

Background and overview

ArcFace is a loss function that normalizes both the features and the weights of the classification layer to unit length, adds a constant mm to the angle θ\theta between a feature and the weight of its target class, converts the result back with cos, and then computes the loss with softmax and cross-entropy. The paper calls it the Additive Angular Margin Loss. Deng et al. proposed it in 2019 for face recognition.

L=−1N∑i=1Nlog⁡escos⁡(θyi+m)escos⁡(θyi+m)+∑j≠yiescos⁡θjL = -\frac{1}{N} \sum_{i=1}^{N} \log \frac{e^{s \cos(\theta_{y_i} + m)}}{e^{s \cos(\theta_{y_i} + m)} + \sum_{j \neq y_i} e^{s \cos\theta_{j}}}

θj\theta_j is the angle between the feature xix_i and the weight WjW_j of class jj, yiy_i is the target class, ss is a constant multiplied into every logit (the scale), and mm is the margin. The paper uses s=64s = 64 and m=0.5m = 0.5 (radians, about 28.6°).

There were two main ways to train face recognition networks.

  • Train as classification (softmax loss): People seen in training can be separated, but the features are not discriminative enough to tell apart people not seen in training. The size of the classification layer's weight WW also grows in proportion to the number of identities.
  • Learn the embedding directly (Triplet Loss): The number of triplets explodes with the amount of data, and selecting triplets that are useful for training becomes difficult.

Along the line of improving the classification loss, Center loss pulls features of the same class toward the class center, SphereFace introduced a margin that multiplies the angle by mm, and CosFace a margin that subtracts mm from the cosine. The ArcFace paper notes that SphereFace relies on a series of approximations, which makes training unstable and requires mixing it with the ordinary softmax loss, and that CosFace is simpler and performs better. Building on this, it proposes adding mm directly to the angle.

When features and weights have unit length, the angle equals the arc length on the unit hypersphere (the geodesic distance). Adding mm to the angle therefore means estimating the distance to the target class center on the hypersphere as mm farther in arc length. The left side of the figure at the top shows the decision regions when the two class weights are 90° apart: a band of about 29°, equal to mm, is classified as neither class.

Theory (how the loss is computed)

The ArcFace loss is computed in the following steps (Figure 2 and Algorithm 1 of the paper).

  1. Extract features: A CNN (ResNet50 and ResNet100 in the paper; see ResNet) extracts a 512-dimensional feature xix_i from a face image. After the last convolutional layer, the paper places batch normalization, dropout, a fully connected layer, and batch normalization to produce the feature.
  2. Normalize features and weights to unit length: Set ∥xi∥=1\lVert x_i \rVert = 1 and ∥Wj∥=1\lVert W_j \rVert = 1, and fix the bias at 0. The output of the fully connected layer, Wj⊤xiW_j^{\top} x_i, is then exactly cos⁡θj\cos\theta_j.
  3. Get the angle of the target class: From the target-class value, compute θyi=arccos⁡(Wyi⊤xi)\theta_{y_i} = \arccos(W_{y_i}^{\top} x_i).
  4. Add mm to the angle and convert back with cos: Replace only the target-class value with cos⁡(θyi+m)\cos(\theta_{y_i} + m). The other classes keep cos⁡θj\cos\theta_j.
  5. Multiply by the scale ss and compute the loss with softmax and cross-entropy: Multiply every value by ss and compute LL in the equation above. Multiplying by ss corresponds to placing the features on a hypersphere of radius ss; if the values stayed within −1-1 to 11, the softmax probabilities would barely differ. From here on, everything is identical to the ordinary softmax loss.

For example, if the angle to the target class is 60°, the logit without a margin is 64cos⁡60°=32.064 \cos 60° = 32.0, while ArcFace gives 64cos⁡(60°+28.6°)≈1.564 \cos(60° + 28.6°) \approx 1.5 (CosFace with m=0.35m = 0.35 gives 64×(0.5−0.35)=9.664 \times (0.5 - 0.35) = 9.6). To get the same score, the angle has to shrink by about 28.6°. The right side of the figure at the top plots this relationship over the whole range of angles: the ArcFace curve is cos⁡θ\cos\theta shifted left by mm.

With two classes, the condition for being classified as class 1 is cos⁡(θ1+m)>cos⁡θ2\cos(\theta_1 + m) > \cos\theta_2, that is, θ1+m<θ2\theta_1 + m < \theta_2. The same holds for class 2, so between the two boundaries there is a margin exactly mm wide in angle. This width does not change however far apart the two class weights are.

The ArcFace paper unifies the margins of SphereFace, ArcFace, and CosFace in a single expression. Writing the target-class logit as s (cos⁡(m1θ+m2)−m3)s\,(\cos(m_1 \theta + m_2) - m_3), m1m_1 corresponds to SphereFace (multiply the angle), m2m_2 to ArcFace (add to the angle), and m3m_3 to CosFace (subtract from the cosine). The paper also tries combinations of the three, such as (m1,m2,m3)=(1,0.3,0.2)(m_1, m_2, m_3) = (1, 0.3, 0.2) and (0.9,0.4,0.15)(0.9, 0.4, 0.15).

Why the features become discriminative

There are three reasons ArcFace produces features that can distinguish people not seen during training.

  • The weights act as class centers: Once features and weights are normalized to unit length, the classification-layer weight WjW_j represents the direction on the hypersphere where features of class jj gather. Adding mm to the target-class angle applies two forces at once: one that pulls features toward their own class center (intra-class compactness) and one that pushes them away from other class centers (inter-class discrepancy). In the paper's angle statistics, the mean angle between the trained weight WjW_j and the actual feature center was 44.26° for the normalized softmax loss without a margin, but 14.29° for ArcFace, so the weights matched the class centers closely.
  • The margin is a constant distance on the hypersphere: Because the angle is exactly the arc length on the hypersphere, mm gives a margin of the same distance for every pair of classes. The margins of SphereFace (multiply the angle) and CosFace (subtract from the cosine), viewed as angles, vary with the angle between classes (see the figure in "Comparison with other methods").
  • The logit drops enough over the range of angles seen during training: The paper reports that the angle between a feature and its target weight starts at about 90° from random initialization and ends at about 30° by the end of training (the band on the right of the figure at the top). It argues that where the target logit starts, where it ends, and how steeply it falls over this range determine performance, and compares the curves of the three margins.

Adding to ArcFace a loss that shrinks intra-class angles (Intra), a loss that pushes class centers apart (Inter), or a loss that puts a margin on triplet angles (Triplet) did not improve performance. The paper interprets this as ArcFace alone already providing intra-class compactness, inter-class discrepancy, and a classification margin.

As an analogy, each class weight is a "town center" on a globe, and ArcFace follows the rule "always add the same mm kilometers to the distance from your own town center, then decide which town is closest." For your own town to still be the closest even with the extra mm kilometers, face features are drawn close to their own town center.

Experimental results

Using the same network (ResNet50) and the same training data (CASIA-WebFace, about 10,000 identities and 500,000 images), the paper changed only the loss and compared verification accuracy. SphereFace and CosFace were re-implemented by the authors using the unified expression above.

LossLFWCFP-FP (frontal vs. profile)AgeDB-30 (age gap)
ArcFace (m=0.4m = 0.4)99.53%95.41%94.98%
ArcFace (m=0.45m = 0.45)99.46%95.47%94.93%
ArcFace (m=0.5m = 0.5)99.53%95.56%95.15%
ArcFace (m=0.55m = 0.55)99.41%95.32%95.05%
SphereFace (m=1.35m = 1.35)99.11%94.38%91.70%
CosFace (m=0.35m = 0.35)99.51%95.44%94.56%
Combined (1, 0.3, 0.2)99.48%95.12%94.38%
Softmax loss99.08%94.39%92.33%
Normalized softmax loss (no margin)98.56%89.79%88.72%
Triplet Loss (margin 0.35)98.98%91.90%89.98%
  • m=0.5m = 0.5 worked best: Among 0.4 to 0.55, m=0.5m = 0.5 gave the highest value on all three benchmarks.
  • Highest of the three margins: It edged out CosFace and beat SphereFace (m=1.35m = 1.35) by about 1.2 points on CFP-FP and about 3.5 points on AgeDB-30. The combined margin was better than SphereFace or CosFace alone but did not surpass ArcFace.
  • Without a margin, normalization hurts: The softmax loss with only the weights and features normalized scored lower than the ordinary softmax loss. Normalization pays off only when combined with a margin.

Trained on large data (MS1MV2, about 85,000 identities and 5.8 million images) with ResNet100, the model reached 99.83% on LFW, 98.02% on YTF, 92.08% on CPLFW (large pose variation), and 95.45% on CALFW (large age gap). On MegaFace (rank-1 identification among 1 million distractors, and verification rate at a false accept rate of 10−610^{-6}), ArcFace scored 81.03% and 96.98%, against 80.56% and 96.56% for CosFace retrained with the same MS1MV2 and ResNet100.

The paper found many wrong labels in the MegaFace evaluation data and also evaluated on a manually cleaned version (ArcFace: 98.35% and 98.48%). Values on the cleaned data cannot be compared directly with values other papers reported on the original data.

Practical considerations

Where θ+m\theta + m exceeds π\pi (180°), cos⁡(θ+m)\cos(\theta + m) is no longer monotonically decreasing. If the angle θ\theta to the target class is larger than π−m\pi - m, cos⁡(θ+m)\cos(\theta + m) increases as the angle grows, breaking the relation "smaller angle, higher score" (a property of the formula not discussed in the paper). This is rare because angles during training usually stay around 30° to 90°, but an implementation should decide how to handle this range. The figure at the top and the implementation example below clip θ+m\theta + m at π\pi.

Keep the following points in mind as well.

  • Watch the gradient of arccos⁡\arccos: When cos⁡θ\cos\theta is close to ±1\pm 1, the gradient of arccos⁡\arccos becomes very large. Implementations shrink cos⁡θ\cos\theta slightly into the interior of (−1,1)(-1, 1) before computing arccos⁡\arccos.
  • ss and mm are chosen as a pair: Following CosFace, the paper sets s=64s = 64 and picks m=0.5m = 0.5 after comparing 0.4 to 0.55. These values come from face data with about 10,000 to 85,000 identities; for tasks with a very different number of classes or feature dimension, tune them on validation data.
  • No need to mix with other losses: SphereFace was mixed with the ordinary softmax loss to stabilize training, but the paper states that ArcFace converges easily on its own with any training data.
  • The classification layer is not used at test time: Verification uses only the feature network (160 MB for ResNet50) and compares the cosine similarity of two face features with a threshold. For videos and templates, the mean of all image features is used.
  • The classification-layer weights grow with the number of identities: The weight WW has size (feature dimension) × (number of identities). The paper states that the extra computation is small, that current GPUs can train with millions of identities, and that even more identities can be handled with model parallelism across multiple GPUs.
  • PyTorch has no built-in version: torch.nn does not include an ArcFace loss, so the step that rewrites the fully connected layer's output has to be written by hand (see the implementation example below). Algorithm 1 in the paper is only a few lines as well.

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.

The ArcFace paper points out that only ArcFace has a margin of constant width in angle, while the margins of SphereFace and CosFace are not constant (nonlinear) when viewed as angles. As the bottom graph of the figure above shows, the closer the two class weights are, the smaller the SphereFace margin and the larger the CosFace margin.

It differs from losses based on Euclidean distance or triplets (Triplet Loss, Contrastive Loss, Center loss) in that no pair selection is needed and the margin sits between the class centers (weights) and the features. In the paper's comparison, putting the margin between features and class centers, as ArcFace does, was more effective than putting a margin on triplet angles.

Rules of thumb for choosing:

  • To learn features for verification with many classes, such as face recognition, start with ArcFace: Under equal conditions it scored highest of the three margins and trains stably without mixing in other losses.
  • To write it as simply as possible without arccos⁡\arccos, use CosFace: It only subtracts mm from the logit and performed almost as well as ArcFace.
  • Read SphereFace as the starting point of the idea rather than adopting it anew: It was the first to bring angular margins and hypersphere geometry into the loss, but it needs extra tricks to train stably.

PyTorch example

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


class ArcFaceHead(nn.Module):
    """ArcFace (Eq. (3), Algorithm 1): normalize features and weights to unit length, add m to the target-class angle, and multiply by s"""

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

    def forward(self, x, labels):
        cos = F.linear(F.normalize(x, dim=1), F.normalize(self.weight, dim=1))   # cos θ_j (no bias)
        cos = cos.clamp(-1 + 1e-7, 1 - 1e-7)            # keep the arccos gradient from blowing up near ±1
        theta = torch.acos(cos.gather(1, labels[:, None]))
        # cos(θ + m) starts increasing once θ + m exceeds π, so clip at π (one way to handle it)
        target = torch.cos((theta + self.m).clamp(max=math.pi))
        logits = cos.scatter(1, labels[:, None], target) * self.s   # cos(θ + m) only for the target class
        return F.cross_entropy(logits, labels)


backbone = nn.Sequential(
    nn.Flatten(), nn.Linear(3 * 112 * 112, 512), nn.BatchNorm1d(512), nn.Dropout(0.4),
    nn.Linear(512, 512), nn.BatchNorm1d(512),          # BN, Dropout, FC, BN as in the paper (the dropout rate is just an example)
)
head = ArcFaceHead(512, num_classes=10575, s=64.0, m=0.5)
optimizer = torch.optim.SGD(list(backbone.parameters()) + list(head.parameters()),
                            lr=0.1, momentum=0.9, weight_decay=5e-4)

backbone.train()                                       # BatchNorm and Dropout in training mode
images = torch.randn(8, 3, 112, 112)
labels = torch.randint(0, 10575, (8,))
loss = head(backbone(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()

# Test: skip the classification layer (head) and verify by the cosine similarity of features
backbone.eval()                                        # BatchNorm uses running statistics; Dropout is off
with torch.no_grad():
    a, b = backbone(torch.randn(1, 3, 112, 112)), backbone(torch.randn(1, 3, 112, 112))
    score = F.cosine_similarity(a, b)   # same person if above the threshold

FAQ

Q. Should I use ArcFace or CosFace?
A.

In the paper's comparison with the same network and training data, ArcFace (m=0.5m = 0.5) slightly outperformed CosFace (m=0.35m = 0.35) (LFW 99.53% vs. 99.51%, AgeDB-30 95.15% vs. 94.56%). ArcFace has a constant margin in angle, while CosFace needs no arccos⁡\arccos and is a little simpler to implement. If unsure, try ArcFace first, and if the difference is small, pick whichever is easier to work with.

Q. How many degrees is the margin m = 0.5?
A.

mm is in radians, and 0.5 radians is about 28.6°. The angle to the target class is overestimated by about 28.6° before the decision, so with two classes there is always a gap of about 28.6° between the two decision boundaries.

Q. What if the training labels contain many errors?
A.

A later version of the paper (v4 on arXiv) adds sub-center ArcFace, which gives each class several centers and only requires a feature to be close to one of them. Clean faces gather around the dominant center, while hard faces and mislabeled faces split off to other centers, which the paper reports makes training robust to label noise.

References

  1. J. Deng, J. Guo, N. Xue, and S. Zafeiriou, "ArcFace: Additive Angular Margin Loss for Deep Face Recognition," CVPR, 2019.
  2. W. Liu, Y. Wen, Z. Yu, M. Li, B. Raj, and L. Song, "SphereFace: Deep Hypersphere Embedding for Face Recognition," CVPR, 2017.
  3. 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.
  4. deepinsight/insightface (official ArcFace implementation)