AI Logic

Architectures

Feature Pyramid Network (FPN)

Updated:

Structure of FPN. Left: how the feature pyramid is built. Lateral 1×1 convolutions are applied to the outputs C2–C5 of the ResNet bottom-up pathway, the map from the level above is upsampled 2× and added, and a 3×3 convolution produces P2–P5. P6 is made by subsampling P5, and P2–P6 are passed to a prediction head with shared weights. Right: a table of what each level handles, showing the RPN anchor areas for P2–P6 (32² to 512²), the range of RoI sizes handled by the detector, and the formula assigning an RoI to a level, k = ⌊4 + log₂(√(wh)/224)⌋.

Background and Overview

FPN (Feature Pyramid Network) is a network architecture that adds together a CNN's intermediate feature maps of different resolutions, from the top level down, to build a pyramid of features that are semantically strong at every resolution. Lin et al. at Facebook AI Research proposed it in 2016 (CVPR 2017). It made it possible to detect objects of different sizes from an image at a single scale, with little extra computation.

In object detection, large and small objects appear together in the same image. The long-standing standard approach was to resize the image to many scales (an image pyramid) and compute features at each, but this multiplies the computation. For that reason, detectors such as Faster R-CNN normally used only a single feature map and struggled with small objects.

The paper's main results are as follows.

  • Adding FPN to a ResNet-50 Faster R-CNN raised COCO AP from 31.6 to 33.9 and small-object AP from 13.2 to 17.8.
  • RPN proposal recall (how many ground-truth objects are covered by 1000 proposals per image) rose from 48.3 to 56.3, and from 32.0 to 44.9 for small objects.
  • A ResNet-101 Faster R-CNN with FPN reached 36.2 AP on COCO test-dev, surpassing all previous single-model entries, including the COCO 2016 winner.
  • It ran at 0.148 s per image (ResNet-50), faster than a ResNet-50 Faster R-CNN without FPN (0.32 s).

FPN is not a specific detector but an architecture for the feature extraction part (the backbone). It later became a standard component in many detection and segmentation models, starting with Mask R-CNN.

The Problem: Objects of Different Sizes and Feature Pyramids

FPN addresses the problem of combining the "fine resolution" needed to find small objects with the "semantically strong features" needed to recognize objects, while staying fast.

The paper groups approaches to handling objects of different sizes into four categories.

  1. Image pyramid: Resize the image to several scales and compute features at each. Features at every level are semantically strong and accuracy is high, but inference time multiplies (for example, by 4). Memory limits make it impractical for training, and using it only at test time creates a mismatch between training and testing.
  2. Single feature map: Predict from the CNN's last feature map only. This is fast, but the last feature map is coarse, so information about small objects tends to be lost. This is the standard form in Fast R-CNN and Faster R-CNN.
  3. Using the CNN's intermediate feature maps directly: Because resolution drops as a CNN goes deeper, the outputs of its intermediate layers already form a pyramid. SSD used this. However, the fine feature maps of shallow layers carry only low-level features such as edges and colors and have weak recognition power, so SSD skipped the fine layers and built its pyramid from higher up in the network. The paper points out that this means SSD misses the fine layers that matter for detecting small objects.
  4. FPN: Uses the pyramid shape of approach 3 but feeds the semantically strong features from the upper levels into the fine lower levels. Every level is semantically strong, and the pyramid is built quickly from an image at a single scale.

As an everyday analogy, think of aerial-photo maps: a large-scale (detailed) map shows the shapes of roads in detail but has few place names, while a small-scale (coarse) map clearly labels place names and districts. FPN copies the place names from the coarse map onto the detailed one, so that a map at any scale shows both "what is where" and "fine shapes."

U-Net and similar models also have a top-down pathway with lateral connections (skip connections). The difference is where predictions are made. U-Net-style architectures predict only at the final, finest level, whereas FPN makes independent predictions at every level of the pyramid. This is the same idea as running one detector on every level of an image pyramid.

Theory: Building the Feature Pyramid

FPN builds its pyramid from three parts: a bottom-up pathway, a top-down pathway, and lateral connections. The left of the figure at the top of the article shows the structure, and the right shows what each level handles.

