Package: python-detr
DE⫶TR: End-to-End Object Detection with TransformersPyTorch training code and pretrained models forDETR(DEtectionTRansformer).
We replace the full complex hand-crafted object detection pipeline with a Transformer, and match Faster R-CNN with a ResNet-50, obtaining42 APon COCO using half the computation power (FLOPs) and the same number of parameters. Inference in 50 lines of PyTorch.What it is. Unlike traditional computer vision techniques, DETR approaches object detection as a direct set prediction problem. It consists of a set-based global loss, which forces unique predictions via bipartite matching, and a Transformer encoder-decoder architecture.
Given a fixed small set of learned object queries, DETR reasons about the relations of the objects and the global image context to directly output the final set of predictions in parallel. Due to this parallel nature, DETR is very fast and efficient.About the code. We believe that object detection should not be more difficult than classification,
and should not require complex libraries for training and inference.
DETR is very simple to implement and experiment with, and we provide astandalone Colab Notebookshowing how to do inference with DETR in only a few lines of PyTorch code.
Training code follows this idea - it is not a library,
but simply amain.pyimporting model and criterion
definitions with standard training loops.Additionnally, we provide a Detectron2 wrapper in the d2/ folder. See the readme there for more information.For details seeEnd-to-End Object Detection with Transformersby Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko.See ourblog postto learn more about end to end object detection with transformers.Model ZooWe provide baseline DETR and DETR-DC5 models, and plan to include more in future.
AP is computed on COCO 2017 val5k, and inference time is over the first 100 val5k COCO images,
with torchscript transformer.namebackbonescheduleinf_timebox APurlsize0DETRR505000.03642.0model|logs159Mb1DETR-DC5R505000.08343.3model|logs159Mb2DETRR1015000.05043.5model|logs232Mb3DETR-DC5R1015000.09744.9model|logs232MbCOCO val5k evaluation results can be found in thisgist.The models are also available via torch hub,
to load DETR R50 with pretrained weights simply do:model=torch.hub.load('facebookresearch/detr:main','detr_resnet50',pretrained=True)COCO panoptic val5k models:namebackbonebox APsegm APPQurlsize0DETRR5038.831.143.4download165Mb1DETR-DC5R5040.231.944.6download165Mb2DETRR10140.13345.1download237MbCheckout ourpanoptic colabto see how to use and visualize DETR's panoptic segmentation prediction.NotebooksWe provide a few notebooks in colab to help you get a grasp on DETR:DETR's hands on Colab Notebook: Shows how to load a model from hub, generate predictions, then visualize the attention of the model (similar to the figures of the paper)Standalone Colab Notebook: In this notebook, we demonstrate how to implement a simplified version of DETR from the grounds up in 50 lines of Python, then visualize the predictions. It is a good starting point if you want to gain better understanding the architecture and poke around before diving in the codebase.Panoptic Colab Notebook: Demonstrates how to use DETR for panoptic segmentation and plot the predictions.Usage - Object detectionThere are no extra compiled components in DETR and package dependencies are minimal,
so the code is very simple to use. We provide instructions how to install dependencies via conda.
First, clone the repository locally:git clone https://github.com/facebookresearch/detr.gitThen, install PyTorch 1.5+ and torchvision 0.6+:conda install -c pytorch pytorch torchvisionInstall pycocotools (for evaluation on COCO) and scipy (for training):conda install cython scipy
pip install -U 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'That's it, should be good to train and evaluate detection models.(optional) to work with panoptic install panopticapi:pip install git+https://github.com/cocodataset/panopticapi.gitData preparationDownload and extract COCO 2017 train and val images with annotations fromhttp://cocodataset.org.
We expect the directory structure to be the following:path/to/coco/
  annotations/  # annotation json files
  train2017/    # train images
  val2017/      # val imagesTrainingTo train baseline DETR on a single node with 8 gpus for 300 epochs run:python -m torch.distributed.launch --nproc_per_node=8 --use_env main.py --coco_path /path/to/cocoA single epoch takes 28 minutes, so 300 epoch training
takes around 6 days on a single machine with 8 V100 cards.
To ease reproduction of our results we provideresults and training logsfor 150 epoch schedule (3 days on a single machine), achieving 39.5/60.3 AP/AP50.We train DETR with AdamW setting learning rate in the transformer to 1e-4 and 1e-5 in the backbone.
Horizontal flips, scales and crops are used for augmentation.
Images are rescaled to have min size 800 and max size 1333.
The transformer is trained with dropout of 0.1, and the whole model is trained with grad clip of 0.1.EvaluationTo evaluate DETR R50 on COCO val5k with a single GPU run:python main.py --batch_size 2 --no_aux_loss --eval --resume https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth --coco_path /path/to/cocoWe provide results for all DETR detection models in thisgist.
Note that numbers vary depending on batch size (number of images) per GPU.
Non-DC5 models were trained with batch size 2, and DC5 with 1,
so DC5 models show a significant drop in AP if evaluated with more
than 1 image per GPU.Multinode trainingDistributed training is available via Slurm andsubmitit:pip install submititTrain baseline DETR-6-6 model on 4 nodes for 300 epochs:python run_with_submitit.py --timeout 3000 --coco_path /path/to/cocoUsage - SegmentationWe show that it is relatively straightforward to extend DETR to predict segmentation masks. We mainly demonstrate strong panoptic segmentation results.Data preparationFor panoptic segmentation, you need the panoptic annotations additionally to the coco dataset (see above for the coco dataset). You need to download and extract theannotations.
We expect the directory structure to be the following:path/to/coco_panoptic/
  annotations/  # annotation json files
  panoptic_train2017/    # train panoptic annotations
  panoptic_val2017/      # val panoptic annotationsTrainingWe recommend training segmentation in two stages: first train DETR to detect all the boxes, and then train the segmentation head.
For panoptic segmentation, DETR must learn to detect boxes for both stuff and things classes. You can train it on a single node with 8 gpus for 300 epochs with:python -m torch.distributed.launch --nproc_per_node=8 --use_env main.py --coco_path /path/to/coco  --coco_panoptic_path /path/to/coco_panoptic --dataset_file coco_panoptic --output_dir /output/path/box_modelFor instance segmentation, you can simply train a normal box model (or used a pre-trained one we provide).Once you have a box model checkpoint, you need to freeze it, and train the segmentation head in isolation.
For panoptic segmentation you can train on a single node with 8 gpus for 25 epochs:python -m torch.distributed.launch --nproc_per_node=8 --use_env main.py --masks --epochs 25 --lr_drop 15 --coco_path /path/to/coco  --coco_panoptic_path /path/to/coco_panoptic  --dataset_file coco_panoptic --frozen_weights /output/path/box_model/checkpoint.pth --output_dir /output/path/segm_modelFor instance segmentation only, simply remove thedataset_fileandcoco_panoptic_patharguments from the above command line.LicenseDETR is released under the Apache 2.0 license. Please see theLICENSEfile for more information.ContributingWe actively welcome your pull requests! Please seeCONTRIBUTING.mdandCODE_OF_CONDUCT.mdfor more info.