AI Logic

Loss Functions

CosFace

Updated:

Diagram of CosFace. 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, lowered by m = 0.35, with an arrow at θ = 60° showing m being subtracted. A legend is on the far right

Background and overview

CosFace is a loss function that normalizes both the features and the weights of the classification layer to unit length, subtracts a constant mm from the target class's cosine similarity cos⁡θ\cos\theta, and then computes the loss with softmax and cross-entropy. The paper calls the loss the Large Margin Cosine Loss (LMCL) and the face recognition model trained with it CosFace. Wang et al. at Tencent AI Lab proposed it in 2018.

Llmc=1N∑i−log⁡es (cos⁡θyi−m)es (cos⁡θyi−m)+∑j≠yiescos⁡θjL_{\mathrm{lmc}} = \frac{1}{N} \sum_{i} -\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. Since both WjW_j and xix_i are normalized to unit length, cos⁡θj=Wj⊤xi\cos\theta_j = W_j^{\top} x_i.

To distinguish people not seen during training, face recognition requires features where the same person's features are close together and different people's features are far apart. The ordinary classification loss (which the paper calls the softmax loss; the same as cross-entropy) only separates classes and does not create this property well enough. Earlier improvements went in two directions.

  • Margins in Euclidean distance: Center loss only reduces intra-class variation and does not directly require classes to be far apart. Contrastive Loss and Triplet Loss require effort to select the combinations used for training.
  • Angular margins: SphereFace (the A-Softmax loss) created a margin by multiplying the target-class angle by mm. However, it needs a piecewise function to work around the non-monotonicity of cos, and the size of the margin also depends on the angle between classes.

Because faces are compared by cosine similarity at test time, CosFace puts the margin directly into the cosine value. The left side of the figure at the top shows the decision regions when the two class weights are 90° apart: with m=0.35m = 0.35, a band of about 29° between them is classified as neither class. The right side shows that the target-class logit is uniformly lowered by mm from cos⁡θ\cos\theta.

Theory (how the loss is computed)

LMCL is computed in the following steps.

  1. Extract features: A CNN extracts a feature vector x∗x^{*} from a face image. The paper uses the same 64-layer residual network as SphereFace (built from the same residual units as ResNet).
  2. Normalize features and weights to unit length: Set x=x∗/∥x∗∥x = x^{*} / \lVert x^{*} \rVert and Wj=Wj∗/∥Wj∗∥W_j = W_j^{*} / \lVert W_j^{*} \rVert, and fix the bias at 0. The output of the fully connected layer is then exactly cos⁡θj=Wj⊤x\cos\theta_j = W_j^{\top} x.
  3. Subtract mm from the target class: Replace only the value of the target class yiy_i with cos⁡θyi−m\cos\theta_{y_i} - m. The other classes keep cos⁡θj\cos\theta_j.
  4. Multiply by the scale ss: Multiply every value by ss. Because the features have unit length, the values fall in the narrow range −1-1 to 11, and as is the softmax probabilities would barely differ. ss corresponds to placing the features on a hypersphere of radius ss. The paper uses s=64s = 64.
  5. Compute the loss with softmax and cross-entropy: Compute LlmcL_{\mathrm{lmc}} in the equation above and update the feature network and WW by backpropagation.

For example, with s=64s = 64, m=0.35m = 0.35, and an angle of 60° to the target class, the logit is 64×(cos⁡60°−0.35)=64×0.15=9.664 \times (\cos 60° - 0.35) = 64 \times 0.15 = 9.6. Without the margin it would be 64×0.5=3264 \times 0.5 = 32, so the target score is heavily discounted, and lowering the loss requires a much smaller angle.

Comparing the conditions for being classified as class C1C_1 with two classes gives the following (Section 3.2 of the paper).

LossCondition for class C1C_1Margin
Softmax loss∥W1∥cos⁡θ1>∥W2∥cos⁡θ2\lVert W_1 \rVert \cos\theta_1 > \lVert W_2 \rVert \cos\theta_2Can be negative (the two classes overlap in cosine)
Normalized softmax loss (NSL)cos⁡θ1>cos⁡θ2\cos\theta_1 > \cos\theta_20
A-Softmax loss (SphereFace)cos⁡(mθ1)≥cos⁡θ2\cos(m\theta_1) \ge \cos\theta_20 or more (varies with the angle)
LMCL (CosFace)cos⁡θ1≥cos⁡θ2+m\cos\theta_1 \ge \cos\theta_2 + mPositive (width 2 m\sqrt{2}\,m in the cos⁡θ1\cos\theta_1–cos⁡θ2\cos\theta_2 plane)