With a ResNet backbone, the procedure is as follows.

  1. Bottom-up pathway: Pass the image through ResNet as usual. Each group of layers that produces feature maps of the same size forms one stage, and the outputs of the last residual block of each stage are denoted C2,C3,C4,C5C_2, C_3, C_4, C_5. Their strides relative to the image are 4, 8, 16, and 32 pixels, so each step up halves the height and width. The output of the first stage, conv1, is left out of the pyramid because of its large memory footprint.
  2. Lateral connections: Apply a 1×1 convolution to each CkC_k to reduce it to 256 channels.
  3. Top-down pathway: Starting from the coarsest level, upsample the map from the level above by 2× in height and width (nearest-neighbor interpolation) and add it element-wise to the lateral map. Repeat down to the finest level.
  4. Final step: Apply a 3×3 convolution to each merged map to obtain P2,P3,P4,P5P_2, P_3, P_4, P_5. This reduces the grid-like artifacts (aliasing) introduced by upsampling.

In equations (MkM_k is the merged map and Up\mathrm{Up} is 2× nearest-neighbor upsampling):

M5=Conv1×1(C5),Mk=Up(Mk+1)+Conv1×1(Ck)(k=4,3,2)M_5 = \mathrm{Conv}_{1\times1}(C_5), \qquad M_k = \mathrm{Up}(M_{k+1}) + \mathrm{Conv}_{1\times1}(C_k) \quad (k = 4, 3, 2) Pk=Conv3×3(Mk)(k=2,3,4,5)P_k = \mathrm{Conv}_{3\times3}(M_k) \quad (k = 2, 3, 4, 5)

What is passed down from the level above is Mk+1M_{k+1}, before the 3×3 convolution, not Pk+1P_{k+1}. Because all levels share the same prediction head, the channel count is fixed at d=256d = 256. The added layers have no nonlinear activation (the paper reports that adding one made little difference).

The lateral connections carry "localization accuracy," and the top-down pathway carries "semantic strength." Features in the top-down pathway have been downsampled and upsampled many times, so they are semantically strong but spatially blurry. The fine levels of the bottom-up pathway have been downsampled fewer times, so their locations are precise. Adding the two yields features with both properties.

Use in Detectors: RPN and Fast R-CNN

FPN is integrated into Faster R-CNN by replacing the single feature map with the pyramid in both the RPN (the region proposal network) and Fast R-CNN (the detector that classifies proposals).

RPN: The Faster R-CNN RPN head (a 3×3 convolution followed by two 1×1 convolutions that output objectness and box offsets) is attached to each level of the pyramid.

  • Because the head scans every level, there is no need for anchors of multiple sizes at a single level. Each level is assigned anchors of a single size.
    • P2P_2 through P6P_6 each get anchors with an area of 32232^2, 64264^2, 1282128^2, 2562256^2, and 5122512^2 pixels, respectively.
    • Every level uses three aspect ratios, 1:2, 1:1, and 2:1, for 15 anchor types across the pyramid.
  • P6P_6 exists only for the largest anchors and is made by subsampling P5P_5 with stride 2. Fast R-CNN does not use P6P_6.
  • Positive and negative labels are assigned as in Faster R-CNN (IoU above 0.7 / below 0.3). No extra rule assigns ground-truth boxes to levels; the level follows naturally from the anchors.
  • The head's weights are shared across all levels. Accuracy is about the same without sharing, which indicates that all levels have similar semantic strength.

Fast R-CNN: The level from which features are extracted is chosen according to the size of the region of interest (RoI). An RoI of width ww and height hh on the image is assigned to level PkP_k by the following formula.

k=⌊k0+log⁡2(wh/224)⌋k = \left\lfloor k_0 + \log_2 \left( \sqrt{wh} / 224 \right) \right\rfloor

Here 224 is the ImageNet training image size and k0=4k_0 = 4. A 224×224 RoI is taken from P4P_4, and an RoI half that size from the next finer level, P3P_3. This is the same idea as choosing the level of an image pyramid that matches the object's size. The extracted 7×7 features pass through two 1024-dimensional fully connected layers (each with ReLU) before the class and box-regression outputs. This head is also shared across all levels.

For very small or very large RoIs, the formula can give kk below 2 or above 5. The paper does not specify how to handle this, but implementations such as torchvision clamp kk to the available levels (P2P_2–P5P_5). Remember this clamping when implementing it yourself.

Why Accuracy Improves

