PyramidBox: A Context-assisted Single Shot Face Detector
- Publication
- ECCV 2018Conference
- First submitted to arXiv
- arXiv:1803.07737
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{objectdetectionpyramidbox2018,
title = {{PyramidBox: A Context-assisted Single Shot Face Detector}},
author = {Xu Tang and Daniel K. Du and Zeqiang He and Jingtuo Liu},
year = {2018},
eprint = {1803.07737},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1803.07737}
}
In a big group photo from a school sports day, the faces in the back row might be only 10 pixels wide, a little blurred, and half hidden by the people in front. Look at just those 10×10 pixels and the eyes and nose melt into one smudge; it's hard to say it's a face at all.
Yet people looking at the photo rarely miss it. Above the face there's a ring of hair, below it the neck and shoulders; the whole head is about 20 pixels, 40 with the shoulders, and these outlines are much clearer than the face itself. We see a person first, and only then infer that there's a face there.
PyramidBox is Baidu's 2018 face detector, and it wants the network to learn this kind of inference too. The paper states its starting point right at the beginning, that hard faces lack visual consistency, while the larger regions around them (head, body) are easier to locate and classify. The problem is that WIDER FACE labels only faces; nobody labeled heads or bodies. Without labels, how do you get the network to learn head and body features?
Defining the Problem
Starting From S3FD
PyramidBox didn't design a detector from scratch. It takes S3FD's backbone and anchors as they are and adds things on top, one at a time; the baseline in its ablations is S3FD.
S3FD's skeleton is VGG16 from conv1_1 to pool5, with fc6 and fc7 turned into convolutions and two more groups of convolutions added after them, giving six detection layers: conv3_3, conv4_3, conv5_3, conv_fc7, conv6_2 and conv7_2. With a input, the six layers have strides of 4, 8, 16, 32, 64 and 128, and each position gets one square anchor four times the stride, from 16 to 512 pixels. An anchor whose IoU (intersection area divided by union area) with a ground-truth box exceeds 0.35 is a positive; the shallowest layer, conv3_3, also predicts three background scores and takes the maximum to suppress false positives from small anchors, which is called the max-out background label.
Evaluation uses WIDER FACE, with 32,203 images and 393,703 face boxes, split by difficulty into Easy, Medium and Hard. The split depends on whether EdgeBox, a traditional proposal method, can find the face, which is strongly tied to face size; Hard is mostly small, blurred and occluded faces. The score is AP. A detection counts as correct if its IoU with a labeled box exceeds 0.5; sort the detections by score and draw the precision–recall curve, and AP is the area under it.
The S3FD baseline in the PyramidBox paper scores 94.0, 92.7 and 84.2 (Easy, Medium, Hard) on the WIDER FACE validation set.
Context Isn't Being Used Well Yet
Using context to find small faces isn't new. SSH attaches a context module after each detection layer to enlarge the receptive field (the input region one cell of the feature map can see); CMS-RCNN additionally pulls features from the body region in a two-stage detector. In the introduction, the authors list three gaps that are still open; add one item on data sampling and there are four in all.
- Context features have no supervision. Anchor labels come only from face boxes, and the network is never told "this patch is a head" or "this patch is a shoulder." A large receptive field can see the head and body, but no signal asks it to learn head and body features.
- High-level features don't necessarily help small faces. FPN starts from the deepest layer and sends semantic features all the way down to the shallow layers. S3FD's two deepest layers, conv7_2 and conv6_2, have receptive fields of 724 and 468 pixels, while training images are only 640, so what these two layers see is mostly noise unrelated to small faces.
- The prediction branch is too thin. In SSD and S3FD, classification and regression are a single convolution. SSH made the prediction module wider and DSSD made it deeper, and nobody had put the two together yet.
- Small-face samples aren't diverse enough. The authors argue that the diversity of hard samples matters for learning representative features, and that cross-scale data augmentation can supply it, for example by shrinking a clear large face into a small one.
Solving the Problem
The Big Picture