With cos⁡θ1\cos\theta_1 on the horizontal axis and cos⁡θ2\cos\theta_2 on the vertical axis, the two LMCL boundaries are parallel lines with slope 1, separated by a width of 2 m\sqrt{2}\,m that applies equally to every feature. Viewed in angle, however, the width is not constant; as on the left of the figure at the top, it depends on the angle between the two weights (see the figure in "Comparison with other methods").

Why the features become discriminative

There are three reasons features learned with LMCL suit verification.

  • Training and testing use the same yardstick: Face verification usually compares the cosine similarity of two features. LMCL normalizes features and weights to unit length so that decisions depend only on the cosine value, and then puts the margin on that value. The gap opened during training becomes the gap in similarity at test time.
  • The feature norm offers no escape: Without feature normalization, the softmax loss lowers the loss using both the feature length (norm) and the cosine. The paper points out that easier samples get larger feature norms, weakening the cosine constraint. Moreover, if LMCL is used without normalization, then early in training, while cos⁡θi−m\cos\theta_i - m is smaller than cos⁡θj\cos\theta_j, the loss can be lowered by shrinking the feature norm, and optimization does not proceed well. The paper considers feature normalization essential, especially when training a network from scratch.
  • The function stays simple with the margin: cos⁡θ−m\cos\theta - m decreases monotonically in θ\theta, so no workaround like SphereFace's piecewise function ψ(θ)\psi(\theta) is needed.

The scale ss has a lower bound. With CC classes and PWP_W the minimum posterior probability expected at each class center, the paper gives

s≥C−1Clog⁡(C−1) PW1−PWs \ge \frac{C - 1}{C} \log \frac{(C - 1)\, P_W}{1 - P_W}

For example, with C=10,575C = 10{,}575 identities in CASIA-WebFace and PW=0.9P_W = 0.9, this gives about s≥11.5s \ge 11.5. More classes, or a higher required probability, call for a larger ss.

The margin mm has an upper bound as well. Assuming the weights are spread evenly over the hypersphere, the bound is 0≤m≤1−cos⁡(2π/C)0 \le m \le 1 - \cos(2\pi / C) for 2-D features, and 0≤m≤CC−10 \le m \le \frac{C}{C - 1} when the number of classes is small enough relative to the feature dimension KK (C≤K+1C \le K + 1); with more classes, the bound becomes even smaller. In the paper's 2-D experiment (8 identities), the bound is 1−cos⁡(π/4)≈0.291 - \cos(\pi/4) \approx 0.29, so it compares m=0,0.1,0.2m = 0, 0.1, 0.2 and confirms that larger mm widens the angular gaps between classes.

As an analogy, the softmax loss grades "pass if your score is higher than everyone else's," while CosFace grades "pass only if your score is at least mm points higher than everyone else's." Narrow wins are not accepted, so each class's features are pulled more strongly toward the direction of their own weight.

Experimental results

The paper first trained on the public CASIA-WebFace dataset (about 10,000 identities, 490,000 images) and compared losses using the same 64-layer CNN and settings as SphereFace, changing only the loss. Evaluation used LFW (photos) and YTF (videos) for face verification, and MegaFace Challenge 1 (MF1) with 1 million distractors.

LossLFWYTFMF1 identification (rank-1 rate)MF1 verification (acceptance at a false accept rate of 10−610^{-6})
Softmax loss97.88%93.1%54.85%65.92%
Softmax loss + Contrastive Loss98.78%93.5%65.21%78.86%
Triplet Loss98.70%93.4%64.79%78.32%
L-Softmax loss99.10%94.0%67.12%80.42%
Softmax loss + Center loss99.05%94.4%65.49%80.14%
A-Softmax loss (SphereFace)99.42%95.0%72.72%85.56%
A-Softmax loss + feature normalization99.32%95.4%75.42%88.82%
LMCL (CosFace)99.33%96.1%77.11%89.88%

On LFW it was nearly the same as SphereFace, and on YTF and MegaFace it scored higher than the other losses.

  • Effect of mm: Varying mm from 0 to 0.45, m=0m = 0 (no margin) was the lowest, LFW and YTF accuracy rose as mm grew, and it plateaued at m=0.35m = 0.35. With mm larger than 0.45, training did not converge. Subsequent experiments fix m=0.35m = 0.35.
  • Effect of feature normalization: At m=0.35m = 0.35, without feature normalization the results were 99.10% on LFW, 93.1% on YTF, and 75.10% on MF1 identification; with normalization they were 99.33%, 96.1%, and 77.11%, higher on every benchmark (the unnormalized model was first trained with the softmax loss and then switched to LMCL).

A model trained on large data of about 90,000 identities and 5 million images (combining public and private data) reached 99.73% on LFW and 97.6% on YTF.

Values such as 99.73% on LFW come from large training data that includes private data. To see the effect of the loss alone, use the table above, which compares losses on the same CASIA-WebFace and the same network.

Practical considerations