The paper's ablations on the RPN and Fast R-CNN confirm that each of FPN's three parts is necessary (COCO validation set, ResNet-50).

ConfigurationRPN recall AR1k_{1k}Fast R-CNN AP
FPN (standard)56.333.9
No top-down pathway (only 1×1 and 3×3 on the bottom-up pyramid)49.524.9
No lateral connections (top-down pathway only)46.131.3
Only the finest level, P2P_251.333.4

This shows the following.

  • The top-down pathway is needed: Using the bottom-up levels directly, the shallow levels' features are semantically weak, and the detector's AP dropped sharply to 24.9. The cause is the large difference in semantic strength between levels (the semantic gap), and attaching a separate head to each level did not help.
  • Lateral connections are needed: With the top-down pathway alone, feature locations become inaccurate, and RPN recall dropped by 10 points.
  • Predicting on the pyramid is needed: Using only the semantically strong, fine P2P_2 was worse than using the whole pyramid. Since the RPN scans with a fixed-size window, scanning across levels makes it more robust to scale variation. The P2P_2-only setting also has many more anchors (750k versus 200k for FPN), showing that simply adding anchors does not improve accuracy.

For Fast R-CNN, the gap between P2P_2 only (33.4) and the full pyramid (33.9) was small. The paper attributes this to RoI pooling, which warps regions to a fixed size and is therefore relatively robust to region scale. Note, however, that this comparison uses proposals from the FPN RPN, so the proposal stage already benefits from the pyramid.

Experimental Results

COCO validation: effect of adding FPN to Faster R-CNN (ResNet-50, same backbone for RPN and detector)