Read this figure from top to bottom.
The top box is S3FD's backbone. The second is LFPN (low-level feature pyramid network), which fuses top-down starting from conv_fc7 and produces three levels, lfpn_0, lfpn_1 and lfpn_2, at the resolutions of conv5_3, conv4_3 and conv3_3 respectively. The six detection layers thus become lfpn_2, lfpn_1, lfpn_0, conv_fc7, conv6_2 and conv7_2, with anchors still from 16 to 512.
The third box is CPM (context-sensitive prediction module), one after each detection layer. Each CPM outputs 20 channels and predicts heads and bodies as well as faces:
- 4 channels for face classification (the max-in-out described below uses them);
- 2 channels each for head and body classification;
- 4 channels each for face, head and body box regression.
The bottom box is the loss. The red, green and blue arrows stand for the face, head and body predictions; every green arrow shifts one step left and every blue one two steps. Each plus node collects the three targets for faces of one size, the face itself on its own level, its head one level up and its body two levels up. This is PyramidAnchors, worked through in detail below.
At inference only the face branch is used and the head and body outputs are simply discarded, so PyramidAnchors adds no inference cost. LFPN and CPM, on the other hand, are real extra computation, and the paper reports no speed.
LFPN: A Feature Pyramid That Starts in the Middle
FPN starts from the deepest layer, upsamples its features by two, adds them to the layer below, and works its way down. PyramidBox argues that for small faces, the deepest few layers mostly contribute noise, so it starts from the middle instead.
Which layer to start from? The authors' rule is that the starting layer's receptive field should be about half the input. The receptive fields of S3FD's five layers from conv4_3 to conv7_2 are 108, 228, 340, 468 and 724 (including the prediction convolution); divided by 640 they're 0.17, 0.36, 0.53, 0.73 and 1.13, and the closest to one half is conv_fc7's 0.53. The authors tried every possible starting point:
| Start | RF/640 | Easy | Medium | Hard |
|---|---|---|---|---|
| Baseline | – | 94.0 | 92.7 | 84.2 |
| conv7_2 | 1.13 | 93.9 | 92.9 | 85.9 |
| conv6_2 | 0.73 | 94.1 | 93.1 | 85.9 |
| conv_fc7 | 0.53 | 94.3 | 93.3 | 86.1 |
| conv5_3 | 0.36 | 94.1 | 93.1 | 85.7 |
| conv4_3 | 0.17 | 93.6 | 92.5 | 84.8 |
Compiled from Table 1 of the paper, WIDER FACE validation AP (%). RF/640 is the starting layer's receptive field divided by the input side; the baseline does no fusion, starting from conv7_2 is standard FPN, and conv_fc7 is LFPN's choice.
Starting from conv_fc7 gives the highest Hard, 1.9 above the baseline. But of that 1.9, standard FPN starting from the top layer already gets 1.7, and moving the starting point adds only another 0.2. Starting too low doesn't work either; from conv4_3 the gain is only 0.6. Top-down fusion itself is the big part, and the starting point is fine-tuning.
The fusion itself is shown in Fig. 3(a).