Choose mm and ss to match the number of classes and the feature dimension. If mm is too large, the condition cos⁡θ1−m>cos⁡θ2\cos\theta_1 - m > \cos\theta_2 can no longer be met and training does not converge (m>0.45m > 0.45 in the paper's face experiments). An overly large mm also makes the model sensitive to noise such as wrong labels. If ss is too small, the loss does not drop enough and may fail to converge. The paper's settings are s=64s = 64 and m=0.35m = 0.35.

Keep the following points in mind as well.

  • Keep the feature normalization: LMCL assumes features are normalized to unit length. Without normalization, shrinking the feature norm becomes a loophole for lowering the loss.
  • Fix ss instead of learning it: The paper finds it better to fix ss at a sufficiently large value than to learn it.
  • If classes are too close in angle, no gap can be opened: With two classes and θ12\theta_{12} the angle between the weights, when 1−cos⁡θ12<m1 - \cos\theta_{12} < m the condition cannot be met even if the feature lies exactly on its own weight (for m=0.35m = 0.35, when θ12\theta_{12} is below about 49.5°). Training pushes the weights apart beyond this.
  • The classification layer is not used at test time: Verification uses only the feature network and compares the cosine similarity of two face features with a threshold. The paper concatenates the features of the original image and its horizontally flipped version into a single feature.
  • PyTorch has no built-in version: torch.nn does not include LMCL, so the fully connected layer's output has to be rewritten by hand (see the implementation example below). The formula is simple, so it takes only a few lines.

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 unifies the three margins in a single expression, cos⁡(m1θ+m2)−m3\cos(m_1 \theta + m_2) - m_3, where m1m_1 corresponds to SphereFace, m2m_2 to ArcFace, and m3m_3 to CosFace. Compared in that paper with the same network (ResNet50) and training data (CASIA-WebFace), verification accuracy on LFW, CFP-FP, and AgeDB-30 was 99.51%, 95.44%, and 94.56% for CosFace (m=0.35m = 0.35) and 99.53%, 95.56%, and 95.15% for ArcFace (m=0.5m = 0.5), with ArcFace slightly ahead.

Rules of thumb for choosing:

  • If ease of implementation comes first, use CosFace: It only subtracts mm from the logit, with no arccos⁡\arccos and no piecewise function.
  • If a constant margin in angle is wanted, use ArcFace: CosFace's margin is constant in cosine, but in angle it varies with the angle between classes.
  • If you can afford the effort of selecting combinations and there are very many classes, Triplet Loss is also a candidate: CosFace keeps a classification-layer weight WW for every class, so it grows with the number of identities.

PyTorch example

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


class CosFaceHead(nn.Module):
    """LMCL (Eqs. (4) and (5)): normalize features and weights to unit length, subtract m from the target-class cos, and multiply by s"""

    def __init__(self, in_features, num_classes, s=64.0, m=0.35):
        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)
        one_hot = F.one_hot(labels, cos.size(1)).to(cos.dtype)
        logits = self.s * (cos - self.m * one_hot)       # cos θ − m only for the target class
        return F.cross_entropy(logits, labels)


backbone = nn.Sequential(nn.Flatten(), nn.Linear(3 * 112 * 96, 512), nn.PReLU(), nn.Linear(512, 512))
head = CosFaceHead(512, num_classes=10575, s=64.0, m=0.35)
optimizer = torch.optim.SGD(list(backbone.parameters()) + list(head.parameters()),
                            lr=0.1, momentum=0.9, weight_decay=5e-4)

backbone.train()
images = torch.randn(8, 3, 112, 96)
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()
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 the threshold

FAQ

Q. How should the scale s be chosen?
A.

From the number of classes CC and the minimum probability PWP_W expected at each class center, the paper gives the lower bound s≥C−1Clog⁡(C−1)PW1−PWs \ge \frac{C-1}{C}\log\frac{(C-1)P_W}{1-P_W}. With about 10,000 identities and PW=0.9P_W = 0.9, the bound is about 11.5, and more classes require a larger ss. The paper's experiments fix s=64s = 64 to leave room to spare.

Q. Does performance keep improving as the margin m grows?
A.

Up to a point. In the paper's face experiments, LFW and YTF accuracy rose as mm grew from 0 and plateaued at m=0.35m = 0.35. Once mm exceeded 0.45, the condition could not be met and training did not converge. The theoretical upper bound also shrinks as the number of classes grows, so with many classes, start from a modest value.

Q. Are CosFace and AM-Softmax the same thing?
A.

Both are margin losses that subtract a constant from the target-class cosine, published independently around the same time. The ArcFace paper cites AM-Softmax (Wang et al., 2018) alongside CosFace and treats both as losses with a margin subtracted from the cosine (cos⁡θ−m\cos\theta - m).

References

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