ConfigurationFeatures used for predictionHeadAP@0.5APAPS_SAPM_MAPL_L
He et al. (reference)C4C_4conv547.326.3―――
Single feature map (paper's reimplementation)C4C_4conv553.131.613.235.647.1
Single feature mapC5C_52 fc layers51.728.09.631.943.1
FPNP2P_2–P5P_52 fc layers56.933.917.837.745.8

APS_S, APM_M, and APL_L are the AP for small, medium, and large objects. FPN beats a strong single-feature-map baseline under the same settings by 2.3 points AP and 3.8 points AP@0.5, with a 4.6-point gain on small objects in particular.

COCO validation: RPN proposal recall (ResNet-50, 1000 proposals per image)

ConfigurationAR1k_{1k}Small objectsMedium objectsLarge objects
Single feature map (C4C_4)48.332.058.762.2
Single feature map (C5C_5)44.925.355.564.2
FPN56.344.963.466.2

C5C_5 should be semantically stronger than C4C_4, yet recall actually fell. There is a trade-off between coarse resolution and semantic strength, and a single feature map has to give up one or the other.

COCO test-dev: single-model comparison (AP)

MethodBackboneAP@0.5APAPS_S
Faster R-CNN+++ (COCO 2015 winner, uses an image pyramid)ResNet-10155.734.915.6
G-RMI (COCO 2016 winner)Inception-ResNet―34.7―
AttractioNet (uses an image pyramid)VGG-16 + Wide ResNet53.435.715.6
Faster R-CNN with FPNResNet-10159.136.218.2

Without image pyramids or other elaborate tricks, FPN outperformed the single models of the winning entries.

Speed: Faster R-CNN with FPN, sharing features between the RPN and the detector, ran at 0.148 s per image (ResNet-50) and 0.172 s (ResNet-101, M40 GPU). It is faster than ResNet-50 Faster R-CNN without FPN (0.32 s) because replacing the heavy conv5-based ResNet head with a light two-fc-layer head saves more than the extra FPN layers cost.

Practical Considerations

Keep the following points in mind when using FPN.

  • Fine levels cost computation and memory: P2P_2 has 1/4 of the image resolution and 256 channels, so the number of RPN anchors grows considerably (about 200k per image in the paper's setup). The paper leaves the conv1 output out of the pyramid because its memory cost is too high.
  • Image size and level sizes: In the top-down pathway, the 2× upsampled map must match the size of the lateral map. If the image height and width are not multiples of 32, rounding during downsampling can cause size mismatches, so implementations either upsample to the lateral map's size or pad the image to a multiple of 32.
  • The paper's baseline uses stronger settings: The paper's baseline Faster R-CNN is stronger than the original Faster R-CNN setup: a shorter image side of 800 pixels (originally 600), 512 RoIs per image (originally 64), anchors of five sizes, and 1000 proposals at test time (originally 300). The paper compares FPN against this stronger baseline (which itself is 7.6 points AP above the original baseline).
  • Backbone-agnostic: The paper experiments with ResNet, but any CNN whose stage outputs can be extracted will work.

In the paper's setup, anchors that cross the image boundary are included when training the FPN RPN. The original Faster R-CNN reported that training does not converge unless such anchors are ignored, so when reproducing results by mixing the settings of the two papers, decide which one to follow.

Comparison with Other Methods

Lining up approaches to handling objects of different sizes along the same dimensions gives the following.

MethodHow features are builtLevels used for predictionSemantic strength of fine levelsSpeed
Image pyramidRun the CNN on each resized imageAll levelsStrongSlow (computation per image level)
Single feature map (standard Faster R-CNN)The CNN's last feature mapOne map only― (no fine levels)Fast
Using the CNN's intermediate levels directly (SSD)Intermediate layer outputs plus layers added on topAll levelsWeak (so the fine levels are not used)Fast
Top-down pathway, predicting at the last level only (e.g., U-Net)Top-down pathway and skip connectionsFinest level onlyStrongFast
FPNTop-down pathway and lateral connectionsAll levelsStrongFast

Placing the FPN detector within the R-CNN family gives the following (times are the values reported in each paper; GPUs differ, so treat them as rough).

MethodRegion proposalsHow proposal features are extractedOutputDetection time per image (reported)
R-CNNSelective Search (about 2000)Crop each proposal from the image and run the CNNClass and box13 s (AlexNet-style), 47 s (VGG-16)
SPP-netSelective SearchSpatial pyramid pooling on the whole-image feature mapClass and box10–100× faster than R-CNN
Fast R-CNNSelective SearchRoI pooling on the whole-image feature mapClass and box0.32 s + about 1.5 s for region proposals (VGG-16)
Faster R-CNNRPN (shares the feature map, 300 proposals)RoI poolingClass and box0.198 s (VGG-16)
Faster R-CNN + FPNRPN on each level of the feature pyramidChoose the level by RoI size, then RoI poolingClass and box0.148 s (ResNet-50)
Mask R-CNNRPN (uses FPN)RoIAlignClass, box, and mask0.195 s (ResNet-101-FPN)

Rough guidelines for choosing:

  • Detection with a mix of small and large objects: Faster R-CNN or Mask R-CNN with FPN is the standard starting point. The built-in Faster R-CNN and Mask R-CNN in torchvision also use FPN.
  • Objects of roughly uniform size: A single feature map may be enough, and the setup is simpler.
  • Per-pixel segmentation that needs a single fine output: An architecture that predicts only at the finest level, like U-Net, is a better fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from torchvision.models import resnet50, ResNet50_Weights
from torchvision.models.feature_extraction import create_feature_extractor
from torchvision.ops import FeaturePyramidNetwork
from torchvision.ops.feature_pyramid_network import LastLevelMaxPool

'''
(1) FPN as in Section 3 of the paper (1×1 lateral connections, add after 2× nearest-neighbor upsampling, finish with 3×3, P6 subsamples P5)
(2) Choose the pyramid level from the RoI size with Eq. (1)
(3) Build the same thing with torchvision's built-in FeaturePyramidNetwork
'''



class FPN(nn.Module):
  def __init__(self, in_channels_list=(256, 512, 1024, 2048), d=256):
    super().__init__()
    # Lateral connections (1×1) and output convs (3×3). No activation in the added layers (Section 3)
    self.lateral = nn.ModuleList(nn.Conv2d(c, d, 1) for c in in_channels_list)
    self.output = nn.ModuleList(nn.Conv2d(d, d, 3, padding=1) for _ in in_channels_list)

  def forward(self, feats):                           # feats: [C2, C3, C4, C5] (finest first)
    m = self.lateral[-1](feats[-1])                   # M5 = 1×1(C5)
    outs = [self.output[-1](m)]                       # P5 = 3×3(M5)
    for k in range(len(feats) - 2, -1, -1):           # C4 → C3 → C2
      lat = self.lateral[k](feats[k])
      up = F.interpolate(m, size=lat.shape[-2:], mode='nearest')  # upsample 2× (match the lateral map's size)
      m = up + lat                                    # Mk = Up(Mk+1) + 1×1(Ck); pass down the map before the 3×3
      outs.insert(0, self.output[k](m))               # Pk = 3×3(Mk)
    p6 = F.max_pool2d(outs[-1], kernel_size=1, stride=2)  # P6: subsample P5 with stride 2 (used only by the RPN)
    return outs + [p6]                                # [P2, P3, P4, P5, P6]


def assign_level(boxes, k0=4, k_min=2, k_max=5, canonical=224):
  """Eq. (1): assign an RoI of width w and height h to level Pk. boxes: [R, 4] (x1, y1, x2, y2 in image coordinates)"""
  w, h = boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]
  k = torch.floor(k0 + torch.log2(torch.sqrt(w * h) / canonical + 1e-6))
  return k.clamp(k_min, k_max).long()                 # out-of-range values (not covered in the paper) are clamped to available levels


# Extract the outputs of the last residual block of each ResNet-50 stage (C2–C5)
backbone = create_feature_extractor(
  resnet50(weights=ResNet50_Weights.IMAGENET1K_V2),
  return_nodes={'layer1': 'c2', 'layer2': 'c3', 'layer3': 'c4', 'layer4': 'c5'},
)
backbone.eval()                                       # put batch norm in inference mode (use model.train() for training)
fpn = FPN()

with torch.no_grad():
  image = torch.randn(1, 3, 800, 1216)                # shorter side 800 pixels (Section 5)
  c = backbone(image)
  pyramid = fpn([c['c2'], c['c3'], c['c4'], c['c5']])
  for name, p in zip(['P2', 'P3', 'P4', 'P5', 'P6'], pyramid):
    print(name, tuple(p.shape))                       # every level has 256 channels; sizes are 1/4, 1/8, 1/16, 1/32, 1/64

rois = torch.tensor([[0., 0., 100., 100.], [0., 0., 224., 224.], [0., 0., 600., 500.]])
print(assign_level(rois))                             # tensor([2, 4, 5]): √(wh) is 100, 224, 548

# (3) torchvision built-in: input is a named dict (finest first); extra_blocks adds P6
tv_fpn = FeaturePyramidNetwork(in_channels_list=[256, 512, 1024, 2048], out_channels=256,
                               extra_blocks=LastLevelMaxPool())
with torch.no_grad():
  out = tv_fpn(OrderedDict((k, c[k]) for k in ['c2', 'c3', 'c4', 'c5']))
print({k: tuple(v.shape) for k, v in out.items()})   # 'pool' corresponds to P6

# For detection, a Faster R-CNN with FPN is built in
from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights
detector = fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.COCO_V1)