Let's follow a 640×640 input through it, with shapes worked out from the official PaddlePaddle code.
- conv_fc7 is . A convolution first reduces it to 512 channels, and it is then upsampled by two to .
- conv5_3 is and also passes through a convolution, with the channel count unchanged.
- The two are multiplied element-wise, giving lfpn_0, .
- Repeat with lfpn_0 as the upper layer and conv4_3 as the lower one to get lfpn_1, ; do it once more with conv3_3 to get lfpn_2, . Each convolution aligns the upper layer's channel count to the lower layer's.
The upsampling uses a transposed convolution, but its weights are initialized to bilinear interpolation and its learning rate is set to 0, so it amounts to a fixed bilinear upscaling.
Step 3 is where LFPN departs from FPN. FPN adds. The paper's text says LFPN's blocks are "as same as FPN," yet the figure is labeled element-wise product, and the official code does multiply (with the comment # eltwise mul). The PyramidBox++ paper a year later states outright that LFPN uses element-wise product rather than summation.
Multiplication works like a gate. Where the upper layer's response at some position is close to 0, the lower layer's detail features at the same position are suppressed too; only where the upper layer responds strongly do the lower layer's features get amplified. The paper runs no comparison between adding and multiplying, so there's no telling what this choice actually buys.
CPM: A Prediction Module Both Wide and Deep
CPM wants both SSH's width and DSSD's depth.
SSH's context module has three branches, one a single convolution, one a stack of two, and one a stack of three (the last two share their first layer). Two stacked layers have the receptive field of one , and three that of a , so each branch sees a wider area than the one before, and in the end they're concatenated. DSSD adds a residual block before prediction.
The paper's CPM follows SSH's three-branch structure and replaces each convolution layer with a DSSD-style prediction module (without the residual connection); those are the stacks of blocks labeled 1024, 256, 256 in Fig. 3(b). The output then goes through one more convolution to produce the 20 channels mentioned above. On lfpn_2, at stride 4, every extra stacked adds 8 pixels of receptive field.
The CPM in the official code doesn't look like this figure. It starts with a DSSD residual block (a shortcut plus a , , bottleneck), followed by a plain, unmodified SSH context module, whose three branches of 256, 128 and 128 channels concatenate to 512. The README itself explains that the open-source model's CPM is "slightly different" from the paper's and faster to train and test. In June 2020 a user in issue #4711 drew diagrams comparing the two and said the code didn't match the paper's diagram at all; the maintainer's answer was that they had redesigned it a bit.
Max-in-out
On conv3_3, S3FD has each anchor output 3 background scores and 1 face score, takes the maximum background score and then applies softmax. PyramidBox extends the trick to both sides. It first predicts scores, takes the maximum of the positive scores as "face" and the maximum of the negative scores as "background."
- The first prediction module (lfpn_2, anchor 16): , , the same as S3FD, because small anchors have the messiest backgrounds.
- The other five modules: , , the other way round, giving the face three chances in order to recall more faces.
So face classification has 4 channels on every level, which is where the "4 channels for face classification" in the CPM output comes from. As an example, say a 32-pixel anchor has the three face scores and a background score of 1.0. The largest face score, 1.9, is compared against the background, and the face probability is ; with only one face channel, that channel would have to learn what every kind of face looks like on its own.
PyramidAnchors: Heads and Bodies Nobody Labeled
This is PyramidBox's central design. WIDER FACE has only face boxes, and the authors' assumption is that regions taken relative to the face, at a fixed ratio and offset, have similar context features across different faces. In other words, enlarge the face box two times and what's inside is roughly the head; four times, and it's roughly the head plus shoulders and upper body. These boxes aren't precise, and the paper calls the approach semi-supervised.
The label is defined in equation (1):
To fit narrow screens, the paper's is shortened here to , to and threshold to , and the shrunk anchor is written separately as . is the -th anchor on level , is that level's stride, is its region in the original image, and dividing by gives the shrunk ; is the face box. stand for face, head and body. because the strides of adjacent levels differ by a factor of two; , the same as S3FD's matching threshold.
The equation says to shrink the anchor by a factor of and then compute its IoU with the face box. At , a 32-pixel anchor shrinks to 16 pixels and is compared against a 16-pixel face; put the other way round, the 32-pixel anchor learns that face's head. Here it is worked out for a 16-pixel face.

The 16-pixel face lands on P0 (lfpn_2, anchor 16), where 9 anchors have IoU above 0.35, the one in the very center at 1.00. Its head is a 32-pixel box centered on the face at twice its size, handled by P1 (lfpn_1, anchor 32), which matches 10 anchors, the best at 0.78. Its body is a 64-pixel box at four times the size, handled by P2 (lfpn_0, anchor 64), which also matches 10, the best at 0.70.
Take a 128-pixel face instead, and the face is on P3 (conv_fc7), the head on P4 (conv6_2, 256) and the body on P5 (conv7_2, 512). A 256-pixel face finds no 1,024-pixel anchor, so only two targets are left, face and head; a 512-pixel face has only itself. The smaller the face, the more complete the context supervision it gets.
How does this head and body supervision help small faces? P1's head branch learns "the heads of those small faces on P0," and P1 is in turn fused down into P0 through LFPN. The head supervision teaches P1's features to recognize heads, and these features are sent back to the shallowest level to help with small faces.
The official PaddlePaddle code goes about it more directly. As the data is read in, each face box is expanded by half a face in each of the four directions and used as the head box:
def expand_bboxes(bboxes,
expand_left=2.,
expand_up=2.,
expand_right=2.,
expand_down=2.):
"""
Expand bboxes, expand 2 times by defalut.
"""
expand_boxes = []
for bbox in bboxes:
xmin = bbox[0]
ymin = bbox[1]
xmax = bbox[2]
ymax = bbox[3]
w = xmax - xmin
h = ymax - ymin
ex_xmin = max(xmin - w / expand_left, 0.)
ex_ymin = max(ymin - h / expand_up, 0.)
ex_xmax = min(xmax + w / expand_right, 1.)
ex_ymax = min(ymax + h / expand_down, 1.)
expand_boxes.append([ex_xmin, ex_ymin, ex_xmax, ex_ymax])
return expand_boxes
The coordinates are normalized to 0 to 1, so the box is clipped to the image at the end. The network then runs the same anchor matching and loss on the head boxes as on the faces (again with a threshold of 0.35). The paper shrinks the anchor to compare it with the face, the code enlarges the face to compare it with the anchor, and both are after the same thing.
The code has no body. In March 2020 a user asked about it in issue #4446, and the maintainer replied that adding the body does help, but only a little, and it lengthens training, so it wasn't implemented. Face and head losses have equal weights (issue #1371).
Loss: One Term per Target
PyramidBox's loss is a weighted sum over the three targets, equations (2) and (3):
Each has the same form as S3FD's loss. is the probability that anchor is a target of type and is the label from equation (1); classification uses a two-class log loss, regression uses smooth L1, and only positives count toward regression. The paper gives no values for or the three .
The regression targets are derived from the face box, in equation (5). Writing the face box as its top-left corner , width and height , the box of the -th target is
and are scale factors for width and height, and and are offsets. Plugging in the paper's settings:
- Head (): , , giving , the same box the code builds, centered on the face at twice its size.
- Body (): , , , . The width is times the face and the height times; the top edge sits half a face above the face's, and the bottom edge half a face below.
So the "body" used for classification is a square four times the face (equation 1), while the body box used for regression is a flat box 3.5 times as wide and 2 times as tall, the same height as the head box and extending out to both sides.
Data-anchor-sampling: Shrinking Big Faces Into Small Ones
The last item touches only the data. S3FD's random cropping enlarges the image so small faces become large; data-anchor-sampling (DAS) goes the other way and deliberately shrinks large faces into small ones.
DAS works in five steps, with the anchor sizes written as , , that is, 16 to 512.
- Pick a random face in the image, of size .
- Find the anchor size closest to it, .
- Pick a random from .
- Pick a random target size between and .
- Scale the whole image by , then randomly crop a patch that contains that face.
The paper's example is a 140-pixel face. The closest anchor is 128 (), so is picked from 0 to 4, corresponding to the five sizes 16, 32, 64, 128 and 256. Suppose it picks 32; the target size then lies between 16 and 64. The paper simply takes 32, and the scale factor is , shrinking the whole image to less than a quarter of its size.
Work out the probabilities and the bias is plain to see. For this 140-pixel face, picking 16, 32 or 64 caps the target size at 32, 64 or 128, so the face is always shrunk; picking 128 puts the target between 64 and 256, about a 40% chance of shrinking; picking 256 puts it between 128 and 512, almost always an enlargement. Averaged over the five equally likely choices, the face has about a 70% chance of being shrunk. A face of exactly 16 pixels can only pick 16 or 32. The larger the face, the better its chances of being shrunk into a small face, which is just what the authors want, using large faces to produce small faces of varied appearance.
The paper groups the training faces by pose, occlusion, blur and illumination. After sampling, every group has more faces of 32 pixels or less, and the groups with the most faces grow the most visibly. For typical pose, faces of 16 to 32 pixels go from about 40,000 to nearly 90,000.
The official code hides two more things the paper doesn't mention. DAS is used only half the time; the other half uses S3FD's pick-one-of-five crop. Before that, with another probability of one half, an SSD-style expansion first pastes the image onto a canvas up to 4 times larger, shrinking the whole image. In November 2020 a user asked in issue #4970 why the code uses DAS only half the time and whether the paper's results used the same setting; nobody replied.
Training Setup
WIDER FACE's training set has 12,880 images. The backbone loads ImageNet-pretrained VGG16, and the new layers use xavier initialization. The learning rate is for 80k iterations, then and for 20k each, with batch 16, momentum 0.9 and weight decay 0.0005. That works out to epochs. The official README's numbers agree, with 4 Tesla P40s, batch 16, about 40 minutes per epoch and convergence after about 150 epochs, roughly 100 hours in all.
Discussion
Ablation: Adding One Piece at a Time
| Setting | Easy | Medium | Hard |
|---|---|---|---|
| Baseline (S3FD) | 94.0 | 92.7 | 84.2 |
| + LFPN | 94.3 | 93.3 | 86.1 |
| + DAS | 94.7 | 93.7 | 86.7 |
| + PyramidAnchors | 95.5 | 94.3 | 88.3 |
| + CPM | 95.9 | 94.7 | 88.8 |
| + max-in-out | 96.1 | 95.0 | 88.9 |
Compiled from Table 4 of the paper, WIDER FACE validation AP (%); each row includes the components of the rows above it.
- PyramidAnchors gains a lot in all three groups. Stacked on LFPN and DAS, it adds 1.6 on Hard, second only to LFPN's 1.9; on Easy it adds 0.8, the most of all five items. Added alone to the S3FD baseline, it gives +0.7, +0.6 and +0.9. The authors also tried different settings. With the head only (), Hard is 84.9, and adding the body () gives 85.1, so the body adds just 0.2, consistent with the official code's decision not to implement the body at all.
- LFPN adds 1.9 on Hard, and 1.7 of that is the work of the top-down fusion itself, as broken down earlier.
- DAS adds 0.4, 0.4 and 0.6, improving all three groups, so the benefit isn't limited to small faces.
- CPM adds 0.5 on Hard, and 0.4 each on Easy and Medium. The table comparing prediction modules on their own pits DSSD's prediction module, SSH's context module and CPM against one another, at 88.2, 88.4 and 88.5 on Hard. The authors' reading is that adding DSSD's depth on top of SSH gains very little, and that a large receptive field is what matters.
- Max-in-out adds 0.2, 0.3 and 0.1. Each cell holds a single number, and whether the 0.1 on Hard can be told apart from random variation in training is something this table can't answer.
The S3FD baseline in the ablation table, meanwhile, has 84.2 on Hard. The S3FD paper itself reports 85.2 on validation Hard, and the latest result in its supplementary material is 85.9; the PyramidBox paper's own WIDER FACE comparison figure also marks S3FD (labeled SFD in the legend) at 85.9. Against this 85.9, the final 88.9 is an improvement of 3.0 percentage points; the ablation table says 4.7 (the baseline shrank a little).
WIDER FACE and FDDB
On the WIDER FACE validation set it scores 96.1, 95.0 and 88.9, and on the test set 95.6, 94.6 and 88.7. The paper says it beats the other methods in all three groups. On Easy and Medium it leads the runner-up, FDNet, by 0.2 to 0.7 percentage points; the runner-up on Hard is FAN (Face Attention Network), at 88.8 on validation and 88.5 on test, which PyramidBox beats by 0.1 and 0.2.
FDDB has 2,845 images and 5,171 faces, annotated with ellipses, and two kinds of score. Discrete counts a face as found as long as a detection box overlaps the ellipse by more than 0.5; continuous adds up the overlap of each hit itself, so the tighter the box, the higher the score. Results are drawn as ROC curves, with the number of false positives on the horizontal axis and the true positive rate on the vertical axis. PyramidBox's continuous score is 0.860, the highest in the figure; its discrete score is 0.987, behind Face R-FCN's 0.990. On FDDB, the paper says PyramidBox "achieves state-of-art performance" (second place in its own legend).
The paper doesn't say how these numbers were measured. In the official widerface_eval.py, each image is run at original size, flipped horizontally, through S3FD's shrink-and-enlarge scheme, and through an extra image pyramid at 0.25, 0.75, 1.25, 1.5 and 1.75, with everything merged by box voting at the end. The maintainer said in issue #1272 (September 2018) that evaluated this way, one Tesla P40 takes over an hour to get through the validation set, an average of 1.9 seconds per image; real inference can drop the multi-scale test and the image pyramid. The whole paper doesn't contain a single speed number.
Official Code and Reproduction
The code link in the paper points to fluid/face_detection in the PaddlePaddle models repo. That path later moved off the default branch, and you have to look for PaddleCV/face_detection in old branches such as release/1.8. The model released in the README scores 96.0, 94.8 and 88.8 on the WIDER FACE validation set, 0.1 to 0.2 off the paper.
The differences between the official code and the paper, in summary:
- CPM has a different structure (the README admits as much);
- there's no body branch, only face and head;
- LFPN multiplies, unlike the paper's text ("as same as FPN") and in line with its figure;
- DAS is used only half the time, plus an expansion the paper doesn't mention;
- the learning rate drops once more, to , at epoch 149, for 160 epochs in total.
Retraining it yourself goes less smoothly. In April 2019 the user in issue #2171 retrained it on 4 1080 Tis with batch 12, and Hard came out nearly 10 percentage points below the open-source model. The maintainer replied that the documented parameters reproduce it, and said the team would run a regression check themselves (and that was the last anyone heard). Community reproductions are spread far apart too. The TensorFlow version, EricZgw/PyramidBox, doesn't implement DAS and uses a batch of only 1, scoring 90.6, 88.8 and 73.4 on validation; the PyTorch version, yxlijun/Pyramidbox.pytorch, uses batch 4 and reaches 94.8, 93.8 and 88.0, already very close.
The same yxlijun also wrote a PyTorch reproduction of S3FD, which the S3FD authors even recommended in an issue. Half the time, that reproduction's data augmentation uses none other than PyramidBox's DAS.
What Came Next
A year later, the same team, working with the Institute of Automation of the Chinese Academy of Sciences, published PyramidBox++. The first thing it changed was DAS, on the grounds that DAS always produces too many small faces and unbalances the samples; it became Balanced-data-anchor-sampling, which first picks an anchor size with equal probability and then draws a size near it, and is used only 4/5 of the time. PyramidAnchors also took on DSFD's progressive anchor loss and became Dual-PyramidAnchors; CPM became the Dense Context Module, with DenseNet-style dense connections; the backbone switched to ResNet-50 and the framework to PyTorch. WIDER FACE validation Hard reached 91.2.
Baidu's own PaddleHub later reused the PyramidBox name for mask-detection modules such as pyramidbox_lite_server_mask and pyramidbox_lite_mobile_mask; as early as February 2020, a user in issue #4307 was asking why it ran slowly on video. The module description says PyramidBox-Lite is a lightweight model developed from this paper, with the backbone switched to FaceBoxes, and the mobile model is only 1.2 MB.
Conclusion
Of the 4.7 percentage points the ablation table adds on Hard, LFPN takes 1.9, but 1.7 of that comes just as well from standard FPN; among PyramidBox's own ideas, the largest share is PyramidAnchors' 1.6, and at inference all it does is throw away the head and body outputs. It rests on one assumption, that boxes enlarged at fixed ratios relative to the face carry similar context across different faces. Enlarge the face box two times for the head and four times for the body, hand them to anchors one and two levels up, and send what those levels learn back to the shallowest level through LFPN. The other three items each add a little, CPM 0.5 on Hard, max-in-out 0.1, and DAS 0.4 to 0.6 in each group.
PyramidAnchors is also the piece that takes the fewest changes to move into another anchor-based detector. Training gets one more head box and one more set of classification and regression outputs, and the head box is just the dozen or so lines of expand_bboxes. The body can be left out; in the ablation it's worth only 0.2, and the official code never wrote it either. DAS touches only the data; when porting it, leave some probability for the original crop, since PyramidBox++ replaced it a year later precisely because it produced too many small faces. As for the 88.9, it comes from evaluation with the original image, flipping, multi-scale testing and an image pyramid, nearly two seconds per image.
On the photo of the world's largest selfie, Finding Tiny Faces counted about 800 faces, S3FD 853, PyramidBox 880 and PyramidBox++ 916, all out of "the reportedly 1000." By the time RetinaFace demonstrated on the same photo, the denominator had changed to a reported 1,151 people.