Skip to main content
Open In Colab Reference companion for the six-section Faster RCNN from-scratch chapter This page presents the complete source code of frcnn_common.py, the shared module that all six sections import from. The module is organised into five sections that mirror the data flow through the detector:

1. Constants

Global configuration shared by every section: image resolution, class count, device selection, ImageNet normalisation statistics, and COCO category names. The 400 px input size was chosen to fit a full training loop in 16 GB GPU memory with AMP and gradient checkpointing enabled.

2. Utilities

Three functions shared between the RPN and ROI head:
  • box_iou, pairwise Intersection-over-Union between two box sets
  • encode_boxes, convert (proposal, GT) pairs into regression deltas
  • decode_boxes, apply predicted deltas to anchors/proposals to recover boxes

3. Data pipeline

  • COCOStreamDataset, an IterableDataset that streams COCO 2017 from Hugging Face Hub, resizes images, converts bounding boxes, and normalises with ImageNet statistics
  • frcnn_collate_fn, stacks images into a batch tensor while keeping variable-length target dicts in a list

4. Backbone: ResNet50 + FPN

The feature extractor consists of three classes:
  • Bottleneck, a single ResNet bottleneck block (1x1 → 3x3 → 1x1 convolutions with residual connection)
  • ResNet50, loads pre-trained ImageNet weights and exposes layers 1–4 as multi-scale feature maps; supports gradient checkpointing on layers 3–4 to save ~1.5 GB activation memory
  • FPN, Feature Pyramid Network that fuses ResNet features into P2–P6 maps with 256-channel uniform representation

5. Detection head

Region Proposal Network (RPN)

  • AnchorGenerator, generates multi-scale anchors at every FPN level
  • RPNHead, predicts objectness scores and box deltas for each anchor
  • RegionProposalNetwork, combines anchor generation, RPN predictions, NMS filtering, and loss computation

ROI Head

  • ROIAlign, crops and resizes FPN features for each proposal to a fixed spatial size
  • TwoMLPHead, flattens ROI features through two fully-connected layers
  • FastRCNNPredictor, final classification and box regression heads

End-to-end model

  • FasterRCNN, wires backbone, RPN, and ROI head into a single nn.Module with unified forward() for both training and inference