FAQ

Q. Is FPN an object detection method?
A.

FPN itself is an architecture for the part that extracts features at several resolutions from an image (the backbone). Detection or segmentation heads are attached separately. The paper demonstrates its effect by integrating it into the RPN and detector of Faster R-CNN, and it is also used as the standard configuration in Mask R-CNN.

Q. Why add features from upper levels to lower levels?
A.

The fine feature maps of a CNN's shallow layers are spatially precise but carry only low-level features such as edges and colors, so their recognition power is weak. The coarse feature maps of deep layers represent object semantics well, so upsampling and adding them gives the fine levels the power to recognize objects as well. In the paper, removing the top-down pathway lowered the detector's AP from 33.9 to 24.9.

Q. How does it differ from an image pyramid?
A.

An image pyramid runs the CNN on each resized image, so computation grows with the number of levels. FPN runs the CNN once on an image at a single scale and builds the pyramid from the intermediate layer outputs, so the extra computation is small. Another difference is that the same pyramid can be used for training and testing.

References

  1. Lin, T.-Y., Dollár, P., Girshick, R., He, K., Hariharan, B., & Belongie, S. (2017). Feature Pyramid Networks for Object Detection. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2117–2125. arXiv:1612.03144.
  2. Ren, S., He, K., Girshick, R., & Sun, J. (2015). Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks. NeurIPS 2015. arXiv:1506.01497.
  3. He, K., Gkioxari, G., Dollár, P., & Girshick, R. (2017). Mask R-CNN. ICCV 2017. arXiv:1703.06870.
  4. PyTorch. torchvision.ops.FeaturePyramidNetwork.