[
  {
    "path": ".github/CODE_OF_CONDUCT.md",
    "content": "# Code of Conduct\n\nFacebook has adopted a Code of Conduct that we expect project participants to adhere to.\nPlease read the [full text](https://code.fb.com/codeofconduct/)\nso that you can understand what actions will and will not be tolerated.\n"
  },
  {
    "path": ".github/CONTRIBUTING.md",
    "content": "# Contributing to DETR\nWe want to make contributing to this project as easy and transparent as\npossible.\n\n## Our Development Process\nMinor changes and improvements will be released on an ongoing basis. Larger changes (e.g., changesets implementing a new paper) will be released on a more periodic basis.\n\n## Pull Requests\nWe actively welcome your pull requests.\n\n1. Fork the repo and create your branch from `master`.\n2. If you've added code that should be tested, add tests.\n3. If you've changed APIs, update the documentation.\n4. Ensure the test suite passes.\n5. Make sure your code lints.\n6. If you haven't already, complete the Contributor License Agreement (\"CLA\").\n\n## Contributor License Agreement (\"CLA\")\nIn order to accept your pull request, we need you to submit a CLA. You only need\nto do this once to work on any of Facebook's open source projects.\n\nComplete your CLA here: <https://code.facebook.com/cla>\n\n## Issues\nWe use GitHub issues to track public bugs. Please ensure your description is\nclear and has sufficient instructions to be able to reproduce the issue.\n\nFacebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe\ndisclosure of security bugs. In those cases, please go through the process\noutlined on that page and do not file a public issue.\n\n## Coding Style  \n* 4 spaces for indentation rather than tabs\n* 80 character line length\n* PEP8 formatting following [Black](https://black.readthedocs.io/en/stable/)\n\n## License\nBy contributing to DETR, you agree that your contributions will be licensed\nunder the LICENSE file in the root directory of this source tree.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bugs.md",
    "content": "---\nname: \"🐛 Bugs\"\nabout: Report bugs in DETR\ntitle: Please read & provide the following\n\n---\n\n## Instructions To Reproduce the 🐛 Bug:\n\n1. what changes you made (`git diff`) or what code you wrote\n```\n<put diff or code here>\n```\n2. what exact command you run:\n3. what you observed (including __full logs__):\n```\n<put logs here>\n```\n4. please simplify the steps as much as possible so they do not require additional resources to\n\t run, such as a private dataset.\n\n## Expected behavior:\n\nIf there are no obvious error in \"what you observed\" provided above,\nplease tell us the expected behavior.\n\n## Environment:\n\nProvide your environment information using the following command:\n```\npython -m torch.utils.collect_env\n```\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/questions-help-support.md",
    "content": "---\nname: \"How to do something❓\"\nabout: How to do something using DETR?\n\n---\n\n## ❓ How to do something using DETR\n\nDescribe what you want to do, including:\n1. what inputs you will provide, if any:\n2. what outputs you are expecting:\n\n\nNOTE:\n\n1. Only general answers are provided.\n   If you want to ask about \"why X did not work\", please use the\n   [Unexpected behaviors](https://github.com/facebookresearch/detr/issues/new/choose) issue template.\n\n2. About how to implement new models / new dataloader / new training logic, etc., check documentation first.\n\n3. We do not answer general machine learning / computer vision questions that are not specific to DETR, such as how a model works, how to improve your training/make it converge, or what algorithm/methods can be used to achieve X.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/unexpected-problems-bugs.md",
    "content": "---\nname: \"Unexpected behaviors\"\nabout: Run into unexpected behaviors when using DETR\ntitle: Please read & provide the following\n\n---\n\nIf you do not know the root cause of the problem, and wish someone to help you, please\npost according to this template:\n\n## Instructions To Reproduce the Issue:\n\n1. what changes you made (`git diff`) or what code you wrote\n```\n<put diff or code here>\n```\n2. what exact command you run:\n3. what you observed (including __full logs__):\n```\n<put logs here>\n```\n4. please simplify the steps as much as possible so they do not require additional resources to\n\t run, such as a private dataset.\n\n## Expected behavior:\n\nIf there are no obvious error in \"what you observed\" provided above,\nplease tell us the expected behavior.\n\nIf you expect the model to converge / work better, note that we do not give suggestions\non how to train a new model.\nOnly in one of the two conditions we will help with it:\n(1) You're unable to reproduce the results in DETR model zoo.\n(2) It indicates a DETR bug.\n\n## Environment:\n\nProvide your environment information using the following command:\n```\npython -m torch.utils.collect_env\n```\n"
  },
  {
    "path": ".gitignore",
    "content": ".nfs*\n*.ipynb\n*.pyc\n.dumbo.json\n.DS_Store\n.*.swp\n*.pth\n**/__pycache__/**\n.ipynb_checkpoints/\ndatasets/data/\nexperiment-*\n*.tmp\n*.pkl\n**/.mypy_cache/*\n.mypy_cache/*\nnot_tracked_dir/\n.vscode\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM pytorch/pytorch:1.5-cuda10.1-cudnn7-runtime\n\nENV DEBIAN_FRONTEND=noninteractive\n\nRUN apt-get update -qq && \\\n    apt-get install -y git vim libgtk2.0-dev && \\\n    rm -rf /var/cache/apk/*\n\nRUN pip --no-cache-dir install Cython\n\nCOPY requirements.txt /workspace\n\nRUN pip --no-cache-dir install -r /workspace/requirements.txt\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2020 - present, Facebook, Inc\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "**DE⫶TR**: End-to-End Object Detection with Transformers\n========\n\n[![Support Ukraine](https://img.shields.io/badge/Support-Ukraine-FFD500?style=flat&labelColor=005BBB)](https://opensource.fb.com/support-ukraine)\n\nPyTorch training code and pretrained models for **DETR** (**DE**tection **TR**ansformer).\nWe replace the full complex hand-crafted object detection pipeline with a Transformer, and match Faster R-CNN with a ResNet-50, obtaining **42 AP** on COCO using half the computation power (FLOPs) and the same number of parameters. Inference in 50 lines of PyTorch.\n\n![DETR](.github/DETR.png)\n\n**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. \nGiven 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.\n\n**About the code**. We believe that object detection should not be more difficult than classification,\nand should not require complex libraries for training and inference.\nDETR is very simple to implement and experiment with, and we provide a\n[standalone Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/detr_demo.ipynb)\nshowing how to do inference with DETR in only a few lines of PyTorch code.\nTraining code follows this idea - it is not a library,\nbut simply a [main.py](main.py) importing model and criterion\ndefinitions with standard training loops.\n\nAdditionnally, we provide a Detectron2 wrapper in the d2/ folder. See the readme there for more information.\n\nFor details see [End-to-End Object Detection with Transformers](https://ai.facebook.com/research/publications/end-to-end-object-detection-with-transformers) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko.\n\nSee our [blog post](https://ai.facebook.com/blog/end-to-end-object-detection-with-transformers/) to learn more about end to end object detection with transformers.\n# Model Zoo\nWe provide baseline DETR and DETR-DC5 models, and plan to include more in future.\nAP is computed on COCO 2017 val5k, and inference time is over the first 100 val5k COCO images,\nwith torchscript transformer.\n\n<table>\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>name</th>\n      <th>backbone</th>\n      <th>schedule</th>\n      <th>inf_time</th>\n      <th>box AP</th>\n      <th>url</th>\n      <th>size</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>DETR</td>\n      <td>R50</td>\n      <td>500</td>\n      <td>0.036</td>\n      <td>42.0</td>\n      <td><a href=\"https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth\">model</a>&nbsp;|&nbsp;<a href=\"https://dl.fbaipublicfiles.com/detr/logs/detr-r50_log.txt\">logs</a></td>\n      <td>159Mb</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>DETR-DC5</td>\n      <td>R50</td>\n      <td>500</td>\n      <td>0.083</td>\n      <td>43.3</td>\n      <td><a href=\"https://dl.fbaipublicfiles.com/detr/detr-r50-dc5-f0fb7ef5.pth\">model</a>&nbsp;|&nbsp;<a href=\"https://dl.fbaipublicfiles.com/detr/logs/detr-r50-dc5_log.txt\">logs</a></td>\n      <td>159Mb</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>DETR</td>\n      <td>R101</td>\n      <td>500</td>\n      <td>0.050</td>\n      <td>43.5</td>\n      <td><a href=\"https://dl.fbaipublicfiles.com/detr/detr-r101-2c7b67e5.pth\">model</a>&nbsp;|&nbsp;<a href=\"https://dl.fbaipublicfiles.com/detr/logs/detr-r101_log.txt\">logs</a></td>\n      <td>232Mb</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>DETR-DC5</td>\n      <td>R101</td>\n      <td>500</td>\n      <td>0.097</td>\n      <td>44.9</td>\n      <td><a href=\"https://dl.fbaipublicfiles.com/detr/detr-r101-dc5-a2e86def.pth\">model</a>&nbsp;|&nbsp;<a href=\"https://dl.fbaipublicfiles.com/detr/logs/detr-r101-dc5_log.txt\">logs</a></td>\n      <td>232Mb</td>\n    </tr>\n  </tbody>\n</table>\n\nCOCO val5k evaluation results can be found in this [gist](https://gist.github.com/szagoruyko/9c9ebb8455610958f7deaa27845d7918).\n\nThe models are also available via torch hub,\nto load DETR R50 with pretrained weights simply do:\n```python\nmodel = torch.hub.load('facebookresearch/detr:main', 'detr_resnet50', pretrained=True)\n```\n\n\nCOCO panoptic val5k models:\n<table>\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>name</th>\n      <th>backbone</th>\n      <th>box AP</th>\n      <th>segm AP</th>\n      <th>PQ</th>\n      <th>url</th>\n      <th>size</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>DETR</td>\n      <td>R50</td>\n      <td>38.8</td>\n      <td>31.1</td>\n      <td>43.4</td>\n      <td><a href=\"https://dl.fbaipublicfiles.com/detr/detr-r50-panoptic-00ce5173.pth\">download</a></td>\n      <td>165Mb</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>DETR-DC5</td>\n      <td>R50</td>\n      <td>40.2</td>\n      <td>31.9</td>\n      <td>44.6</td>\n      <td><a href=\"https://dl.fbaipublicfiles.com/detr/detr-r50-dc5-panoptic-da08f1b1.pth\">download</a></td>\n      <td>165Mb</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>DETR</td>\n      <td>R101</td>\n      <td>40.1</td>\n      <td>33</td>\n      <td>45.1</td>\n      <td><a href=\"https://dl.fbaipublicfiles.com/detr/detr-r101-panoptic-40021d53.pth\">download</a></td>\n      <td>237Mb</td>\n    </tr>\n  </tbody>\n</table>\n\nCheckout our [panoptic colab](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/DETR_panoptic.ipynb)\nto see how to use and visualize DETR's panoptic segmentation prediction.\n\n# Notebooks\n\nWe provide a few notebooks in colab to help you get a grasp on DETR:\n* [DETR's hands on Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/detr_attention.ipynb): Shows how to load a model from hub, generate predictions, then visualize the attention of the model (similar to the figures of the paper)\n* [Standalone Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/detr_demo.ipynb): 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.\n* [Panoptic Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/DETR_panoptic.ipynb): Demonstrates how to use DETR for panoptic segmentation and plot the predictions.\n\n\n# Usage - Object detection\nThere are no extra compiled components in DETR and package dependencies are minimal,\nso the code is very simple to use. We provide instructions how to install dependencies via conda.\nFirst, clone the repository locally:\n```\ngit clone https://github.com/facebookresearch/detr.git\n```\nThen, install PyTorch 1.5+ and torchvision 0.6+:\n```\nconda install -c pytorch pytorch torchvision\n```\nInstall pycocotools (for evaluation on COCO) and scipy (for training):\n```\nconda install cython scipy\npip install -U 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'\n```\nThat's it, should be good to train and evaluate detection models.\n\n(optional) to work with panoptic install panopticapi:\n```\npip install git+https://github.com/cocodataset/panopticapi.git\n```\n\n## Data preparation\n\nDownload and extract COCO 2017 train and val images with annotations from\n[http://cocodataset.org](http://cocodataset.org/#download).\nWe expect the directory structure to be the following:\n```\npath/to/coco/\n  annotations/  # annotation json files\n  train2017/    # train images\n  val2017/      # val images\n```\n\n## Training\nTo train baseline DETR on a single node with 8 gpus for 300 epochs run:\n```\npython -m torch.distributed.launch --nproc_per_node=8 --use_env main.py --coco_path /path/to/coco \n```\nA single epoch takes 28 minutes, so 300 epoch training\ntakes around 6 days on a single machine with 8 V100 cards.\nTo ease reproduction of our results we provide\n[results and training logs](https://gist.github.com/szagoruyko/b4c3b2c3627294fc369b899987385a3f)\nfor 150 epoch schedule (3 days on a single machine), achieving 39.5/60.3 AP/AP50.\n\nWe train DETR with AdamW setting learning rate in the transformer to 1e-4 and 1e-5 in the backbone.\nHorizontal flips, scales and crops are used for augmentation.\nImages are rescaled to have min size 800 and max size 1333.\nThe transformer is trained with dropout of 0.1, and the whole model is trained with grad clip of 0.1.\n\n\n## Evaluation\nTo evaluate DETR R50 on COCO val5k with a single GPU run:\n```\npython main.py --batch_size 2 --no_aux_loss --eval --resume https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth --coco_path /path/to/coco\n```\nWe provide results for all DETR detection models in this\n[gist](https://gist.github.com/szagoruyko/9c9ebb8455610958f7deaa27845d7918).\nNote that numbers vary depending on batch size (number of images) per GPU.\nNon-DC5 models were trained with batch size 2, and DC5 with 1,\nso DC5 models show a significant drop in AP if evaluated with more\nthan 1 image per GPU.\n\n## Multinode training\nDistributed training is available via Slurm and [submitit](https://github.com/facebookincubator/submitit):\n```\npip install submitit\n```\nTrain baseline DETR-6-6 model on 4 nodes for 300 epochs:\n```\npython run_with_submitit.py --timeout 3000 --coco_path /path/to/coco\n```\n\n# Usage - Segmentation\n\nWe show that it is relatively straightforward to extend DETR to predict segmentation masks. We mainly demonstrate strong panoptic segmentation results.\n\n## Data preparation\n\nFor panoptic segmentation, you need the panoptic annotations additionally to the coco dataset (see above for the coco dataset). You need to download and extract the [annotations](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip).\nWe expect the directory structure to be the following:\n```\npath/to/coco_panoptic/\n  annotations/  # annotation json files\n  panoptic_train2017/    # train panoptic annotations\n  panoptic_val2017/      # val panoptic annotations\n```\n\n## Training\n\nWe recommend training segmentation in two stages: first train DETR to detect all the boxes, and then train the segmentation head.\nFor 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:\n```\npython -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_model\n```\nFor instance segmentation, you can simply train a normal box model (or used a pre-trained one we provide).\n\nOnce you have a box model checkpoint, you need to freeze it, and train the segmentation head in isolation.\nFor panoptic segmentation you can train on a single node with 8 gpus for 25 epochs:\n```\npython -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_model\n```\nFor instance segmentation only, simply remove the `dataset_file` and `coco_panoptic_path` arguments from the above command line.\n\n# License\nDETR is released under the Apache 2.0 license. Please see the [LICENSE](LICENSE) file for more information.\n\n# Contributing\nWe actively welcome your pull requests! Please see [CONTRIBUTING.md](.github/CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](.github/CODE_OF_CONDUCT.md) for more info.\n"
  },
  {
    "path": "d2/README.md",
    "content": "Detectron2 wrapper for DETR\n=======\n\nWe provide a Detectron2 wrapper for DETR, thus providing a way to better integrate it in the existing detection ecosystem. It can be used for example to easily leverage datasets or backbones provided in Detectron2.\n\nThis wrapper currently supports only box detection, and is intended to be as close as possible to the original implementation, and we checked that it indeed match the results. Some notable facts and caveats:\n- The data augmentation matches DETR's original data augmentation. This required patching the RandomCrop augmentation from Detectron2, so you'll need a version from the master branch from June 24th 2020 or more recent.\n- To match DETR's original backbone initialization, we use the weights of a ResNet50 trained on imagenet using torchvision. This network uses a different pixel mean and std than most of the backbones available in Detectron2 by default, so extra care must be taken when switching to another one. Note that no other torchvision models are available in Detectron2 as of now, though it may change in the future.\n- The gradient clipping mode is \"full_model\", which is not the default in Detectron2.\n\n# Usage\n\nTo install Detectron2, please follow the [official installation instructions](https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md).\n\n## Evaluating a model\n\nFor convenience, we provide a conversion script to convert models trained by the main DETR training loop into the format of this wrapper. To download and convert the main Resnet50 model, simply do:\n\n```\npython converter.py --source_model https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth --output_model converted_model.pth\n```\n\nYou can then evaluate it using:\n```\npython train_net.py --eval-only --config configs/detr_256_6_6_torchvision.yaml  MODEL.WEIGHTS \"converted_model.pth\"\n```\n\n\n## Training\n\nTo train DETR on a single node with 8 gpus, simply use:\n```\npython train_net.py --config configs/detr_256_6_6_torchvision.yaml --num-gpus 8\n```\n\nTo fine-tune DETR for instance segmentation on a single node with 8 gpus, simply use:\n```\npython train_net.py --config configs/detr_segm_256_6_6_torchvision.yaml --num-gpus 8 MODEL.DETR.FROZEN_WEIGHTS <model_path>\n```\n"
  },
  {
    "path": "d2/configs/detr_256_6_6_torchvision.yaml",
    "content": "MODEL:\n  META_ARCHITECTURE: \"Detr\"\n  WEIGHTS: \"detectron2://ImageNetPretrained/torchvision/R-50.pkl\"\n  PIXEL_MEAN: [123.675, 116.280, 103.530]\n  PIXEL_STD: [58.395, 57.120, 57.375]\n  MASK_ON: False\n  RESNETS:\n    DEPTH: 50\n    STRIDE_IN_1X1: False\n    OUT_FEATURES: [\"res2\", \"res3\", \"res4\", \"res5\"]\n  DETR:\n    GIOU_WEIGHT: 2.0\n    L1_WEIGHT: 5.0\n    NUM_OBJECT_QUERIES: 100\nDATASETS:\n  TRAIN: (\"coco_2017_train\",)\n  TEST: (\"coco_2017_val\",)\nSOLVER:\n  IMS_PER_BATCH: 64\n  BASE_LR: 0.0001\n  STEPS: (369600,)\n  MAX_ITER: 554400\n  WARMUP_FACTOR: 1.0\n  WARMUP_ITERS: 10\n  WEIGHT_DECAY: 0.0001\n  OPTIMIZER: \"ADAMW\"\n  BACKBONE_MULTIPLIER: 0.1\n  CLIP_GRADIENTS:\n    ENABLED: True\n    CLIP_TYPE: \"full_model\"\n    CLIP_VALUE: 0.01\n    NORM_TYPE: 2.0\nINPUT:\n  MIN_SIZE_TRAIN: (480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800)\n  CROP:\n    ENABLED: True\n    TYPE: \"absolute_range\"\n    SIZE: (384, 600)\n  FORMAT: \"RGB\"\nTEST:\n  EVAL_PERIOD: 4000\nDATALOADER:\n  FILTER_EMPTY_ANNOTATIONS: False\n  NUM_WORKERS: 4\nVERSION: 2\n"
  },
  {
    "path": "d2/configs/detr_segm_256_6_6_torchvision.yaml",
    "content": "MODEL:\n  META_ARCHITECTURE: \"Detr\"\n#  WEIGHTS: \"detectron2://ImageNetPretrained/torchvision/R-50.pkl\"\n  PIXEL_MEAN: [123.675, 116.280, 103.530]\n  PIXEL_STD: [58.395, 57.120, 57.375]\n  MASK_ON: True\n  RESNETS:\n    DEPTH: 50\n    STRIDE_IN_1X1: False\n    OUT_FEATURES: [\"res2\", \"res3\", \"res4\", \"res5\"]\n  DETR:\n    GIOU_WEIGHT: 2.0\n    L1_WEIGHT: 5.0\n    NUM_OBJECT_QUERIES: 100\n    FROZEN_WEIGHTS: ''\nDATASETS:\n  TRAIN: (\"coco_2017_train\",)\n  TEST: (\"coco_2017_val\",)\nSOLVER:\n  IMS_PER_BATCH: 64\n  BASE_LR: 0.0001\n  STEPS: (55440,)\n  MAX_ITER: 92400\n  WARMUP_FACTOR: 1.0\n  WARMUP_ITERS: 10\n  WEIGHT_DECAY: 0.0001\n  OPTIMIZER: \"ADAMW\"\n  BACKBONE_MULTIPLIER: 0.1\n  CLIP_GRADIENTS:\n    ENABLED: True\n    CLIP_TYPE: \"full_model\"\n    CLIP_VALUE: 0.01\n    NORM_TYPE: 2.0\nINPUT:\n  MIN_SIZE_TRAIN: (480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800)\n  CROP:\n    ENABLED: True\n    TYPE: \"absolute_range\"\n    SIZE: (384, 600)\n  FORMAT: \"RGB\"\nTEST:\n  EVAL_PERIOD: 4000\nDATALOADER:\n  FILTER_EMPTY_ANNOTATIONS: False\n  NUM_WORKERS: 4\nVERSION: 2\n"
  },
  {
    "path": "d2/converter.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nHelper script to convert models trained with the main version of DETR to be used with the Detectron2 version.\n\"\"\"\nimport json\nimport argparse\n\nimport numpy as np\nimport torch\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\"D2 model converter\")\n\n    parser.add_argument(\"--source_model\", default=\"\", type=str, help=\"Path or url to the DETR model to convert\")\n    parser.add_argument(\"--output_model\", default=\"\", type=str, help=\"Path where to save the converted model\")\n    return parser.parse_args()\n\n\ndef main():\n    args = parse_args()\n\n    # D2 expects contiguous classes, so we need to remap the 92 classes from DETR\n    # fmt: off\n    coco_idx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n                27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51,\n                52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 70, 72, 73, 74, 75, 76, 77,\n                78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91]\n    # fmt: on\n\n    coco_idx = np.array(coco_idx)\n\n    if args.source_model.startswith(\"https\"):\n        checkpoint = torch.hub.load_state_dict_from_url(args.source_model, map_location=\"cpu\", check_hash=True)\n    else:\n        checkpoint = torch.load(args.source_model, map_location=\"cpu\")\n    model_to_convert = checkpoint[\"model\"]\n\n    model_converted = {}\n    for k in model_to_convert.keys():\n        old_k = k\n        if \"backbone\" in k:\n            k = k.replace(\"backbone.0.body.\", \"\")\n            if \"layer\" not in k:\n                k = \"stem.\" + k\n            for t in [1, 2, 3, 4]:\n                k = k.replace(f\"layer{t}\", f\"res{t + 1}\")\n            for t in [1, 2, 3]:\n                k = k.replace(f\"bn{t}\", f\"conv{t}.norm\")\n            k = k.replace(\"downsample.0\", \"shortcut\")\n            k = k.replace(\"downsample.1\", \"shortcut.norm\")\n            k = \"backbone.0.backbone.\" + k\n        k = \"detr.\" + k\n        print(old_k, \"->\", k)\n        if \"class_embed\" in old_k:\n            v = model_to_convert[old_k].detach()\n            if v.shape[0] == 92:\n                shape_old = v.shape\n                model_converted[k] = v[coco_idx]\n                print(\"Head conversion: changing shape from {} to {}\".format(shape_old, model_converted[k].shape))\n                continue\n        model_converted[k] = model_to_convert[old_k].detach()\n\n    model_to_save = {\"model\": model_converted}\n    torch.save(model_to_save, args.output_model)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "d2/detr/__init__.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nfrom .config import add_detr_config\nfrom .detr import Detr\nfrom .dataset_mapper import DetrDatasetMapper\n"
  },
  {
    "path": "d2/detr/config.py",
    "content": "# -*- coding: utf-8 -*-\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nfrom detectron2.config import CfgNode as CN\n\n\ndef add_detr_config(cfg):\n    \"\"\"\n    Add config for DETR.\n    \"\"\"\n    cfg.MODEL.DETR = CN()\n    cfg.MODEL.DETR.NUM_CLASSES = 80\n\n    # For Segmentation\n    cfg.MODEL.DETR.FROZEN_WEIGHTS = ''\n\n    # LOSS\n    cfg.MODEL.DETR.GIOU_WEIGHT = 2.0\n    cfg.MODEL.DETR.L1_WEIGHT = 5.0\n    cfg.MODEL.DETR.DEEP_SUPERVISION = True\n    cfg.MODEL.DETR.NO_OBJECT_WEIGHT = 0.1\n\n    # TRANSFORMER\n    cfg.MODEL.DETR.NHEADS = 8\n    cfg.MODEL.DETR.DROPOUT = 0.1\n    cfg.MODEL.DETR.DIM_FEEDFORWARD = 2048\n    cfg.MODEL.DETR.ENC_LAYERS = 6\n    cfg.MODEL.DETR.DEC_LAYERS = 6\n    cfg.MODEL.DETR.PRE_NORM = False\n\n    cfg.MODEL.DETR.HIDDEN_DIM = 256\n    cfg.MODEL.DETR.NUM_OBJECT_QUERIES = 100\n\n    cfg.SOLVER.OPTIMIZER = \"ADAMW\"\n    cfg.SOLVER.BACKBONE_MULTIPLIER = 0.1\n"
  },
  {
    "path": "d2/detr/dataset_mapper.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport copy\nimport logging\n\nimport numpy as np\nimport torch\n\nfrom detectron2.data import detection_utils as utils\nfrom detectron2.data import transforms as T\nfrom detectron2.data.transforms import TransformGen\n\n__all__ = [\"DetrDatasetMapper\"]\n\n\ndef build_transform_gen(cfg, is_train):\n    \"\"\"\n    Create a list of :class:`TransformGen` from config.\n    Returns:\n        list[TransformGen]\n    \"\"\"\n    if is_train:\n        min_size = cfg.INPUT.MIN_SIZE_TRAIN\n        max_size = cfg.INPUT.MAX_SIZE_TRAIN\n        sample_style = cfg.INPUT.MIN_SIZE_TRAIN_SAMPLING\n    else:\n        min_size = cfg.INPUT.MIN_SIZE_TEST\n        max_size = cfg.INPUT.MAX_SIZE_TEST\n        sample_style = \"choice\"\n    if sample_style == \"range\":\n        assert len(min_size) == 2, \"more than 2 ({}) min_size(s) are provided for ranges\".format(len(min_size))\n\n    logger = logging.getLogger(__name__)\n    tfm_gens = []\n    if is_train:\n        tfm_gens.append(T.RandomFlip())\n    tfm_gens.append(T.ResizeShortestEdge(min_size, max_size, sample_style))\n    if is_train:\n        logger.info(\"TransformGens used in training: \" + str(tfm_gens))\n    return tfm_gens\n\n\nclass DetrDatasetMapper:\n    \"\"\"\n    A callable which takes a dataset dict in Detectron2 Dataset format,\n    and map it into a format used by DETR.\n\n    The callable currently does the following:\n\n    1. Read the image from \"file_name\"\n    2. Applies geometric transforms to the image and annotation\n    3. Find and applies suitable cropping to the image and annotation\n    4. Prepare image and annotation to Tensors\n    \"\"\"\n\n    def __init__(self, cfg, is_train=True):\n        if cfg.INPUT.CROP.ENABLED and is_train:\n            self.crop_gen = [\n                T.ResizeShortestEdge([400, 500, 600], sample_style=\"choice\"),\n                T.RandomCrop(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE),\n            ]\n        else:\n            self.crop_gen = None\n\n        self.mask_on = cfg.MODEL.MASK_ON\n        self.tfm_gens = build_transform_gen(cfg, is_train)\n        logging.getLogger(__name__).info(\n            \"Full TransformGens used in training: {}, crop: {}\".format(str(self.tfm_gens), str(self.crop_gen))\n        )\n\n        self.img_format = cfg.INPUT.FORMAT\n        self.is_train = is_train\n\n    def __call__(self, dataset_dict):\n        \"\"\"\n        Args:\n            dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.\n\n        Returns:\n            dict: a format that builtin models in detectron2 accept\n        \"\"\"\n        dataset_dict = copy.deepcopy(dataset_dict)  # it will be modified by code below\n        image = utils.read_image(dataset_dict[\"file_name\"], format=self.img_format)\n        utils.check_image_size(dataset_dict, image)\n\n        if self.crop_gen is None:\n            image, transforms = T.apply_transform_gens(self.tfm_gens, image)\n        else:\n            if np.random.rand() > 0.5:\n                image, transforms = T.apply_transform_gens(self.tfm_gens, image)\n            else:\n                image, transforms = T.apply_transform_gens(\n                    self.tfm_gens[:-1] + self.crop_gen + self.tfm_gens[-1:], image\n                )\n\n        image_shape = image.shape[:2]  # h, w\n\n        # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,\n        # but not efficient on large generic data structures due to the use of pickle & mp.Queue.\n        # Therefore it's important to use torch.Tensor.\n        dataset_dict[\"image\"] = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))\n\n        if not self.is_train:\n            # USER: Modify this if you want to keep them for some reason.\n            dataset_dict.pop(\"annotations\", None)\n            return dataset_dict\n\n        if \"annotations\" in dataset_dict:\n            # USER: Modify this if you want to keep them for some reason.\n            for anno in dataset_dict[\"annotations\"]:\n                if not self.mask_on:\n                    anno.pop(\"segmentation\", None)\n                anno.pop(\"keypoints\", None)\n\n            # USER: Implement additional transformations if you have other types of data\n            annos = [\n                utils.transform_instance_annotations(obj, transforms, image_shape)\n                for obj in dataset_dict.pop(\"annotations\")\n                if obj.get(\"iscrowd\", 0) == 0\n            ]\n            instances = utils.annotations_to_instances(annos, image_shape)\n            dataset_dict[\"instances\"] = utils.filter_empty_instances(instances)\n        return dataset_dict\n"
  },
  {
    "path": "d2/detr/detr.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport logging\nimport math\nfrom typing import List\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nfrom scipy.optimize import linear_sum_assignment\nfrom torch import nn\n\nfrom detectron2.layers import ShapeSpec\nfrom detectron2.modeling import META_ARCH_REGISTRY, build_backbone, detector_postprocess\nfrom detectron2.structures import Boxes, ImageList, Instances, BitMasks, PolygonMasks\nfrom detectron2.utils.logger import log_first_n\nfrom fvcore.nn import giou_loss, smooth_l1_loss\nfrom models.backbone import Joiner\nfrom models.detr import DETR, SetCriterion\nfrom models.matcher import HungarianMatcher\nfrom models.position_encoding import PositionEmbeddingSine\nfrom models.transformer import Transformer\nfrom models.segmentation import DETRsegm, PostProcessPanoptic, PostProcessSegm\nfrom util.box_ops import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh\nfrom util.misc import NestedTensor\nfrom datasets.coco import convert_coco_poly_to_mask\n\n__all__ = [\"Detr\"]\n\n\nclass MaskedBackbone(nn.Module):\n    \"\"\" This is a thin wrapper around D2's backbone to provide padding masking\"\"\"\n\n    def __init__(self, cfg):\n        super().__init__()\n        self.backbone = build_backbone(cfg)\n        backbone_shape = self.backbone.output_shape()\n        self.feature_strides = [backbone_shape[f].stride for f in backbone_shape.keys()]\n        self.num_channels = backbone_shape[list(backbone_shape.keys())[-1]].channels\n\n    def forward(self, images):\n        features = self.backbone(images.tensor)\n        masks = self.mask_out_padding(\n            [features_per_level.shape for features_per_level in features.values()],\n            images.image_sizes,\n            images.tensor.device,\n        )\n        assert len(features) == len(masks)\n        for i, k in enumerate(features.keys()):\n            features[k] = NestedTensor(features[k], masks[i])\n        return features\n\n    def mask_out_padding(self, feature_shapes, image_sizes, device):\n        masks = []\n        assert len(feature_shapes) == len(self.feature_strides)\n        for idx, shape in enumerate(feature_shapes):\n            N, _, H, W = shape\n            masks_per_feature_level = torch.ones((N, H, W), dtype=torch.bool, device=device)\n            for img_idx, (h, w) in enumerate(image_sizes):\n                masks_per_feature_level[\n                    img_idx,\n                    : int(np.ceil(float(h) / self.feature_strides[idx])),\n                    : int(np.ceil(float(w) / self.feature_strides[idx])),\n                ] = 0\n            masks.append(masks_per_feature_level)\n        return masks\n\n\n@META_ARCH_REGISTRY.register()\nclass Detr(nn.Module):\n    \"\"\"\n    Implement Detr\n    \"\"\"\n\n    def __init__(self, cfg):\n        super().__init__()\n\n        self.device = torch.device(cfg.MODEL.DEVICE)\n\n        self.num_classes = cfg.MODEL.DETR.NUM_CLASSES\n        self.mask_on = cfg.MODEL.MASK_ON\n        hidden_dim = cfg.MODEL.DETR.HIDDEN_DIM\n        num_queries = cfg.MODEL.DETR.NUM_OBJECT_QUERIES\n        # Transformer parameters:\n        nheads = cfg.MODEL.DETR.NHEADS\n        dropout = cfg.MODEL.DETR.DROPOUT\n        dim_feedforward = cfg.MODEL.DETR.DIM_FEEDFORWARD\n        enc_layers = cfg.MODEL.DETR.ENC_LAYERS\n        dec_layers = cfg.MODEL.DETR.DEC_LAYERS\n        pre_norm = cfg.MODEL.DETR.PRE_NORM\n\n        # Loss parameters:\n        giou_weight = cfg.MODEL.DETR.GIOU_WEIGHT\n        l1_weight = cfg.MODEL.DETR.L1_WEIGHT\n        deep_supervision = cfg.MODEL.DETR.DEEP_SUPERVISION\n        no_object_weight = cfg.MODEL.DETR.NO_OBJECT_WEIGHT\n\n        N_steps = hidden_dim // 2\n        d2_backbone = MaskedBackbone(cfg)\n        backbone = Joiner(d2_backbone, PositionEmbeddingSine(N_steps, normalize=True))\n        backbone.num_channels = d2_backbone.num_channels\n\n        transformer = Transformer(\n            d_model=hidden_dim,\n            dropout=dropout,\n            nhead=nheads,\n            dim_feedforward=dim_feedforward,\n            num_encoder_layers=enc_layers,\n            num_decoder_layers=dec_layers,\n            normalize_before=pre_norm,\n            return_intermediate_dec=deep_supervision,\n        )\n\n        self.detr = DETR(\n            backbone, transformer, num_classes=self.num_classes, num_queries=num_queries, aux_loss=deep_supervision\n        )\n        if self.mask_on:\n            frozen_weights = cfg.MODEL.DETR.FROZEN_WEIGHTS\n            if frozen_weights != '':\n                print(\"LOAD pre-trained weights\")\n                weight = torch.load(frozen_weights, map_location=lambda storage, loc: storage)['model']\n                new_weight = {}\n                for k, v in weight.items():\n                    if 'detr.' in k:\n                        new_weight[k.replace('detr.', '')] = v\n                    else:\n                        print(f\"Skipping loading weight {k} from frozen model\")\n                del weight\n                self.detr.load_state_dict(new_weight)\n                del new_weight\n            self.detr = DETRsegm(self.detr, freeze_detr=(frozen_weights != ''))\n            self.seg_postprocess = PostProcessSegm\n\n        self.detr.to(self.device)\n\n        # building criterion\n        matcher = HungarianMatcher(cost_class=1, cost_bbox=l1_weight, cost_giou=giou_weight)\n        weight_dict = {\"loss_ce\": 1, \"loss_bbox\": l1_weight}\n        weight_dict[\"loss_giou\"] = giou_weight\n        if deep_supervision:\n            aux_weight_dict = {}\n            for i in range(dec_layers - 1):\n                aux_weight_dict.update({k + f\"_{i}\": v for k, v in weight_dict.items()})\n            weight_dict.update(aux_weight_dict)\n        losses = [\"labels\", \"boxes\", \"cardinality\"]\n        if self.mask_on:\n            losses += [\"masks\"]\n        self.criterion = SetCriterion(\n            self.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=no_object_weight, losses=losses,\n        )\n        self.criterion.to(self.device)\n\n        pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(3, 1, 1)\n        pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(3, 1, 1)\n        self.normalizer = lambda x: (x - pixel_mean) / pixel_std\n        self.to(self.device)\n\n    def forward(self, batched_inputs):\n        \"\"\"\n        Args:\n            batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n                Each item in the list contains the inputs for one image.\n                For now, each item in the list is a dict that contains:\n\n                * image: Tensor, image in (C, H, W) format.\n                * instances: Instances\n\n                Other information that's included in the original dicts, such as:\n\n                * \"height\", \"width\" (int): the output resolution of the model, used in inference.\n                  See :meth:`postprocess` for details.\n        Returns:\n            dict[str: Tensor]:\n                mapping from a named loss to a tensor storing the loss. Used during training only.\n        \"\"\"\n        images = self.preprocess_image(batched_inputs)\n        output = self.detr(images)\n\n        if self.training:\n            gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n\n            targets = self.prepare_targets(gt_instances)\n            loss_dict = self.criterion(output, targets)\n            weight_dict = self.criterion.weight_dict\n            for k in loss_dict.keys():\n                if k in weight_dict:\n                    loss_dict[k] *= weight_dict[k]\n            return loss_dict\n        else:\n            box_cls = output[\"pred_logits\"]\n            box_pred = output[\"pred_boxes\"]\n            mask_pred = output[\"pred_masks\"] if self.mask_on else None\n            results = self.inference(box_cls, box_pred, mask_pred, images.image_sizes)\n            processed_results = []\n            for results_per_image, input_per_image, image_size in zip(results, batched_inputs, images.image_sizes):\n                height = input_per_image.get(\"height\", image_size[0])\n                width = input_per_image.get(\"width\", image_size[1])\n                r = detector_postprocess(results_per_image, height, width)\n                processed_results.append({\"instances\": r})\n            return processed_results\n\n    def prepare_targets(self, targets):\n        new_targets = []\n        for targets_per_image in targets:\n            h, w = targets_per_image.image_size\n            image_size_xyxy = torch.as_tensor([w, h, w, h], dtype=torch.float, device=self.device)\n            gt_classes = targets_per_image.gt_classes\n            gt_boxes = targets_per_image.gt_boxes.tensor / image_size_xyxy\n            gt_boxes = box_xyxy_to_cxcywh(gt_boxes)\n            new_targets.append({\"labels\": gt_classes, \"boxes\": gt_boxes})\n            if self.mask_on and hasattr(targets_per_image, 'gt_masks'):\n                gt_masks = targets_per_image.gt_masks\n                gt_masks = convert_coco_poly_to_mask(gt_masks.polygons, h, w)\n                new_targets[-1].update({'masks': gt_masks})\n        return new_targets\n\n    def inference(self, box_cls, box_pred, mask_pred, image_sizes):\n        \"\"\"\n        Arguments:\n            box_cls (Tensor): tensor of shape (batch_size, num_queries, K).\n                The tensor predicts the classification probability for each query.\n            box_pred (Tensor): tensors of shape (batch_size, num_queries, 4).\n                The tensor predicts 4-vector (x,y,w,h) box\n                regression values for every queryx\n            image_sizes (List[torch.Size]): the input image sizes\n\n        Returns:\n            results (List[Instances]): a list of #images elements.\n        \"\"\"\n        assert len(box_cls) == len(image_sizes)\n        results = []\n\n        # For each box we assign the best class or the second best if the best on is `no_object`.\n        scores, labels = F.softmax(box_cls, dim=-1)[:, :, :-1].max(-1)\n\n        for i, (scores_per_image, labels_per_image, box_pred_per_image, image_size) in enumerate(zip(\n            scores, labels, box_pred, image_sizes\n        )):\n            result = Instances(image_size)\n            result.pred_boxes = Boxes(box_cxcywh_to_xyxy(box_pred_per_image))\n\n            result.pred_boxes.scale(scale_x=image_size[1], scale_y=image_size[0])\n            if self.mask_on:\n                mask = F.interpolate(mask_pred[i].unsqueeze(0), size=image_size, mode='bilinear', align_corners=False)\n                mask = mask[0].sigmoid() > 0.5\n                B, N, H, W = mask_pred.shape\n                mask = BitMasks(mask.cpu()).crop_and_resize(result.pred_boxes.tensor.cpu(), 32)\n                result.pred_masks = mask.unsqueeze(1).to(mask_pred[0].device)\n\n            result.scores = scores_per_image\n            result.pred_classes = labels_per_image\n            results.append(result)\n        return results\n\n    def preprocess_image(self, batched_inputs):\n        \"\"\"\n        Normalize, pad and batch the input images.\n        \"\"\"\n        images = [self.normalizer(x[\"image\"].to(self.device)) for x in batched_inputs]\n        images = ImageList.from_tensors(images)\n        return images\n"
  },
  {
    "path": "d2/train_net.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nDETR Training Script.\n\nThis script is a simplified version of the training script in detectron2/tools.\n\"\"\"\nimport os\nimport sys\nimport itertools\n\n# fmt: off\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\n# fmt: on\n\nimport time\nfrom typing import Any, Dict, List, Set\n\nimport torch\n\nimport detectron2.utils.comm as comm\nfrom d2.detr import DetrDatasetMapper, add_detr_config\nfrom detectron2.checkpoint import DetectionCheckpointer\nfrom detectron2.config import get_cfg\nfrom detectron2.data import MetadataCatalog, build_detection_train_loader\nfrom detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch\nfrom detectron2.evaluation import COCOEvaluator, verify_results\n\nfrom detectron2.solver.build import maybe_add_gradient_clipping\n\n\nclass Trainer(DefaultTrainer):\n    \"\"\"\n    Extension of the Trainer class adapted to DETR.\n    \"\"\"\n\n    @classmethod\n    def build_evaluator(cls, cfg, dataset_name, output_folder=None):\n        \"\"\"\n        Create evaluator(s) for a given dataset.\n        This uses the special metadata \"evaluator_type\" associated with each builtin dataset.\n        For your own dataset, you can simply create an evaluator manually in your\n        script and do not have to worry about the hacky if-else logic here.\n        \"\"\"\n        if output_folder is None:\n            output_folder = os.path.join(cfg.OUTPUT_DIR, \"inference\")\n        return COCOEvaluator(dataset_name, cfg, True, output_folder)\n\n    @classmethod\n    def build_train_loader(cls, cfg):\n        if \"Detr\" == cfg.MODEL.META_ARCHITECTURE:\n            mapper = DetrDatasetMapper(cfg, True)\n        else:\n            mapper = None\n        return build_detection_train_loader(cfg, mapper=mapper)\n\n    @classmethod\n    def build_optimizer(cls, cfg, model):\n        params: List[Dict[str, Any]] = []\n        memo: Set[torch.nn.parameter.Parameter] = set()\n        for key, value in model.named_parameters(recurse=True):\n            if not value.requires_grad:\n                continue\n            # Avoid duplicating parameters\n            if value in memo:\n                continue\n            memo.add(value)\n            lr = cfg.SOLVER.BASE_LR\n            weight_decay = cfg.SOLVER.WEIGHT_DECAY\n            if \"backbone\" in key:\n                lr = lr * cfg.SOLVER.BACKBONE_MULTIPLIER\n            params += [{\"params\": [value], \"lr\": lr, \"weight_decay\": weight_decay}]\n\n        def maybe_add_full_model_gradient_clipping(optim):  # optim: the optimizer class\n            # detectron2 doesn't have full model gradient clipping now\n            clip_norm_val = cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE\n            enable = (\n                cfg.SOLVER.CLIP_GRADIENTS.ENABLED\n                and cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == \"full_model\"\n                and clip_norm_val > 0.0\n            )\n\n            class FullModelGradientClippingOptimizer(optim):\n                def step(self, closure=None):\n                    all_params = itertools.chain(*[x[\"params\"] for x in self.param_groups])\n                    torch.nn.utils.clip_grad_norm_(all_params, clip_norm_val)\n                    super().step(closure=closure)\n\n            return FullModelGradientClippingOptimizer if enable else optim\n\n        optimizer_type = cfg.SOLVER.OPTIMIZER\n        if optimizer_type == \"SGD\":\n            optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)(\n                params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM\n            )\n        elif optimizer_type == \"ADAMW\":\n            optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)(\n                params, cfg.SOLVER.BASE_LR\n            )\n        else:\n            raise NotImplementedError(f\"no optimizer type {optimizer_type}\")\n        if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == \"full_model\":\n            optimizer = maybe_add_gradient_clipping(cfg, optimizer)\n        return optimizer\n\n\ndef setup(args):\n    \"\"\"\n    Create configs and perform basic setups.\n    \"\"\"\n    cfg = get_cfg()\n    add_detr_config(cfg)\n    cfg.merge_from_file(args.config_file)\n    cfg.merge_from_list(args.opts)\n    cfg.freeze()\n    default_setup(cfg, args)\n    return cfg\n\n\ndef main(args):\n    cfg = setup(args)\n\n    if args.eval_only:\n        model = Trainer.build_model(cfg)\n        DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume)\n        res = Trainer.test(cfg, model)\n        if comm.is_main_process():\n            verify_results(cfg, res)\n        return res\n\n    trainer = Trainer(cfg)\n    trainer.resume_or_load(resume=args.resume)\n    return trainer.train()\n\n\nif __name__ == \"__main__\":\n    args = default_argument_parser().parse_args()\n    print(\"Command Line Args:\", args)\n    launch(\n        main,\n        args.num_gpus,\n        num_machines=args.num_machines,\n        machine_rank=args.machine_rank,\n        dist_url=args.dist_url,\n        args=(args,),\n    )\n"
  },
  {
    "path": "datasets/__init__.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport torch.utils.data\nimport torchvision\n\nfrom .coco import build as build_coco\n\n\ndef get_coco_api_from_dataset(dataset):\n    for _ in range(10):\n        # if isinstance(dataset, torchvision.datasets.CocoDetection):\n        #     break\n        if isinstance(dataset, torch.utils.data.Subset):\n            dataset = dataset.dataset\n    if isinstance(dataset, torchvision.datasets.CocoDetection):\n        return dataset.coco\n\n\ndef build_dataset(image_set, args):\n    if args.dataset_file == 'coco':\n        return build_coco(image_set, args)\n    if args.dataset_file == 'coco_panoptic':\n        # to avoid making panopticapi required for coco\n        from .coco_panoptic import build as build_coco_panoptic\n        return build_coco_panoptic(image_set, args)\n    raise ValueError(f'dataset {args.dataset_file} not supported')\n"
  },
  {
    "path": "datasets/coco.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nCOCO dataset which returns image_id for evaluation.\n\nMostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py\n\"\"\"\nfrom pathlib import Path\n\nimport torch\nimport torch.utils.data\nimport torchvision\nfrom pycocotools import mask as coco_mask\n\nimport datasets.transforms as T\n\n\nclass CocoDetection(torchvision.datasets.CocoDetection):\n    def __init__(self, img_folder, ann_file, transforms, return_masks):\n        super(CocoDetection, self).__init__(img_folder, ann_file)\n        self._transforms = transforms\n        self.prepare = ConvertCocoPolysToMask(return_masks)\n\n    def __getitem__(self, idx):\n        img, target = super(CocoDetection, self).__getitem__(idx)\n        image_id = self.ids[idx]\n        target = {'image_id': image_id, 'annotations': target}\n        img, target = self.prepare(img, target)\n        if self._transforms is not None:\n            img, target = self._transforms(img, target)\n        return img, target\n\n\ndef convert_coco_poly_to_mask(segmentations, height, width):\n    masks = []\n    for polygons in segmentations:\n        rles = coco_mask.frPyObjects(polygons, height, width)\n        mask = coco_mask.decode(rles)\n        if len(mask.shape) < 3:\n            mask = mask[..., None]\n        mask = torch.as_tensor(mask, dtype=torch.uint8)\n        mask = mask.any(dim=2)\n        masks.append(mask)\n    if masks:\n        masks = torch.stack(masks, dim=0)\n    else:\n        masks = torch.zeros((0, height, width), dtype=torch.uint8)\n    return masks\n\n\nclass ConvertCocoPolysToMask(object):\n    def __init__(self, return_masks=False):\n        self.return_masks = return_masks\n\n    def __call__(self, image, target):\n        w, h = image.size\n\n        image_id = target[\"image_id\"]\n        image_id = torch.tensor([image_id])\n\n        anno = target[\"annotations\"]\n\n        anno = [obj for obj in anno if 'iscrowd' not in obj or obj['iscrowd'] == 0]\n\n        boxes = [obj[\"bbox\"] for obj in anno]\n        # guard against no boxes via resizing\n        boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4)\n        boxes[:, 2:] += boxes[:, :2]\n        boxes[:, 0::2].clamp_(min=0, max=w)\n        boxes[:, 1::2].clamp_(min=0, max=h)\n\n        classes = [obj[\"category_id\"] for obj in anno]\n        classes = torch.tensor(classes, dtype=torch.int64)\n\n        if self.return_masks:\n            segmentations = [obj[\"segmentation\"] for obj in anno]\n            masks = convert_coco_poly_to_mask(segmentations, h, w)\n\n        keypoints = None\n        if anno and \"keypoints\" in anno[0]:\n            keypoints = [obj[\"keypoints\"] for obj in anno]\n            keypoints = torch.as_tensor(keypoints, dtype=torch.float32)\n            num_keypoints = keypoints.shape[0]\n            if num_keypoints:\n                keypoints = keypoints.view(num_keypoints, -1, 3)\n\n        keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])\n        boxes = boxes[keep]\n        classes = classes[keep]\n        if self.return_masks:\n            masks = masks[keep]\n        if keypoints is not None:\n            keypoints = keypoints[keep]\n\n        target = {}\n        target[\"boxes\"] = boxes\n        target[\"labels\"] = classes\n        if self.return_masks:\n            target[\"masks\"] = masks\n        target[\"image_id\"] = image_id\n        if keypoints is not None:\n            target[\"keypoints\"] = keypoints\n\n        # for conversion to coco api\n        area = torch.tensor([obj[\"area\"] for obj in anno])\n        iscrowd = torch.tensor([obj[\"iscrowd\"] if \"iscrowd\" in obj else 0 for obj in anno])\n        target[\"area\"] = area[keep]\n        target[\"iscrowd\"] = iscrowd[keep]\n\n        target[\"orig_size\"] = torch.as_tensor([int(h), int(w)])\n        target[\"size\"] = torch.as_tensor([int(h), int(w)])\n\n        return image, target\n\n\ndef make_coco_transforms(image_set):\n\n    normalize = T.Compose([\n        T.ToTensor(),\n        T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n    ])\n\n    scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800]\n\n    if image_set == 'train':\n        return T.Compose([\n            T.RandomHorizontalFlip(),\n            T.RandomSelect(\n                T.RandomResize(scales, max_size=1333),\n                T.Compose([\n                    T.RandomResize([400, 500, 600]),\n                    T.RandomSizeCrop(384, 600),\n                    T.RandomResize(scales, max_size=1333),\n                ])\n            ),\n            normalize,\n        ])\n\n    if image_set == 'val':\n        return T.Compose([\n            T.RandomResize([800], max_size=1333),\n            normalize,\n        ])\n\n    raise ValueError(f'unknown {image_set}')\n\n\ndef build(image_set, args):\n    root = Path(args.coco_path)\n    assert root.exists(), f'provided COCO path {root} does not exist'\n    mode = 'instances'\n    PATHS = {\n        \"train\": (root / \"train2017\", root / \"annotations\" / f'{mode}_train2017.json'),\n        \"val\": (root / \"val2017\", root / \"annotations\" / f'{mode}_val2017.json'),\n    }\n\n    img_folder, ann_file = PATHS[image_set]\n    dataset = CocoDetection(img_folder, ann_file, transforms=make_coco_transforms(image_set), return_masks=args.masks)\n    return dataset\n"
  },
  {
    "path": "datasets/coco_eval.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nCOCO evaluator that works in distributed mode.\n\nMostly copy-paste from https://github.com/pytorch/vision/blob/edfd5a7/references/detection/coco_eval.py\nThe difference is that there is less copy-pasting from pycocotools\nin the end of the file, as python3 can suppress prints with contextlib\n\"\"\"\nimport os\nimport contextlib\nimport copy\nimport numpy as np\nimport torch\n\nfrom pycocotools.cocoeval import COCOeval\nfrom pycocotools.coco import COCO\nimport pycocotools.mask as mask_util\n\nfrom util.misc import all_gather\n\n\nclass CocoEvaluator(object):\n    def __init__(self, coco_gt, iou_types):\n        assert isinstance(iou_types, (list, tuple))\n        coco_gt = copy.deepcopy(coco_gt)\n        self.coco_gt = coco_gt\n\n        self.iou_types = iou_types\n        self.coco_eval = {}\n        for iou_type in iou_types:\n            self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type)\n\n        self.img_ids = []\n        self.eval_imgs = {k: [] for k in iou_types}\n\n    def update(self, predictions):\n        img_ids = list(np.unique(list(predictions.keys())))\n        self.img_ids.extend(img_ids)\n\n        for iou_type in self.iou_types:\n            results = self.prepare(predictions, iou_type)\n\n            # suppress pycocotools prints\n            with open(os.devnull, 'w') as devnull:\n                with contextlib.redirect_stdout(devnull):\n                    coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO()\n            coco_eval = self.coco_eval[iou_type]\n\n            coco_eval.cocoDt = coco_dt\n            coco_eval.params.imgIds = list(img_ids)\n            img_ids, eval_imgs = evaluate(coco_eval)\n\n            self.eval_imgs[iou_type].append(eval_imgs)\n\n    def synchronize_between_processes(self):\n        for iou_type in self.iou_types:\n            self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2)\n            create_common_coco_eval(self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type])\n\n    def accumulate(self):\n        for coco_eval in self.coco_eval.values():\n            coco_eval.accumulate()\n\n    def summarize(self):\n        for iou_type, coco_eval in self.coco_eval.items():\n            print(\"IoU metric: {}\".format(iou_type))\n            coco_eval.summarize()\n\n    def prepare(self, predictions, iou_type):\n        if iou_type == \"bbox\":\n            return self.prepare_for_coco_detection(predictions)\n        elif iou_type == \"segm\":\n            return self.prepare_for_coco_segmentation(predictions)\n        elif iou_type == \"keypoints\":\n            return self.prepare_for_coco_keypoint(predictions)\n        else:\n            raise ValueError(\"Unknown iou type {}\".format(iou_type))\n\n    def prepare_for_coco_detection(self, predictions):\n        coco_results = []\n        for original_id, prediction in predictions.items():\n            if len(prediction) == 0:\n                continue\n\n            boxes = prediction[\"boxes\"]\n            boxes = convert_to_xywh(boxes).tolist()\n            scores = prediction[\"scores\"].tolist()\n            labels = prediction[\"labels\"].tolist()\n\n            coco_results.extend(\n                [\n                    {\n                        \"image_id\": original_id,\n                        \"category_id\": labels[k],\n                        \"bbox\": box,\n                        \"score\": scores[k],\n                    }\n                    for k, box in enumerate(boxes)\n                ]\n            )\n        return coco_results\n\n    def prepare_for_coco_segmentation(self, predictions):\n        coco_results = []\n        for original_id, prediction in predictions.items():\n            if len(prediction) == 0:\n                continue\n\n            scores = prediction[\"scores\"]\n            labels = prediction[\"labels\"]\n            masks = prediction[\"masks\"]\n\n            masks = masks > 0.5\n\n            scores = prediction[\"scores\"].tolist()\n            labels = prediction[\"labels\"].tolist()\n\n            rles = [\n                mask_util.encode(np.array(mask[0, :, :, np.newaxis], dtype=np.uint8, order=\"F\"))[0]\n                for mask in masks\n            ]\n            for rle in rles:\n                rle[\"counts\"] = rle[\"counts\"].decode(\"utf-8\")\n\n            coco_results.extend(\n                [\n                    {\n                        \"image_id\": original_id,\n                        \"category_id\": labels[k],\n                        \"segmentation\": rle,\n                        \"score\": scores[k],\n                    }\n                    for k, rle in enumerate(rles)\n                ]\n            )\n        return coco_results\n\n    def prepare_for_coco_keypoint(self, predictions):\n        coco_results = []\n        for original_id, prediction in predictions.items():\n            if len(prediction) == 0:\n                continue\n\n            boxes = prediction[\"boxes\"]\n            boxes = convert_to_xywh(boxes).tolist()\n            scores = prediction[\"scores\"].tolist()\n            labels = prediction[\"labels\"].tolist()\n            keypoints = prediction[\"keypoints\"]\n            keypoints = keypoints.flatten(start_dim=1).tolist()\n\n            coco_results.extend(\n                [\n                    {\n                        \"image_id\": original_id,\n                        \"category_id\": labels[k],\n                        'keypoints': keypoint,\n                        \"score\": scores[k],\n                    }\n                    for k, keypoint in enumerate(keypoints)\n                ]\n            )\n        return coco_results\n\n\ndef convert_to_xywh(boxes):\n    xmin, ymin, xmax, ymax = boxes.unbind(1)\n    return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1)\n\n\ndef merge(img_ids, eval_imgs):\n    all_img_ids = all_gather(img_ids)\n    all_eval_imgs = all_gather(eval_imgs)\n\n    merged_img_ids = []\n    for p in all_img_ids:\n        merged_img_ids.extend(p)\n\n    merged_eval_imgs = []\n    for p in all_eval_imgs:\n        merged_eval_imgs.append(p)\n\n    merged_img_ids = np.array(merged_img_ids)\n    merged_eval_imgs = np.concatenate(merged_eval_imgs, 2)\n\n    # keep only unique (and in sorted order) images\n    merged_img_ids, idx = np.unique(merged_img_ids, return_index=True)\n    merged_eval_imgs = merged_eval_imgs[..., idx]\n\n    return merged_img_ids, merged_eval_imgs\n\n\ndef create_common_coco_eval(coco_eval, img_ids, eval_imgs):\n    img_ids, eval_imgs = merge(img_ids, eval_imgs)\n    img_ids = list(img_ids)\n    eval_imgs = list(eval_imgs.flatten())\n\n    coco_eval.evalImgs = eval_imgs\n    coco_eval.params.imgIds = img_ids\n    coco_eval._paramsEval = copy.deepcopy(coco_eval.params)\n\n\n#################################################################\n# From pycocotools, just removed the prints and fixed\n# a Python3 bug about unicode not defined\n#################################################################\n\n\ndef evaluate(self):\n    '''\n    Run per image evaluation on given images and store results (a list of dict) in self.evalImgs\n    :return: None\n    '''\n    # tic = time.time()\n    # print('Running per image evaluation...')\n    p = self.params\n    # add backward compatibility if useSegm is specified in params\n    if p.useSegm is not None:\n        p.iouType = 'segm' if p.useSegm == 1 else 'bbox'\n        print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType))\n    # print('Evaluate annotation type *{}*'.format(p.iouType))\n    p.imgIds = list(np.unique(p.imgIds))\n    if p.useCats:\n        p.catIds = list(np.unique(p.catIds))\n    p.maxDets = sorted(p.maxDets)\n    self.params = p\n\n    self._prepare()\n    # loop through images, area range, max detection number\n    catIds = p.catIds if p.useCats else [-1]\n\n    if p.iouType == 'segm' or p.iouType == 'bbox':\n        computeIoU = self.computeIoU\n    elif p.iouType == 'keypoints':\n        computeIoU = self.computeOks\n    self.ious = {\n        (imgId, catId): computeIoU(imgId, catId)\n        for imgId in p.imgIds\n        for catId in catIds}\n\n    evaluateImg = self.evaluateImg\n    maxDet = p.maxDets[-1]\n    evalImgs = [\n        evaluateImg(imgId, catId, areaRng, maxDet)\n        for catId in catIds\n        for areaRng in p.areaRng\n        for imgId in p.imgIds\n    ]\n    # this is NOT in the pycocotools code, but could be done outside\n    evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds))\n    self._paramsEval = copy.deepcopy(self.params)\n    # toc = time.time()\n    # print('DONE (t={:0.2f}s).'.format(toc-tic))\n    return p.imgIds, evalImgs\n\n#################################################################\n# end of straight copy from pycocotools, just removing the prints\n#################################################################\n"
  },
  {
    "path": "datasets/coco_panoptic.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport json\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom PIL import Image\n\nfrom panopticapi.utils import rgb2id\nfrom util.box_ops import masks_to_boxes\n\nfrom .coco import make_coco_transforms\n\n\nclass CocoPanoptic:\n    def __init__(self, img_folder, ann_folder, ann_file, transforms=None, return_masks=True):\n        with open(ann_file, 'r') as f:\n            self.coco = json.load(f)\n\n        # sort 'images' field so that they are aligned with 'annotations'\n        # i.e., in alphabetical order\n        self.coco['images'] = sorted(self.coco['images'], key=lambda x: x['id'])\n        # sanity check\n        if \"annotations\" in self.coco:\n            for img, ann in zip(self.coco['images'], self.coco['annotations']):\n                assert img['file_name'][:-4] == ann['file_name'][:-4]\n\n        self.img_folder = img_folder\n        self.ann_folder = ann_folder\n        self.ann_file = ann_file\n        self.transforms = transforms\n        self.return_masks = return_masks\n\n    def __getitem__(self, idx):\n        ann_info = self.coco['annotations'][idx] if \"annotations\" in self.coco else self.coco['images'][idx]\n        img_path = Path(self.img_folder) / ann_info['file_name'].replace('.png', '.jpg')\n        ann_path = Path(self.ann_folder) / ann_info['file_name']\n\n        img = Image.open(img_path).convert('RGB')\n        w, h = img.size\n        if \"segments_info\" in ann_info:\n            masks = np.asarray(Image.open(ann_path), dtype=np.uint32)\n            masks = rgb2id(masks)\n\n            ids = np.array([ann['id'] for ann in ann_info['segments_info']])\n            masks = masks == ids[:, None, None]\n\n            masks = torch.as_tensor(masks, dtype=torch.uint8)\n            labels = torch.tensor([ann['category_id'] for ann in ann_info['segments_info']], dtype=torch.int64)\n\n        target = {}\n        target['image_id'] = torch.tensor([ann_info['image_id'] if \"image_id\" in ann_info else ann_info[\"id\"]])\n        if self.return_masks:\n            target['masks'] = masks\n        target['labels'] = labels\n\n        target[\"boxes\"] = masks_to_boxes(masks)\n\n        target['size'] = torch.as_tensor([int(h), int(w)])\n        target['orig_size'] = torch.as_tensor([int(h), int(w)])\n        if \"segments_info\" in ann_info:\n            for name in ['iscrowd', 'area']:\n                target[name] = torch.tensor([ann[name] for ann in ann_info['segments_info']])\n\n        if self.transforms is not None:\n            img, target = self.transforms(img, target)\n\n        return img, target\n\n    def __len__(self):\n        return len(self.coco['images'])\n\n    def get_height_and_width(self, idx):\n        img_info = self.coco['images'][idx]\n        height = img_info['height']\n        width = img_info['width']\n        return height, width\n\n\ndef build(image_set, args):\n    img_folder_root = Path(args.coco_path)\n    ann_folder_root = Path(args.coco_panoptic_path)\n    assert img_folder_root.exists(), f'provided COCO path {img_folder_root} does not exist'\n    assert ann_folder_root.exists(), f'provided COCO path {ann_folder_root} does not exist'\n    mode = 'panoptic'\n    PATHS = {\n        \"train\": (\"train2017\", Path(\"annotations\") / f'{mode}_train2017.json'),\n        \"val\": (\"val2017\", Path(\"annotations\") / f'{mode}_val2017.json'),\n    }\n\n    img_folder, ann_file = PATHS[image_set]\n    img_folder_path = img_folder_root / img_folder\n    ann_folder = ann_folder_root / f'{mode}_{img_folder}'\n    ann_file = ann_folder_root / ann_file\n\n    dataset = CocoPanoptic(img_folder_path, ann_folder, ann_file,\n                           transforms=make_coco_transforms(image_set), return_masks=args.masks)\n\n    return dataset\n"
  },
  {
    "path": "datasets/panoptic_eval.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport json\nimport os\n\nimport util.misc as utils\n\ntry:\n    from panopticapi.evaluation import pq_compute\nexcept ImportError:\n    pass\n\n\nclass PanopticEvaluator(object):\n    def __init__(self, ann_file, ann_folder, output_dir=\"panoptic_eval\"):\n        self.gt_json = ann_file\n        self.gt_folder = ann_folder\n        if utils.is_main_process():\n            if not os.path.exists(output_dir):\n                os.mkdir(output_dir)\n        self.output_dir = output_dir\n        self.predictions = []\n\n    def update(self, predictions):\n        for p in predictions:\n            with open(os.path.join(self.output_dir, p[\"file_name\"]), \"wb\") as f:\n                f.write(p.pop(\"png_string\"))\n\n        self.predictions += predictions\n\n    def synchronize_between_processes(self):\n        all_predictions = utils.all_gather(self.predictions)\n        merged_predictions = []\n        for p in all_predictions:\n            merged_predictions += p\n        self.predictions = merged_predictions\n\n    def summarize(self):\n        if utils.is_main_process():\n            json_data = {\"annotations\": self.predictions}\n            predictions_json = os.path.join(self.output_dir, \"predictions.json\")\n            with open(predictions_json, \"w\") as f:\n                f.write(json.dumps(json_data))\n            return pq_compute(self.gt_json, predictions_json, gt_folder=self.gt_folder, pred_folder=self.output_dir)\n        return None\n"
  },
  {
    "path": "datasets/transforms.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nTransforms and data augmentation for both image + bbox.\n\"\"\"\nimport random\n\nimport PIL\nimport torch\nimport torchvision.transforms as T\nimport torchvision.transforms.functional as F\n\nfrom util.box_ops import box_xyxy_to_cxcywh\nfrom util.misc import interpolate\n\n\ndef crop(image, target, region):\n    cropped_image = F.crop(image, *region)\n\n    target = target.copy()\n    i, j, h, w = region\n\n    # should we do something wrt the original size?\n    target[\"size\"] = torch.tensor([h, w])\n\n    fields = [\"labels\", \"area\", \"iscrowd\"]\n\n    if \"boxes\" in target:\n        boxes = target[\"boxes\"]\n        max_size = torch.as_tensor([w, h], dtype=torch.float32)\n        cropped_boxes = boxes - torch.as_tensor([j, i, j, i])\n        cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)\n        cropped_boxes = cropped_boxes.clamp(min=0)\n        area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)\n        target[\"boxes\"] = cropped_boxes.reshape(-1, 4)\n        target[\"area\"] = area\n        fields.append(\"boxes\")\n\n    if \"masks\" in target:\n        # FIXME should we update the area here if there are no boxes?\n        target['masks'] = target['masks'][:, i:i + h, j:j + w]\n        fields.append(\"masks\")\n\n    # remove elements for which the boxes or masks that have zero area\n    if \"boxes\" in target or \"masks\" in target:\n        # favor boxes selection when defining which elements to keep\n        # this is compatible with previous implementation\n        if \"boxes\" in target:\n            cropped_boxes = target['boxes'].reshape(-1, 2, 2)\n            keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1)\n        else:\n            keep = target['masks'].flatten(1).any(1)\n\n        for field in fields:\n            target[field] = target[field][keep]\n\n    return cropped_image, target\n\n\ndef hflip(image, target):\n    flipped_image = F.hflip(image)\n\n    w, h = image.size\n\n    target = target.copy()\n    if \"boxes\" in target:\n        boxes = target[\"boxes\"]\n        boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor([w, 0, w, 0])\n        target[\"boxes\"] = boxes\n\n    if \"masks\" in target:\n        target['masks'] = target['masks'].flip(-1)\n\n    return flipped_image, target\n\n\ndef resize(image, target, size, max_size=None):\n    # size can be min_size (scalar) or (w, h) tuple\n\n    def get_size_with_aspect_ratio(image_size, size, max_size=None):\n        w, h = image_size\n        if max_size is not None:\n            min_original_size = float(min((w, h)))\n            max_original_size = float(max((w, h)))\n            if max_original_size / min_original_size * size > max_size:\n                size = int(round(max_size * min_original_size / max_original_size))\n\n        if (w <= h and w == size) or (h <= w and h == size):\n            return (h, w)\n\n        if w < h:\n            ow = size\n            oh = int(size * h / w)\n        else:\n            oh = size\n            ow = int(size * w / h)\n\n        return (oh, ow)\n\n    def get_size(image_size, size, max_size=None):\n        if isinstance(size, (list, tuple)):\n            return size[::-1]\n        else:\n            return get_size_with_aspect_ratio(image_size, size, max_size)\n\n    size = get_size(image.size, size, max_size)\n    rescaled_image = F.resize(image, size)\n\n    if target is None:\n        return rescaled_image, None\n\n    ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size))\n    ratio_width, ratio_height = ratios\n\n    target = target.copy()\n    if \"boxes\" in target:\n        boxes = target[\"boxes\"]\n        scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height])\n        target[\"boxes\"] = scaled_boxes\n\n    if \"area\" in target:\n        area = target[\"area\"]\n        scaled_area = area * (ratio_width * ratio_height)\n        target[\"area\"] = scaled_area\n\n    h, w = size\n    target[\"size\"] = torch.tensor([h, w])\n\n    if \"masks\" in target:\n        target['masks'] = interpolate(\n            target['masks'][:, None].float(), size, mode=\"nearest\")[:, 0] > 0.5\n\n    return rescaled_image, target\n\n\ndef pad(image, target, padding):\n    # assumes that we only pad on the bottom right corners\n    padded_image = F.pad(image, (0, 0, padding[0], padding[1]))\n    if target is None:\n        return padded_image, None\n    target = target.copy()\n    # should we do something wrt the original size?\n    target[\"size\"] = torch.tensor(padded_image.size[::-1])\n    if \"masks\" in target:\n        target['masks'] = torch.nn.functional.pad(target['masks'], (0, padding[0], 0, padding[1]))\n    return padded_image, target\n\n\nclass RandomCrop(object):\n    def __init__(self, size):\n        self.size = size\n\n    def __call__(self, img, target):\n        region = T.RandomCrop.get_params(img, self.size)\n        return crop(img, target, region)\n\n\nclass RandomSizeCrop(object):\n    def __init__(self, min_size: int, max_size: int):\n        self.min_size = min_size\n        self.max_size = max_size\n\n    def __call__(self, img: PIL.Image.Image, target: dict):\n        w = random.randint(self.min_size, min(img.width, self.max_size))\n        h = random.randint(self.min_size, min(img.height, self.max_size))\n        region = T.RandomCrop.get_params(img, [h, w])\n        return crop(img, target, region)\n\n\nclass CenterCrop(object):\n    def __init__(self, size):\n        self.size = size\n\n    def __call__(self, img, target):\n        image_width, image_height = img.size\n        crop_height, crop_width = self.size\n        crop_top = int(round((image_height - crop_height) / 2.))\n        crop_left = int(round((image_width - crop_width) / 2.))\n        return crop(img, target, (crop_top, crop_left, crop_height, crop_width))\n\n\nclass RandomHorizontalFlip(object):\n    def __init__(self, p=0.5):\n        self.p = p\n\n    def __call__(self, img, target):\n        if random.random() < self.p:\n            return hflip(img, target)\n        return img, target\n\n\nclass RandomResize(object):\n    def __init__(self, sizes, max_size=None):\n        assert isinstance(sizes, (list, tuple))\n        self.sizes = sizes\n        self.max_size = max_size\n\n    def __call__(self, img, target=None):\n        size = random.choice(self.sizes)\n        return resize(img, target, size, self.max_size)\n\n\nclass RandomPad(object):\n    def __init__(self, max_pad):\n        self.max_pad = max_pad\n\n    def __call__(self, img, target):\n        pad_x = random.randint(0, self.max_pad)\n        pad_y = random.randint(0, self.max_pad)\n        return pad(img, target, (pad_x, pad_y))\n\n\nclass RandomSelect(object):\n    \"\"\"\n    Randomly selects between transforms1 and transforms2,\n    with probability p for transforms1 and (1 - p) for transforms2\n    \"\"\"\n    def __init__(self, transforms1, transforms2, p=0.5):\n        self.transforms1 = transforms1\n        self.transforms2 = transforms2\n        self.p = p\n\n    def __call__(self, img, target):\n        if random.random() < self.p:\n            return self.transforms1(img, target)\n        return self.transforms2(img, target)\n\n\nclass ToTensor(object):\n    def __call__(self, img, target):\n        return F.to_tensor(img), target\n\n\nclass RandomErasing(object):\n\n    def __init__(self, *args, **kwargs):\n        self.eraser = T.RandomErasing(*args, **kwargs)\n\n    def __call__(self, img, target):\n        return self.eraser(img), target\n\n\nclass Normalize(object):\n    def __init__(self, mean, std):\n        self.mean = mean\n        self.std = std\n\n    def __call__(self, image, target=None):\n        image = F.normalize(image, mean=self.mean, std=self.std)\n        if target is None:\n            return image, None\n        target = target.copy()\n        h, w = image.shape[-2:]\n        if \"boxes\" in target:\n            boxes = target[\"boxes\"]\n            boxes = box_xyxy_to_cxcywh(boxes)\n            boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32)\n            target[\"boxes\"] = boxes\n        return image, target\n\n\nclass Compose(object):\n    def __init__(self, transforms):\n        self.transforms = transforms\n\n    def __call__(self, image, target):\n        for t in self.transforms:\n            image, target = t(image, target)\n        return image, target\n\n    def __repr__(self):\n        format_string = self.__class__.__name__ + \"(\"\n        for t in self.transforms:\n            format_string += \"\\n\"\n            format_string += \"    {0}\".format(t)\n        format_string += \"\\n)\"\n        return format_string\n"
  },
  {
    "path": "engine.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nTrain and eval functions used in main.py\n\"\"\"\nimport math\nimport os\nimport sys\nfrom typing import Iterable\n\nimport torch\n\nimport util.misc as utils\nfrom datasets.coco_eval import CocoEvaluator\nfrom datasets.panoptic_eval import PanopticEvaluator\n\n\ndef train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,\n                    data_loader: Iterable, optimizer: torch.optim.Optimizer,\n                    device: torch.device, epoch: int, max_norm: float = 0):\n    model.train()\n    criterion.train()\n    metric_logger = utils.MetricLogger(delimiter=\"  \")\n    metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}'))\n    metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}'))\n    header = 'Epoch: [{}]'.format(epoch)\n    print_freq = 10\n\n    for samples, targets in metric_logger.log_every(data_loader, print_freq, header):\n        samples = samples.to(device)\n        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\n        outputs = model(samples)\n        loss_dict = criterion(outputs, targets)\n        weight_dict = criterion.weight_dict\n        losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)\n\n        # reduce losses over all GPUs for logging purposes\n        loss_dict_reduced = utils.reduce_dict(loss_dict)\n        loss_dict_reduced_unscaled = {f'{k}_unscaled': v\n                                      for k, v in loss_dict_reduced.items()}\n        loss_dict_reduced_scaled = {k: v * weight_dict[k]\n                                    for k, v in loss_dict_reduced.items() if k in weight_dict}\n        losses_reduced_scaled = sum(loss_dict_reduced_scaled.values())\n\n        loss_value = losses_reduced_scaled.item()\n\n        if not math.isfinite(loss_value):\n            print(\"Loss is {}, stopping training\".format(loss_value))\n            print(loss_dict_reduced)\n            sys.exit(1)\n\n        optimizer.zero_grad()\n        losses.backward()\n        if max_norm > 0:\n            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)\n        optimizer.step()\n\n        metric_logger.update(loss=loss_value, **loss_dict_reduced_scaled, **loss_dict_reduced_unscaled)\n        metric_logger.update(class_error=loss_dict_reduced['class_error'])\n        metric_logger.update(lr=optimizer.param_groups[0][\"lr\"])\n    # gather the stats from all processes\n    metric_logger.synchronize_between_processes()\n    print(\"Averaged stats:\", metric_logger)\n    return {k: meter.global_avg for k, meter in metric_logger.meters.items()}\n\n\n@torch.no_grad()\ndef evaluate(model, criterion, postprocessors, data_loader, base_ds, device, output_dir):\n    model.eval()\n    criterion.eval()\n\n    metric_logger = utils.MetricLogger(delimiter=\"  \")\n    metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}'))\n    header = 'Test:'\n\n    iou_types = tuple(k for k in ('segm', 'bbox') if k in postprocessors.keys())\n    coco_evaluator = CocoEvaluator(base_ds, iou_types)\n    # coco_evaluator.coco_eval[iou_types[0]].params.iouThrs = [0, 0.1, 0.5, 0.75]\n\n    panoptic_evaluator = None\n    if 'panoptic' in postprocessors.keys():\n        panoptic_evaluator = PanopticEvaluator(\n            data_loader.dataset.ann_file,\n            data_loader.dataset.ann_folder,\n            output_dir=os.path.join(output_dir, \"panoptic_eval\"),\n        )\n\n    for samples, targets in metric_logger.log_every(data_loader, 10, header):\n        samples = samples.to(device)\n        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\n        outputs = model(samples)\n        loss_dict = criterion(outputs, targets)\n        weight_dict = criterion.weight_dict\n\n        # reduce losses over all GPUs for logging purposes\n        loss_dict_reduced = utils.reduce_dict(loss_dict)\n        loss_dict_reduced_scaled = {k: v * weight_dict[k]\n                                    for k, v in loss_dict_reduced.items() if k in weight_dict}\n        loss_dict_reduced_unscaled = {f'{k}_unscaled': v\n                                      for k, v in loss_dict_reduced.items()}\n        metric_logger.update(loss=sum(loss_dict_reduced_scaled.values()),\n                             **loss_dict_reduced_scaled,\n                             **loss_dict_reduced_unscaled)\n        metric_logger.update(class_error=loss_dict_reduced['class_error'])\n\n        orig_target_sizes = torch.stack([t[\"orig_size\"] for t in targets], dim=0)\n        results = postprocessors['bbox'](outputs, orig_target_sizes)\n        if 'segm' in postprocessors.keys():\n            target_sizes = torch.stack([t[\"size\"] for t in targets], dim=0)\n            results = postprocessors['segm'](results, outputs, orig_target_sizes, target_sizes)\n        res = {target['image_id'].item(): output for target, output in zip(targets, results)}\n        if coco_evaluator is not None:\n            coco_evaluator.update(res)\n\n        if panoptic_evaluator is not None:\n            res_pano = postprocessors[\"panoptic\"](outputs, target_sizes, orig_target_sizes)\n            for i, target in enumerate(targets):\n                image_id = target[\"image_id\"].item()\n                file_name = f\"{image_id:012d}.png\"\n                res_pano[i][\"image_id\"] = image_id\n                res_pano[i][\"file_name\"] = file_name\n\n            panoptic_evaluator.update(res_pano)\n\n    # gather the stats from all processes\n    metric_logger.synchronize_between_processes()\n    print(\"Averaged stats:\", metric_logger)\n    if coco_evaluator is not None:\n        coco_evaluator.synchronize_between_processes()\n    if panoptic_evaluator is not None:\n        panoptic_evaluator.synchronize_between_processes()\n\n    # accumulate predictions from all images\n    if coco_evaluator is not None:\n        coco_evaluator.accumulate()\n        coco_evaluator.summarize()\n    panoptic_res = None\n    if panoptic_evaluator is not None:\n        panoptic_res = panoptic_evaluator.summarize()\n    stats = {k: meter.global_avg for k, meter in metric_logger.meters.items()}\n    if coco_evaluator is not None:\n        if 'bbox' in postprocessors.keys():\n            stats['coco_eval_bbox'] = coco_evaluator.coco_eval['bbox'].stats.tolist()\n        if 'segm' in postprocessors.keys():\n            stats['coco_eval_masks'] = coco_evaluator.coco_eval['segm'].stats.tolist()\n    if panoptic_res is not None:\n        stats['PQ_all'] = panoptic_res[\"All\"]\n        stats['PQ_th'] = panoptic_res[\"Things\"]\n        stats['PQ_st'] = panoptic_res[\"Stuff\"]\n    return stats, coco_evaluator\n"
  },
  {
    "path": "hubconf.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport torch\n\nfrom models.backbone import Backbone, Joiner\nfrom models.detr import DETR, PostProcess\nfrom models.position_encoding import PositionEmbeddingSine\nfrom models.segmentation import DETRsegm, PostProcessPanoptic\nfrom models.transformer import Transformer\n\ndependencies = [\"torch\", \"torchvision\"]\n\n\ndef _make_detr(backbone_name: str, dilation=False, num_classes=91, mask=False):\n    hidden_dim = 256\n    backbone = Backbone(backbone_name, train_backbone=True, return_interm_layers=mask, dilation=dilation)\n    pos_enc = PositionEmbeddingSine(hidden_dim // 2, normalize=True)\n    backbone_with_pos_enc = Joiner(backbone, pos_enc)\n    backbone_with_pos_enc.num_channels = backbone.num_channels\n    transformer = Transformer(d_model=hidden_dim, return_intermediate_dec=True)\n    detr = DETR(backbone_with_pos_enc, transformer, num_classes=num_classes, num_queries=100)\n    if mask:\n        return DETRsegm(detr)\n    return detr\n\n\ndef detr_resnet50(pretrained=False, num_classes=91, return_postprocessor=False):\n    \"\"\"\n    DETR R50 with 6 encoder and 6 decoder layers.\n\n    Achieves 42/62.4 AP/AP50 on COCO val5k.\n    \"\"\"\n    model = _make_detr(\"resnet50\", dilation=False, num_classes=num_classes)\n    if pretrained:\n        checkpoint = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth\", map_location=\"cpu\", check_hash=True\n        )\n        model.load_state_dict(checkpoint[\"model\"])\n    if return_postprocessor:\n        return model, PostProcess()\n    return model\n\n\ndef detr_resnet50_dc5(pretrained=False, num_classes=91, return_postprocessor=False):\n    \"\"\"\n    DETR-DC5 R50 with 6 encoder and 6 decoder layers.\n\n    The last block of ResNet-50 has dilation to increase\n    output resolution.\n    Achieves 43.3/63.1 AP/AP50 on COCO val5k.\n    \"\"\"\n    model = _make_detr(\"resnet50\", dilation=True, num_classes=num_classes)\n    if pretrained:\n        checkpoint = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/detr/detr-r50-dc5-f0fb7ef5.pth\", map_location=\"cpu\", check_hash=True\n        )\n        model.load_state_dict(checkpoint[\"model\"])\n    if return_postprocessor:\n        return model, PostProcess()\n    return model\n\n\ndef detr_resnet101(pretrained=False, num_classes=91, return_postprocessor=False):\n    \"\"\"\n    DETR-DC5 R101 with 6 encoder and 6 decoder layers.\n\n    Achieves 43.5/63.8 AP/AP50 on COCO val5k.\n    \"\"\"\n    model = _make_detr(\"resnet101\", dilation=False, num_classes=num_classes)\n    if pretrained:\n        checkpoint = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/detr/detr-r101-2c7b67e5.pth\", map_location=\"cpu\", check_hash=True\n        )\n        model.load_state_dict(checkpoint[\"model\"])\n    if return_postprocessor:\n        return model, PostProcess()\n    return model\n\n\ndef detr_resnet101_dc5(pretrained=False, num_classes=91, return_postprocessor=False):\n    \"\"\"\n    DETR-DC5 R101 with 6 encoder and 6 decoder layers.\n\n    The last block of ResNet-101 has dilation to increase\n    output resolution.\n    Achieves 44.9/64.7 AP/AP50 on COCO val5k.\n    \"\"\"\n    model = _make_detr(\"resnet101\", dilation=True, num_classes=num_classes)\n    if pretrained:\n        checkpoint = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/detr/detr-r101-dc5-a2e86def.pth\", map_location=\"cpu\", check_hash=True\n        )\n        model.load_state_dict(checkpoint[\"model\"])\n    if return_postprocessor:\n        return model, PostProcess()\n    return model\n\n\ndef detr_resnet50_panoptic(\n    pretrained=False, num_classes=250, threshold=0.85, return_postprocessor=False\n):\n    \"\"\"\n    DETR R50 with 6 encoder and 6 decoder layers.\n    Achieves 43.4 PQ on COCO val5k.\n\n   threshold is the minimum confidence required for keeping segments in the prediction\n    \"\"\"\n    model = _make_detr(\"resnet50\", dilation=False, num_classes=num_classes, mask=True)\n    is_thing_map = {i: i <= 90 for i in range(250)}\n    if pretrained:\n        checkpoint = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/detr/detr-r50-panoptic-00ce5173.pth\",\n            map_location=\"cpu\",\n            check_hash=True,\n        )\n        model.load_state_dict(checkpoint[\"model\"])\n    if return_postprocessor:\n        return model, PostProcessPanoptic(is_thing_map, threshold=threshold)\n    return model\n\n\ndef detr_resnet50_dc5_panoptic(\n    pretrained=False, num_classes=250, threshold=0.85, return_postprocessor=False\n):\n    \"\"\"\n    DETR-DC5 R50 with 6 encoder and 6 decoder layers.\n\n    The last block of ResNet-50 has dilation to increase\n    output resolution.\n    Achieves 44.6 on COCO val5k.\n\n   threshold is the minimum confidence required for keeping segments in the prediction\n    \"\"\"\n    model = _make_detr(\"resnet50\", dilation=True, num_classes=num_classes, mask=True)\n    is_thing_map = {i: i <= 90 for i in range(250)}\n    if pretrained:\n        checkpoint = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/detr/detr-r50-dc5-panoptic-da08f1b1.pth\",\n            map_location=\"cpu\",\n            check_hash=True,\n        )\n        model.load_state_dict(checkpoint[\"model\"])\n    if return_postprocessor:\n        return model, PostProcessPanoptic(is_thing_map, threshold=threshold)\n    return model\n\n\ndef detr_resnet101_panoptic(\n    pretrained=False, num_classes=250, threshold=0.85, return_postprocessor=False\n):\n    \"\"\"\n    DETR-DC5 R101 with 6 encoder and 6 decoder layers.\n\n    Achieves 45.1 PQ on COCO val5k.\n\n   threshold is the minimum confidence required for keeping segments in the prediction\n    \"\"\"\n    model = _make_detr(\"resnet101\", dilation=False, num_classes=num_classes, mask=True)\n    is_thing_map = {i: i <= 90 for i in range(250)}\n    if pretrained:\n        checkpoint = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/detr/detr-r101-panoptic-40021d53.pth\",\n            map_location=\"cpu\",\n            check_hash=True,\n        )\n        model.load_state_dict(checkpoint[\"model\"])\n    if return_postprocessor:\n        return model, PostProcessPanoptic(is_thing_map, threshold=threshold)\n    return model\n"
  },
  {
    "path": "main.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport argparse\nimport datetime\nimport json\nimport random\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader, DistributedSampler\n\nimport datasets\nimport util.misc as utils\nfrom datasets import build_dataset, get_coco_api_from_dataset\nfrom engine import evaluate, train_one_epoch\nfrom models import build_model\n\n\ndef get_args_parser():\n    parser = argparse.ArgumentParser('Set transformer detector', add_help=False)\n    parser.add_argument('--lr', default=1e-4, type=float)\n    parser.add_argument('--lr_backbone', default=1e-5, type=float)\n    parser.add_argument('--batch_size', default=2, type=int)\n    parser.add_argument('--weight_decay', default=1e-4, type=float)\n    parser.add_argument('--epochs', default=300, type=int)\n    parser.add_argument('--lr_drop', default=200, type=int)\n    parser.add_argument('--clip_max_norm', default=0.1, type=float,\n                        help='gradient clipping max norm')\n\n    # Model parameters\n    parser.add_argument('--frozen_weights', type=str, default=None,\n                        help=\"Path to the pretrained model. If set, only the mask head will be trained\")\n    # * Backbone\n    parser.add_argument('--backbone', default='resnet50', type=str,\n                        help=\"Name of the convolutional backbone to use\")\n    parser.add_argument('--dilation', action='store_true',\n                        help=\"If true, we replace stride with dilation in the last convolutional block (DC5)\")\n    parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'),\n                        help=\"Type of positional embedding to use on top of the image features\")\n\n    # * Transformer\n    parser.add_argument('--enc_layers', default=6, type=int,\n                        help=\"Number of encoding layers in the transformer\")\n    parser.add_argument('--dec_layers', default=6, type=int,\n                        help=\"Number of decoding layers in the transformer\")\n    parser.add_argument('--dim_feedforward', default=2048, type=int,\n                        help=\"Intermediate size of the feedforward layers in the transformer blocks\")\n    parser.add_argument('--hidden_dim', default=256, type=int,\n                        help=\"Size of the embeddings (dimension of the transformer)\")\n    parser.add_argument('--dropout', default=0.1, type=float,\n                        help=\"Dropout applied in the transformer\")\n    parser.add_argument('--nheads', default=8, type=int,\n                        help=\"Number of attention heads inside the transformer's attentions\")\n    parser.add_argument('--num_queries', default=100, type=int,\n                        help=\"Number of query slots\")\n    parser.add_argument('--pre_norm', action='store_true')\n\n    # * Segmentation\n    parser.add_argument('--masks', action='store_true',\n                        help=\"Train segmentation head if the flag is provided\")\n\n    # Loss\n    parser.add_argument('--no_aux_loss', dest='aux_loss', action='store_false',\n                        help=\"Disables auxiliary decoding losses (loss at each layer)\")\n    # * Matcher\n    parser.add_argument('--set_cost_class', default=1, type=float,\n                        help=\"Class coefficient in the matching cost\")\n    parser.add_argument('--set_cost_bbox', default=5, type=float,\n                        help=\"L1 box coefficient in the matching cost\")\n    parser.add_argument('--set_cost_giou', default=2, type=float,\n                        help=\"giou box coefficient in the matching cost\")\n    # * Loss coefficients\n    parser.add_argument('--mask_loss_coef', default=1, type=float)\n    parser.add_argument('--dice_loss_coef', default=1, type=float)\n    parser.add_argument('--bbox_loss_coef', default=5, type=float)\n    parser.add_argument('--giou_loss_coef', default=2, type=float)\n    parser.add_argument('--eos_coef', default=0.1, type=float,\n                        help=\"Relative classification weight of the no-object class\")\n\n    # dataset parameters\n    parser.add_argument('--dataset_file', default='coco')\n    parser.add_argument('--coco_path', type=str)\n    parser.add_argument('--coco_panoptic_path', type=str)\n    parser.add_argument('--remove_difficult', action='store_true')\n\n    parser.add_argument('--output_dir', default='',\n                        help='path where to save, empty for no saving')\n    parser.add_argument('--device', default='cuda',\n                        help='device to use for training / testing')\n    parser.add_argument('--seed', default=42, type=int)\n    parser.add_argument('--resume', default='', help='resume from checkpoint')\n    parser.add_argument('--start_epoch', default=0, type=int, metavar='N',\n                        help='start epoch')\n    parser.add_argument('--eval', action='store_true')\n    parser.add_argument('--num_workers', default=2, type=int)\n\n    # distributed training parameters\n    parser.add_argument('--world_size', default=1, type=int,\n                        help='number of distributed processes')\n    parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')\n    return parser\n\n\ndef main(args):\n    utils.init_distributed_mode(args)\n    print(\"git:\\n  {}\\n\".format(utils.get_sha()))\n\n    if args.frozen_weights is not None:\n        assert args.masks, \"Frozen training is meant for segmentation only\"\n    print(args)\n\n    device = torch.device(args.device)\n\n    # fix the seed for reproducibility\n    seed = args.seed + utils.get_rank()\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n\n    model, criterion, postprocessors = build_model(args)\n    model.to(device)\n\n    model_without_ddp = model\n    if args.distributed:\n        model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])\n        model_without_ddp = model.module\n    n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n    print('number of params:', n_parameters)\n\n    param_dicts = [\n        {\"params\": [p for n, p in model_without_ddp.named_parameters() if \"backbone\" not in n and p.requires_grad]},\n        {\n            \"params\": [p for n, p in model_without_ddp.named_parameters() if \"backbone\" in n and p.requires_grad],\n            \"lr\": args.lr_backbone,\n        },\n    ]\n    optimizer = torch.optim.AdamW(param_dicts, lr=args.lr,\n                                  weight_decay=args.weight_decay)\n    lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, args.lr_drop)\n\n    dataset_train = build_dataset(image_set='train', args=args)\n    dataset_val = build_dataset(image_set='val', args=args)\n\n    if args.distributed:\n        sampler_train = DistributedSampler(dataset_train)\n        sampler_val = DistributedSampler(dataset_val, shuffle=False)\n    else:\n        sampler_train = torch.utils.data.RandomSampler(dataset_train)\n        sampler_val = torch.utils.data.SequentialSampler(dataset_val)\n\n    batch_sampler_train = torch.utils.data.BatchSampler(\n        sampler_train, args.batch_size, drop_last=True)\n\n    data_loader_train = DataLoader(dataset_train, batch_sampler=batch_sampler_train,\n                                   collate_fn=utils.collate_fn, num_workers=args.num_workers)\n    data_loader_val = DataLoader(dataset_val, args.batch_size, sampler=sampler_val,\n                                 drop_last=False, collate_fn=utils.collate_fn, num_workers=args.num_workers)\n\n    if args.dataset_file == \"coco_panoptic\":\n        # We also evaluate AP during panoptic training, on original coco DS\n        coco_val = datasets.coco.build(\"val\", args)\n        base_ds = get_coco_api_from_dataset(coco_val)\n    else:\n        base_ds = get_coco_api_from_dataset(dataset_val)\n\n    if args.frozen_weights is not None:\n        checkpoint = torch.load(args.frozen_weights, map_location='cpu')\n        model_without_ddp.detr.load_state_dict(checkpoint['model'])\n\n    output_dir = Path(args.output_dir)\n    if args.resume:\n        if args.resume.startswith('https'):\n            checkpoint = torch.hub.load_state_dict_from_url(\n                args.resume, map_location='cpu', check_hash=True)\n        else:\n            checkpoint = torch.load(args.resume, map_location='cpu')\n        model_without_ddp.load_state_dict(checkpoint['model'])\n        if not args.eval and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint:\n            optimizer.load_state_dict(checkpoint['optimizer'])\n            lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n            args.start_epoch = checkpoint['epoch'] + 1\n\n    if args.eval:\n        test_stats, coco_evaluator = evaluate(model, criterion, postprocessors,\n                                              data_loader_val, base_ds, device, args.output_dir)\n        if args.output_dir:\n            utils.save_on_master(coco_evaluator.coco_eval[\"bbox\"].eval, output_dir / \"eval.pth\")\n        return\n\n    print(\"Start training\")\n    start_time = time.time()\n    for epoch in range(args.start_epoch, args.epochs):\n        if args.distributed:\n            sampler_train.set_epoch(epoch)\n        train_stats = train_one_epoch(\n            model, criterion, data_loader_train, optimizer, device, epoch,\n            args.clip_max_norm)\n        lr_scheduler.step()\n        if args.output_dir:\n            checkpoint_paths = [output_dir / 'checkpoint.pth']\n            # extra checkpoint before LR drop and every 100 epochs\n            if (epoch + 1) % args.lr_drop == 0 or (epoch + 1) % 100 == 0:\n                checkpoint_paths.append(output_dir / f'checkpoint{epoch:04}.pth')\n            for checkpoint_path in checkpoint_paths:\n                utils.save_on_master({\n                    'model': model_without_ddp.state_dict(),\n                    'optimizer': optimizer.state_dict(),\n                    'lr_scheduler': lr_scheduler.state_dict(),\n                    'epoch': epoch,\n                    'args': args,\n                }, checkpoint_path)\n\n        test_stats, coco_evaluator = evaluate(\n            model, criterion, postprocessors, data_loader_val, base_ds, device, args.output_dir\n        )\n\n        log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},\n                     **{f'test_{k}': v for k, v in test_stats.items()},\n                     'epoch': epoch,\n                     'n_parameters': n_parameters}\n\n        if args.output_dir and utils.is_main_process():\n            with (output_dir / \"log.txt\").open(\"a\") as f:\n                f.write(json.dumps(log_stats) + \"\\n\")\n\n            # for evaluation logs\n            if coco_evaluator is not None:\n                (output_dir / 'eval').mkdir(exist_ok=True)\n                if \"bbox\" in coco_evaluator.coco_eval:\n                    filenames = ['latest.pth']\n                    if epoch % 50 == 0:\n                        filenames.append(f'{epoch:03}.pth')\n                    for name in filenames:\n                        torch.save(coco_evaluator.coco_eval[\"bbox\"].eval,\n                                   output_dir / \"eval\" / name)\n\n    total_time = time.time() - start_time\n    total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n    print('Training time {}'.format(total_time_str))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('DETR training and evaluation script', parents=[get_args_parser()])\n    args = parser.parse_args()\n    if args.output_dir:\n        Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n    main(args)\n"
  },
  {
    "path": "models/__init__.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nfrom .detr import build\n\n\ndef build_model(args):\n    return build(args)\n"
  },
  {
    "path": "models/backbone.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nBackbone modules.\n\"\"\"\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn.functional as F\nimport torchvision\nfrom torch import nn\nfrom torchvision.models._utils import IntermediateLayerGetter\nfrom typing import Dict, List\n\nfrom util.misc import NestedTensor, is_main_process\n\nfrom .position_encoding import build_position_encoding\n\n\nclass FrozenBatchNorm2d(torch.nn.Module):\n    \"\"\"\n    BatchNorm2d where the batch statistics and the affine parameters are fixed.\n\n    Copy-paste from torchvision.misc.ops with added eps before rqsrt,\n    without which any other models than torchvision.models.resnet[18,34,50,101]\n    produce nans.\n    \"\"\"\n\n    def __init__(self, n):\n        super(FrozenBatchNorm2d, self).__init__()\n        self.register_buffer(\"weight\", torch.ones(n))\n        self.register_buffer(\"bias\", torch.zeros(n))\n        self.register_buffer(\"running_mean\", torch.zeros(n))\n        self.register_buffer(\"running_var\", torch.ones(n))\n\n    def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,\n                              missing_keys, unexpected_keys, error_msgs):\n        num_batches_tracked_key = prefix + 'num_batches_tracked'\n        if num_batches_tracked_key in state_dict:\n            del state_dict[num_batches_tracked_key]\n\n        super(FrozenBatchNorm2d, self)._load_from_state_dict(\n            state_dict, prefix, local_metadata, strict,\n            missing_keys, unexpected_keys, error_msgs)\n\n    def forward(self, x):\n        # move reshapes to the beginning\n        # to make it fuser-friendly\n        w = self.weight.reshape(1, -1, 1, 1)\n        b = self.bias.reshape(1, -1, 1, 1)\n        rv = self.running_var.reshape(1, -1, 1, 1)\n        rm = self.running_mean.reshape(1, -1, 1, 1)\n        eps = 1e-5\n        scale = w * (rv + eps).rsqrt()\n        bias = b - rm * scale\n        return x * scale + bias\n\n\nclass BackboneBase(nn.Module):\n\n    def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool):\n        super().__init__()\n        for name, parameter in backbone.named_parameters():\n            if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:\n                parameter.requires_grad_(False)\n        if return_interm_layers:\n            return_layers = {\"layer1\": \"0\", \"layer2\": \"1\", \"layer3\": \"2\", \"layer4\": \"3\"}\n        else:\n            return_layers = {'layer4': \"0\"}\n        self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)\n        self.num_channels = num_channels\n\n    def forward(self, tensor_list: NestedTensor):\n        xs = self.body(tensor_list.tensors)\n        out: Dict[str, NestedTensor] = {}\n        for name, x in xs.items():\n            m = tensor_list.mask\n            assert m is not None\n            mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0]\n            out[name] = NestedTensor(x, mask)\n        return out\n\n\nclass Backbone(BackboneBase):\n    \"\"\"ResNet backbone with frozen BatchNorm.\"\"\"\n    def __init__(self, name: str,\n                 train_backbone: bool,\n                 return_interm_layers: bool,\n                 dilation: bool):\n        backbone = getattr(torchvision.models, name)(\n            replace_stride_with_dilation=[False, False, dilation],\n            pretrained=is_main_process(), norm_layer=FrozenBatchNorm2d)\n        num_channels = 512 if name in ('resnet18', 'resnet34') else 2048\n        super().__init__(backbone, train_backbone, num_channels, return_interm_layers)\n\n\nclass Joiner(nn.Sequential):\n    def __init__(self, backbone, position_embedding):\n        super().__init__(backbone, position_embedding)\n\n    def forward(self, tensor_list: NestedTensor):\n        xs = self[0](tensor_list)\n        out: List[NestedTensor] = []\n        pos = []\n        for name, x in xs.items():\n            out.append(x)\n            # position encoding\n            pos.append(self[1](x).to(x.tensors.dtype))\n\n        return out, pos\n\n\ndef build_backbone(args):\n    position_embedding = build_position_encoding(args)\n    train_backbone = args.lr_backbone > 0\n    return_interm_layers = args.masks\n    backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation)\n    model = Joiner(backbone, position_embedding)\n    model.num_channels = backbone.num_channels\n    return model\n"
  },
  {
    "path": "models/detr.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nDETR model and criterion classes.\n\"\"\"\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom util import box_ops\nfrom util.misc import (NestedTensor, nested_tensor_from_tensor_list,\n                       accuracy, get_world_size, interpolate,\n                       is_dist_avail_and_initialized)\n\nfrom .backbone import build_backbone\nfrom .matcher import build_matcher\nfrom .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm,\n                           dice_loss, sigmoid_focal_loss)\nfrom .transformer import build_transformer\n\n\nclass DETR(nn.Module):\n    \"\"\" This is the DETR module that performs object detection \"\"\"\n    def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False):\n        \"\"\" Initializes the model.\n        Parameters:\n            backbone: torch module of the backbone to be used. See backbone.py\n            transformer: torch module of the transformer architecture. See transformer.py\n            num_classes: number of object classes\n            num_queries: number of object queries, ie detection slot. This is the maximal number of objects\n                         DETR can detect in a single image. For COCO, we recommend 100 queries.\n            aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.\n        \"\"\"\n        super().__init__()\n        self.num_queries = num_queries\n        self.transformer = transformer\n        hidden_dim = transformer.d_model\n        self.class_embed = nn.Linear(hidden_dim, num_classes + 1)\n        self.bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)\n        self.query_embed = nn.Embedding(num_queries, hidden_dim)\n        self.input_proj = nn.Conv2d(backbone.num_channels, hidden_dim, kernel_size=1)\n        self.backbone = backbone\n        self.aux_loss = aux_loss\n\n    def forward(self, samples: NestedTensor):\n        \"\"\" The forward expects a NestedTensor, which consists of:\n               - samples.tensor: batched images, of shape [batch_size x 3 x H x W]\n               - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels\n\n            It returns a dict with the following elements:\n               - \"pred_logits\": the classification logits (including no-object) for all queries.\n                                Shape= [batch_size x num_queries x (num_classes + 1)]\n               - \"pred_boxes\": The normalized boxes coordinates for all queries, represented as\n                               (center_x, center_y, height, width). These values are normalized in [0, 1],\n                               relative to the size of each individual image (disregarding possible padding).\n                               See PostProcess for information on how to retrieve the unnormalized bounding box.\n               - \"aux_outputs\": Optional, only returned when auxilary losses are activated. It is a list of\n                                dictionnaries containing the two above keys for each decoder layer.\n        \"\"\"\n        if isinstance(samples, (list, torch.Tensor)):\n            samples = nested_tensor_from_tensor_list(samples)\n        features, pos = self.backbone(samples)\n\n        src, mask = features[-1].decompose()\n        assert mask is not None\n        hs = self.transformer(self.input_proj(src), mask, self.query_embed.weight, pos[-1])[0]\n\n        outputs_class = self.class_embed(hs)\n        outputs_coord = self.bbox_embed(hs).sigmoid()\n        out = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1]}\n        if self.aux_loss:\n            out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord)\n        return out\n\n    @torch.jit.unused\n    def _set_aux_loss(self, outputs_class, outputs_coord):\n        # this is a workaround to make torchscript happy, as torchscript\n        # doesn't support dictionary with non-homogeneous values, such\n        # as a dict having both a Tensor and a list.\n        return [{'pred_logits': a, 'pred_boxes': b}\n                for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]\n\n\nclass SetCriterion(nn.Module):\n    \"\"\" This class computes the loss for DETR.\n    The process happens in two steps:\n        1) we compute hungarian assignment between ground truth boxes and the outputs of the model\n        2) we supervise each pair of matched ground-truth / prediction (supervise class and box)\n    \"\"\"\n    def __init__(self, num_classes, matcher, weight_dict, eos_coef, losses):\n        \"\"\" Create the criterion.\n        Parameters:\n            num_classes: number of object categories, omitting the special no-object category\n            matcher: module able to compute a matching between targets and proposals\n            weight_dict: dict containing as key the names of the losses and as values their relative weight.\n            eos_coef: relative classification weight applied to the no-object category\n            losses: list of all the losses to be applied. See get_loss for list of available losses.\n        \"\"\"\n        super().__init__()\n        self.num_classes = num_classes\n        self.matcher = matcher\n        self.weight_dict = weight_dict\n        self.eos_coef = eos_coef\n        self.losses = losses\n        empty_weight = torch.ones(self.num_classes + 1)\n        empty_weight[-1] = self.eos_coef\n        self.register_buffer('empty_weight', empty_weight)\n\n    def loss_labels(self, outputs, targets, indices, num_boxes, log=True):\n        \"\"\"Classification loss (NLL)\n        targets dicts must contain the key \"labels\" containing a tensor of dim [nb_target_boxes]\n        \"\"\"\n        assert 'pred_logits' in outputs\n        src_logits = outputs['pred_logits']\n\n        idx = self._get_src_permutation_idx(indices)\n        target_classes_o = torch.cat([t[\"labels\"][J] for t, (_, J) in zip(targets, indices)])\n        target_classes = torch.full(src_logits.shape[:2], self.num_classes,\n                                    dtype=torch.int64, device=src_logits.device)\n        target_classes[idx] = target_classes_o\n\n        loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight)\n        losses = {'loss_ce': loss_ce}\n\n        if log:\n            # TODO this should probably be a separate loss, not hacked in this one here\n            losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0]\n        return losses\n\n    @torch.no_grad()\n    def loss_cardinality(self, outputs, targets, indices, num_boxes):\n        \"\"\" Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes\n        This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients\n        \"\"\"\n        pred_logits = outputs['pred_logits']\n        device = pred_logits.device\n        tgt_lengths = torch.as_tensor([len(v[\"labels\"]) for v in targets], device=device)\n        # Count the number of predictions that are NOT \"no-object\" (which is the last class)\n        card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1)\n        card_err = F.l1_loss(card_pred.float(), tgt_lengths.float())\n        losses = {'cardinality_error': card_err}\n        return losses\n\n    def loss_boxes(self, outputs, targets, indices, num_boxes):\n        \"\"\"Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss\n           targets dicts must contain the key \"boxes\" containing a tensor of dim [nb_target_boxes, 4]\n           The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size.\n        \"\"\"\n        assert 'pred_boxes' in outputs\n        idx = self._get_src_permutation_idx(indices)\n        src_boxes = outputs['pred_boxes'][idx]\n        target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)\n\n        loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')\n\n        losses = {}\n        losses['loss_bbox'] = loss_bbox.sum() / num_boxes\n\n        loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(\n            box_ops.box_cxcywh_to_xyxy(src_boxes),\n            box_ops.box_cxcywh_to_xyxy(target_boxes)))\n        losses['loss_giou'] = loss_giou.sum() / num_boxes\n        return losses\n\n    def loss_masks(self, outputs, targets, indices, num_boxes):\n        \"\"\"Compute the losses related to the masks: the focal loss and the dice loss.\n           targets dicts must contain the key \"masks\" containing a tensor of dim [nb_target_boxes, h, w]\n        \"\"\"\n        assert \"pred_masks\" in outputs\n\n        src_idx = self._get_src_permutation_idx(indices)\n        tgt_idx = self._get_tgt_permutation_idx(indices)\n        src_masks = outputs[\"pred_masks\"]\n        src_masks = src_masks[src_idx]\n        masks = [t[\"masks\"] for t in targets]\n        # TODO use valid to mask invalid areas due to padding in loss\n        target_masks, valid = nested_tensor_from_tensor_list(masks).decompose()\n        target_masks = target_masks.to(src_masks)\n        target_masks = target_masks[tgt_idx]\n\n        # upsample predictions to the target size\n        src_masks = interpolate(src_masks[:, None], size=target_masks.shape[-2:],\n                                mode=\"bilinear\", align_corners=False)\n        src_masks = src_masks[:, 0].flatten(1)\n\n        target_masks = target_masks.flatten(1)\n        target_masks = target_masks.view(src_masks.shape)\n        losses = {\n            \"loss_mask\": sigmoid_focal_loss(src_masks, target_masks, num_boxes),\n            \"loss_dice\": dice_loss(src_masks, target_masks, num_boxes),\n        }\n        return losses\n\n    def _get_src_permutation_idx(self, indices):\n        # permute predictions following indices\n        batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])\n        src_idx = torch.cat([src for (src, _) in indices])\n        return batch_idx, src_idx\n\n    def _get_tgt_permutation_idx(self, indices):\n        # permute targets following indices\n        batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])\n        tgt_idx = torch.cat([tgt for (_, tgt) in indices])\n        return batch_idx, tgt_idx\n\n    def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):\n        loss_map = {\n            'labels': self.loss_labels,\n            'cardinality': self.loss_cardinality,\n            'boxes': self.loss_boxes,\n            'masks': self.loss_masks\n        }\n        assert loss in loss_map, f'do you really want to compute {loss} loss?'\n        return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)\n\n    def forward(self, outputs, targets):\n        \"\"\" This performs the loss computation.\n        Parameters:\n             outputs: dict of tensors, see the output specification of the model for the format\n             targets: list of dicts, such that len(targets) == batch_size.\n                      The expected keys in each dict depends on the losses applied, see each loss' doc\n        \"\"\"\n        outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'}\n\n        # Retrieve the matching between the outputs of the last layer and the targets\n        indices = self.matcher(outputs_without_aux, targets)\n\n        # Compute the average number of target boxes accross all nodes, for normalization purposes\n        num_boxes = sum(len(t[\"labels\"]) for t in targets)\n        num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)\n        if is_dist_avail_and_initialized():\n            torch.distributed.all_reduce(num_boxes)\n        num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()\n\n        # Compute all the requested losses\n        losses = {}\n        for loss in self.losses:\n            losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))\n\n        # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.\n        if 'aux_outputs' in outputs:\n            for i, aux_outputs in enumerate(outputs['aux_outputs']):\n                indices = self.matcher(aux_outputs, targets)\n                for loss in self.losses:\n                    if loss == 'masks':\n                        # Intermediate masks losses are too costly to compute, we ignore them.\n                        continue\n                    kwargs = {}\n                    if loss == 'labels':\n                        # Logging is enabled only for the last layer\n                        kwargs = {'log': False}\n                    l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs)\n                    l_dict = {k + f'_{i}': v for k, v in l_dict.items()}\n                    losses.update(l_dict)\n\n        return losses\n\n\nclass PostProcess(nn.Module):\n    \"\"\" This module converts the model's output into the format expected by the coco api\"\"\"\n    @torch.no_grad()\n    def forward(self, outputs, target_sizes):\n        \"\"\" Perform the computation\n        Parameters:\n            outputs: raw outputs of the model\n            target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch\n                          For evaluation, this must be the original image size (before any data augmentation)\n                          For visualization, this should be the image size after data augment, but before padding\n        \"\"\"\n        out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes']\n\n        assert len(out_logits) == len(target_sizes)\n        assert target_sizes.shape[1] == 2\n\n        prob = F.softmax(out_logits, -1)\n        scores, labels = prob[..., :-1].max(-1)\n\n        # convert to [x0, y0, x1, y1] format\n        boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)\n        # and from relative [0, 1] to absolute [0, height] coordinates\n        img_h, img_w = target_sizes.unbind(1)\n        scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)\n        boxes = boxes * scale_fct[:, None, :]\n\n        results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)]\n\n        return results\n\n\nclass MLP(nn.Module):\n    \"\"\" Very simple multi-layer perceptron (also called FFN)\"\"\"\n\n    def __init__(self, input_dim, hidden_dim, output_dim, num_layers):\n        super().__init__()\n        self.num_layers = num_layers\n        h = [hidden_dim] * (num_layers - 1)\n        self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))\n\n    def forward(self, x):\n        for i, layer in enumerate(self.layers):\n            x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)\n        return x\n\n\ndef build(args):\n    # the `num_classes` naming here is somewhat misleading.\n    # it indeed corresponds to `max_obj_id + 1`, where max_obj_id\n    # is the maximum id for a class in your dataset. For example,\n    # COCO has a max_obj_id of 90, so we pass `num_classes` to be 91.\n    # As another example, for a dataset that has a single class with id 1,\n    # you should pass `num_classes` to be 2 (max_obj_id + 1).\n    # For more details on this, check the following discussion\n    # https://github.com/facebookresearch/detr/issues/108#issuecomment-650269223\n    num_classes = 20 if args.dataset_file != 'coco' else 91\n    if args.dataset_file == \"coco_panoptic\":\n        # for panoptic, we just add a num_classes that is large enough to hold\n        # max_obj_id + 1, but the exact value doesn't really matter\n        num_classes = 250\n    device = torch.device(args.device)\n\n    backbone = build_backbone(args)\n\n    transformer = build_transformer(args)\n\n    model = DETR(\n        backbone,\n        transformer,\n        num_classes=num_classes,\n        num_queries=args.num_queries,\n        aux_loss=args.aux_loss,\n    )\n    if args.masks:\n        model = DETRsegm(model, freeze_detr=(args.frozen_weights is not None))\n    matcher = build_matcher(args)\n    weight_dict = {'loss_ce': 1, 'loss_bbox': args.bbox_loss_coef}\n    weight_dict['loss_giou'] = args.giou_loss_coef\n    if args.masks:\n        weight_dict[\"loss_mask\"] = args.mask_loss_coef\n        weight_dict[\"loss_dice\"] = args.dice_loss_coef\n    # TODO this is a hack\n    if args.aux_loss:\n        aux_weight_dict = {}\n        for i in range(args.dec_layers - 1):\n            aux_weight_dict.update({k + f'_{i}': v for k, v in weight_dict.items()})\n        weight_dict.update(aux_weight_dict)\n\n    losses = ['labels', 'boxes', 'cardinality']\n    if args.masks:\n        losses += [\"masks\"]\n    criterion = SetCriterion(num_classes, matcher=matcher, weight_dict=weight_dict,\n                             eos_coef=args.eos_coef, losses=losses)\n    criterion.to(device)\n    postprocessors = {'bbox': PostProcess()}\n    if args.masks:\n        postprocessors['segm'] = PostProcessSegm()\n        if args.dataset_file == \"coco_panoptic\":\n            is_thing_map = {i: i <= 90 for i in range(201)}\n            postprocessors[\"panoptic\"] = PostProcessPanoptic(is_thing_map, threshold=0.85)\n\n    return model, criterion, postprocessors\n"
  },
  {
    "path": "models/matcher.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nModules to compute the matching cost and solve the corresponding LSAP.\n\"\"\"\nimport torch\nfrom scipy.optimize import linear_sum_assignment\nfrom torch import nn\n\nfrom util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou\n\n\nclass HungarianMatcher(nn.Module):\n    \"\"\"This class computes an assignment between the targets and the predictions of the network\n\n    For efficiency reasons, the targets don't include the no_object. Because of this, in general,\n    there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,\n    while the others are un-matched (and thus treated as non-objects).\n    \"\"\"\n\n    def __init__(self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1):\n        \"\"\"Creates the matcher\n\n        Params:\n            cost_class: This is the relative weight of the classification error in the matching cost\n            cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost\n            cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost\n        \"\"\"\n        super().__init__()\n        self.cost_class = cost_class\n        self.cost_bbox = cost_bbox\n        self.cost_giou = cost_giou\n        assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, \"all costs cant be 0\"\n\n    @torch.no_grad()\n    def forward(self, outputs, targets):\n        \"\"\" Performs the matching\n\n        Params:\n            outputs: This is a dict that contains at least these entries:\n                 \"pred_logits\": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits\n                 \"pred_boxes\": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates\n\n            targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:\n                 \"labels\": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth\n                           objects in the target) containing the class labels\n                 \"boxes\": Tensor of dim [num_target_boxes, 4] containing the target box coordinates\n\n        Returns:\n            A list of size batch_size, containing tuples of (index_i, index_j) where:\n                - index_i is the indices of the selected predictions (in order)\n                - index_j is the indices of the corresponding selected targets (in order)\n            For each batch element, it holds:\n                len(index_i) = len(index_j) = min(num_queries, num_target_boxes)\n        \"\"\"\n        bs, num_queries = outputs[\"pred_logits\"].shape[:2]\n\n        # We flatten to compute the cost matrices in a batch\n        out_prob = outputs[\"pred_logits\"].flatten(0, 1).softmax(-1)  # [batch_size * num_queries, num_classes]\n        out_bbox = outputs[\"pred_boxes\"].flatten(0, 1)  # [batch_size * num_queries, 4]\n\n        # Also concat the target labels and boxes\n        tgt_ids = torch.cat([v[\"labels\"] for v in targets])\n        tgt_bbox = torch.cat([v[\"boxes\"] for v in targets])\n\n        # Compute the classification cost. Contrary to the loss, we don't use the NLL,\n        # but approximate it in 1 - proba[target class].\n        # The 1 is a constant that doesn't change the matching, it can be ommitted.\n        cost_class = -out_prob[:, tgt_ids]\n\n        # Compute the L1 cost between boxes\n        cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)\n\n        # Compute the giou cost betwen boxes\n        cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))\n\n        # Final cost matrix\n        C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou\n        C = C.view(bs, num_queries, -1).cpu()\n\n        sizes = [len(v[\"boxes\"]) for v in targets]\n        indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]\n        return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]\n\n\ndef build_matcher(args):\n    return HungarianMatcher(cost_class=args.set_cost_class, cost_bbox=args.set_cost_bbox, cost_giou=args.set_cost_giou)\n"
  },
  {
    "path": "models/position_encoding.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nVarious positional encodings for the transformer.\n\"\"\"\nimport math\nimport torch\nfrom torch import nn\n\nfrom util.misc import NestedTensor\n\n\nclass PositionEmbeddingSine(nn.Module):\n    \"\"\"\n    This is a more standard version of the position embedding, very similar to the one\n    used by the Attention is all you need paper, generalized to work on images.\n    \"\"\"\n    def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):\n        super().__init__()\n        self.num_pos_feats = num_pos_feats\n        self.temperature = temperature\n        self.normalize = normalize\n        if scale is not None and normalize is False:\n            raise ValueError(\"normalize should be True if scale is passed\")\n        if scale is None:\n            scale = 2 * math.pi\n        self.scale = scale\n\n    def forward(self, tensor_list: NestedTensor):\n        x = tensor_list.tensors\n        mask = tensor_list.mask\n        assert mask is not None\n        not_mask = ~mask\n        y_embed = not_mask.cumsum(1, dtype=torch.float32)\n        x_embed = not_mask.cumsum(2, dtype=torch.float32)\n        if self.normalize:\n            eps = 1e-6\n            y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale\n            x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale\n\n        dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)\n        dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)\n\n        pos_x = x_embed[:, :, :, None] / dim_t\n        pos_y = y_embed[:, :, :, None] / dim_t\n        pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)\n        pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)\n        pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)\n        return pos\n\n\nclass PositionEmbeddingLearned(nn.Module):\n    \"\"\"\n    Absolute pos embedding, learned.\n    \"\"\"\n    def __init__(self, num_pos_feats=256):\n        super().__init__()\n        self.row_embed = nn.Embedding(50, num_pos_feats)\n        self.col_embed = nn.Embedding(50, num_pos_feats)\n        self.reset_parameters()\n\n    def reset_parameters(self):\n        nn.init.uniform_(self.row_embed.weight)\n        nn.init.uniform_(self.col_embed.weight)\n\n    def forward(self, tensor_list: NestedTensor):\n        x = tensor_list.tensors\n        h, w = x.shape[-2:]\n        i = torch.arange(w, device=x.device)\n        j = torch.arange(h, device=x.device)\n        x_emb = self.col_embed(i)\n        y_emb = self.row_embed(j)\n        pos = torch.cat([\n            x_emb.unsqueeze(0).repeat(h, 1, 1),\n            y_emb.unsqueeze(1).repeat(1, w, 1),\n        ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)\n        return pos\n\n\ndef build_position_encoding(args):\n    N_steps = args.hidden_dim // 2\n    if args.position_embedding in ('v2', 'sine'):\n        # TODO find a better way of exposing other arguments\n        position_embedding = PositionEmbeddingSine(N_steps, normalize=True)\n    elif args.position_embedding in ('v3', 'learned'):\n        position_embedding = PositionEmbeddingLearned(N_steps)\n    else:\n        raise ValueError(f\"not supported {args.position_embedding}\")\n\n    return position_embedding\n"
  },
  {
    "path": "models/segmentation.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nThis file provides the definition of the convolutional heads used to predict masks, as well as the losses\n\"\"\"\nimport io\nfrom collections import defaultdict\nfrom typing import List, Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom PIL import Image\n\nimport util.box_ops as box_ops\nfrom util.misc import NestedTensor, interpolate, nested_tensor_from_tensor_list\n\ntry:\n    from panopticapi.utils import id2rgb, rgb2id\nexcept ImportError:\n    pass\n\n\nclass DETRsegm(nn.Module):\n    def __init__(self, detr, freeze_detr=False):\n        super().__init__()\n        self.detr = detr\n\n        if freeze_detr:\n            for p in self.parameters():\n                p.requires_grad_(False)\n\n        hidden_dim, nheads = detr.transformer.d_model, detr.transformer.nhead\n        self.bbox_attention = MHAttentionMap(hidden_dim, hidden_dim, nheads, dropout=0.0)\n        self.mask_head = MaskHeadSmallConv(hidden_dim + nheads, [1024, 512, 256], hidden_dim)\n\n    def forward(self, samples: NestedTensor):\n        if isinstance(samples, (list, torch.Tensor)):\n            samples = nested_tensor_from_tensor_list(samples)\n        features, pos = self.detr.backbone(samples)\n\n        bs = features[-1].tensors.shape[0]\n\n        src, mask = features[-1].decompose()\n        assert mask is not None\n        src_proj = self.detr.input_proj(src)\n        hs, memory = self.detr.transformer(src_proj, mask, self.detr.query_embed.weight, pos[-1])\n\n        outputs_class = self.detr.class_embed(hs)\n        outputs_coord = self.detr.bbox_embed(hs).sigmoid()\n        out = {\"pred_logits\": outputs_class[-1], \"pred_boxes\": outputs_coord[-1]}\n        if self.detr.aux_loss:\n            out['aux_outputs'] = self.detr._set_aux_loss(outputs_class, outputs_coord)\n\n        # FIXME h_boxes takes the last one computed, keep this in mind\n        bbox_mask = self.bbox_attention(hs[-1], memory, mask=mask)\n\n        seg_masks = self.mask_head(src_proj, bbox_mask, [features[2].tensors, features[1].tensors, features[0].tensors])\n        outputs_seg_masks = seg_masks.view(bs, self.detr.num_queries, seg_masks.shape[-2], seg_masks.shape[-1])\n\n        out[\"pred_masks\"] = outputs_seg_masks\n        return out\n\n\ndef _expand(tensor, length: int):\n    return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1)\n\n\nclass MaskHeadSmallConv(nn.Module):\n    \"\"\"\n    Simple convolutional head, using group norm.\n    Upsampling is done using a FPN approach\n    \"\"\"\n\n    def __init__(self, dim, fpn_dims, context_dim):\n        super().__init__()\n\n        inter_dims = [dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64]\n        self.lay1 = torch.nn.Conv2d(dim, dim, 3, padding=1)\n        self.gn1 = torch.nn.GroupNorm(8, dim)\n        self.lay2 = torch.nn.Conv2d(dim, inter_dims[1], 3, padding=1)\n        self.gn2 = torch.nn.GroupNorm(8, inter_dims[1])\n        self.lay3 = torch.nn.Conv2d(inter_dims[1], inter_dims[2], 3, padding=1)\n        self.gn3 = torch.nn.GroupNorm(8, inter_dims[2])\n        self.lay4 = torch.nn.Conv2d(inter_dims[2], inter_dims[3], 3, padding=1)\n        self.gn4 = torch.nn.GroupNorm(8, inter_dims[3])\n        self.lay5 = torch.nn.Conv2d(inter_dims[3], inter_dims[4], 3, padding=1)\n        self.gn5 = torch.nn.GroupNorm(8, inter_dims[4])\n        self.out_lay = torch.nn.Conv2d(inter_dims[4], 1, 3, padding=1)\n\n        self.dim = dim\n\n        self.adapter1 = torch.nn.Conv2d(fpn_dims[0], inter_dims[1], 1)\n        self.adapter2 = torch.nn.Conv2d(fpn_dims[1], inter_dims[2], 1)\n        self.adapter3 = torch.nn.Conv2d(fpn_dims[2], inter_dims[3], 1)\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_uniform_(m.weight, a=1)\n                nn.init.constant_(m.bias, 0)\n\n    def forward(self, x: Tensor, bbox_mask: Tensor, fpns: List[Tensor]):\n        x = torch.cat([_expand(x, bbox_mask.shape[1]), bbox_mask.flatten(0, 1)], 1)\n\n        x = self.lay1(x)\n        x = self.gn1(x)\n        x = F.relu(x)\n        x = self.lay2(x)\n        x = self.gn2(x)\n        x = F.relu(x)\n\n        cur_fpn = self.adapter1(fpns[0])\n        if cur_fpn.size(0) != x.size(0):\n            cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n        x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n        x = self.lay3(x)\n        x = self.gn3(x)\n        x = F.relu(x)\n\n        cur_fpn = self.adapter2(fpns[1])\n        if cur_fpn.size(0) != x.size(0):\n            cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n        x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n        x = self.lay4(x)\n        x = self.gn4(x)\n        x = F.relu(x)\n\n        cur_fpn = self.adapter3(fpns[2])\n        if cur_fpn.size(0) != x.size(0):\n            cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n        x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n        x = self.lay5(x)\n        x = self.gn5(x)\n        x = F.relu(x)\n\n        x = self.out_lay(x)\n        return x\n\n\nclass MHAttentionMap(nn.Module):\n    \"\"\"This is a 2D attention module, which only returns the attention softmax (no multiplication by value)\"\"\"\n\n    def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True):\n        super().__init__()\n        self.num_heads = num_heads\n        self.hidden_dim = hidden_dim\n        self.dropout = nn.Dropout(dropout)\n\n        self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias)\n        self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias)\n\n        nn.init.zeros_(self.k_linear.bias)\n        nn.init.zeros_(self.q_linear.bias)\n        nn.init.xavier_uniform_(self.k_linear.weight)\n        nn.init.xavier_uniform_(self.q_linear.weight)\n        self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5\n\n    def forward(self, q, k, mask: Optional[Tensor] = None):\n        q = self.q_linear(q)\n        k = F.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias)\n        qh = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads)\n        kh = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1])\n        weights = torch.einsum(\"bqnc,bnchw->bqnhw\", qh * self.normalize_fact, kh)\n\n        if mask is not None:\n            weights.masked_fill_(mask.unsqueeze(1).unsqueeze(1), float(\"-inf\"))\n        weights = F.softmax(weights.flatten(2), dim=-1).view(weights.size())\n        weights = self.dropout(weights)\n        return weights\n\n\ndef dice_loss(inputs, targets, num_boxes):\n    \"\"\"\n    Compute the DICE loss, similar to generalized IOU for masks\n    Args:\n        inputs: A float tensor of arbitrary shape.\n                The predictions for each example.\n        targets: A float tensor with the same shape as inputs. Stores the binary\n                 classification label for each element in inputs\n                (0 for the negative class and 1 for the positive class).\n    \"\"\"\n    inputs = inputs.sigmoid()\n    inputs = inputs.flatten(1)\n    numerator = 2 * (inputs * targets).sum(1)\n    denominator = inputs.sum(-1) + targets.sum(-1)\n    loss = 1 - (numerator + 1) / (denominator + 1)\n    return loss.sum() / num_boxes\n\n\ndef sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):\n    \"\"\"\n    Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.\n    Args:\n        inputs: A float tensor of arbitrary shape.\n                The predictions for each example.\n        targets: A float tensor with the same shape as inputs. Stores the binary\n                 classification label for each element in inputs\n                (0 for the negative class and 1 for the positive class).\n        alpha: (optional) Weighting factor in range (0,1) to balance\n                positive vs negative examples. Default = -1 (no weighting).\n        gamma: Exponent of the modulating factor (1 - p_t) to\n               balance easy vs hard examples.\n    Returns:\n        Loss tensor\n    \"\"\"\n    prob = inputs.sigmoid()\n    ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction=\"none\")\n    p_t = prob * targets + (1 - prob) * (1 - targets)\n    loss = ce_loss * ((1 - p_t) ** gamma)\n\n    if alpha >= 0:\n        alpha_t = alpha * targets + (1 - alpha) * (1 - targets)\n        loss = alpha_t * loss\n\n    return loss.mean(1).sum() / num_boxes\n\n\nclass PostProcessSegm(nn.Module):\n    def __init__(self, threshold=0.5):\n        super().__init__()\n        self.threshold = threshold\n\n    @torch.no_grad()\n    def forward(self, results, outputs, orig_target_sizes, max_target_sizes):\n        assert len(orig_target_sizes) == len(max_target_sizes)\n        max_h, max_w = max_target_sizes.max(0)[0].tolist()\n        outputs_masks = outputs[\"pred_masks\"].squeeze(2)\n        outputs_masks = F.interpolate(outputs_masks, size=(max_h, max_w), mode=\"bilinear\", align_corners=False)\n        outputs_masks = (outputs_masks.sigmoid() > self.threshold).cpu()\n\n        for i, (cur_mask, t, tt) in enumerate(zip(outputs_masks, max_target_sizes, orig_target_sizes)):\n            img_h, img_w = t[0], t[1]\n            results[i][\"masks\"] = cur_mask[:, :img_h, :img_w].unsqueeze(1)\n            results[i][\"masks\"] = F.interpolate(\n                results[i][\"masks\"].float(), size=tuple(tt.tolist()), mode=\"nearest\"\n            ).byte()\n\n        return results\n\n\nclass PostProcessPanoptic(nn.Module):\n    \"\"\"This class converts the output of the model to the final panoptic result, in the format expected by the\n    coco panoptic API \"\"\"\n\n    def __init__(self, is_thing_map, threshold=0.85):\n        \"\"\"\n        Parameters:\n           is_thing_map: This is a whose keys are the class ids, and the values a boolean indicating whether\n                          the class is  a thing (True) or a stuff (False) class\n           threshold: confidence threshold: segments with confidence lower than this will be deleted\n        \"\"\"\n        super().__init__()\n        self.threshold = threshold\n        self.is_thing_map = is_thing_map\n\n    def forward(self, outputs, processed_sizes, target_sizes=None):\n        \"\"\" This function computes the panoptic prediction from the model's predictions.\n        Parameters:\n            outputs: This is a dict coming directly from the model. See the model doc for the content.\n            processed_sizes: This is a list of tuples (or torch tensors) of sizes of the images that were passed to the\n                             model, ie the size after data augmentation but before batching.\n            target_sizes: This is a list of tuples (or torch tensors) corresponding to the requested final size\n                          of each prediction. If left to None, it will default to the processed_sizes\n            \"\"\"\n        if target_sizes is None:\n            target_sizes = processed_sizes\n        assert len(processed_sizes) == len(target_sizes)\n        out_logits, raw_masks, raw_boxes = outputs[\"pred_logits\"], outputs[\"pred_masks\"], outputs[\"pred_boxes\"]\n        assert len(out_logits) == len(raw_masks) == len(target_sizes)\n        preds = []\n\n        def to_tuple(tup):\n            if isinstance(tup, tuple):\n                return tup\n            return tuple(tup.cpu().tolist())\n\n        for cur_logits, cur_masks, cur_boxes, size, target_size in zip(\n            out_logits, raw_masks, raw_boxes, processed_sizes, target_sizes\n        ):\n            # we filter empty queries and detection below threshold\n            scores, labels = cur_logits.softmax(-1).max(-1)\n            keep = labels.ne(outputs[\"pred_logits\"].shape[-1] - 1) & (scores > self.threshold)\n            cur_scores, cur_classes = cur_logits.softmax(-1).max(-1)\n            cur_scores = cur_scores[keep]\n            cur_classes = cur_classes[keep]\n            cur_masks = cur_masks[keep]\n            cur_masks = interpolate(cur_masks[:, None], to_tuple(size), mode=\"bilinear\").squeeze(1)\n            cur_boxes = box_ops.box_cxcywh_to_xyxy(cur_boxes[keep])\n\n            h, w = cur_masks.shape[-2:]\n            assert len(cur_boxes) == len(cur_classes)\n\n            # It may be that we have several predicted masks for the same stuff class.\n            # In the following, we track the list of masks ids for each stuff class (they are merged later on)\n            cur_masks = cur_masks.flatten(1)\n            stuff_equiv_classes = defaultdict(lambda: [])\n            for k, label in enumerate(cur_classes):\n                if not self.is_thing_map[label.item()]:\n                    stuff_equiv_classes[label.item()].append(k)\n\n            def get_ids_area(masks, scores, dedup=False):\n                # This helper function creates the final panoptic segmentation image\n                # It also returns the area of the masks that appears on the image\n\n                m_id = masks.transpose(0, 1).softmax(-1)\n\n                if m_id.shape[-1] == 0:\n                    # We didn't detect any mask :(\n                    m_id = torch.zeros((h, w), dtype=torch.long, device=m_id.device)\n                else:\n                    m_id = m_id.argmax(-1).view(h, w)\n\n                if dedup:\n                    # Merge the masks corresponding to the same stuff class\n                    for equiv in stuff_equiv_classes.values():\n                        if len(equiv) > 1:\n                            for eq_id in equiv:\n                                m_id.masked_fill_(m_id.eq(eq_id), equiv[0])\n\n                final_h, final_w = to_tuple(target_size)\n\n                seg_img = Image.fromarray(id2rgb(m_id.view(h, w).cpu().numpy()))\n                seg_img = seg_img.resize(size=(final_w, final_h), resample=Image.NEAREST)\n\n                np_seg_img = (\n                    torch.ByteTensor(torch.ByteStorage.from_buffer(seg_img.tobytes())).view(final_h, final_w, 3).numpy()\n                )\n                m_id = torch.from_numpy(rgb2id(np_seg_img))\n\n                area = []\n                for i in range(len(scores)):\n                    area.append(m_id.eq(i).sum().item())\n                return area, seg_img\n\n            area, seg_img = get_ids_area(cur_masks, cur_scores, dedup=True)\n            if cur_classes.numel() > 0:\n                # We know filter empty masks as long as we find some\n                while True:\n                    filtered_small = torch.as_tensor(\n                        [area[i] <= 4 for i, c in enumerate(cur_classes)], dtype=torch.bool, device=keep.device\n                    )\n                    if filtered_small.any().item():\n                        cur_scores = cur_scores[~filtered_small]\n                        cur_classes = cur_classes[~filtered_small]\n                        cur_masks = cur_masks[~filtered_small]\n                        area, seg_img = get_ids_area(cur_masks, cur_scores)\n                    else:\n                        break\n\n            else:\n                cur_classes = torch.ones(1, dtype=torch.long, device=cur_classes.device)\n\n            segments_info = []\n            for i, a in enumerate(area):\n                cat = cur_classes[i].item()\n                segments_info.append({\"id\": i, \"isthing\": self.is_thing_map[cat], \"category_id\": cat, \"area\": a})\n            del cur_classes\n\n            with io.BytesIO() as out:\n                seg_img.save(out, format=\"PNG\")\n                predictions = {\"png_string\": out.getvalue(), \"segments_info\": segments_info}\n            preds.append(predictions)\n        return preds\n"
  },
  {
    "path": "models/transformer.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nDETR Transformer class.\n\nCopy-paste from torch.nn.Transformer with modifications:\n    * positional encodings are passed in MHattention\n    * extra LN at the end of encoder is removed\n    * decoder returns a stack of activations from all decoding layers\n\"\"\"\nimport copy\nfrom typing import Optional, List\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn, Tensor\n\n\nclass Transformer(nn.Module):\n\n    def __init__(self, d_model=512, nhead=8, num_encoder_layers=6,\n                 num_decoder_layers=6, dim_feedforward=2048, dropout=0.1,\n                 activation=\"relu\", normalize_before=False,\n                 return_intermediate_dec=False):\n        super().__init__()\n\n        encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward,\n                                                dropout, activation, normalize_before)\n        encoder_norm = nn.LayerNorm(d_model) if normalize_before else None\n        self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)\n\n        decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward,\n                                                dropout, activation, normalize_before)\n        decoder_norm = nn.LayerNorm(d_model)\n        self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm,\n                                          return_intermediate=return_intermediate_dec)\n\n        self._reset_parameters()\n\n        self.d_model = d_model\n        self.nhead = nhead\n\n    def _reset_parameters(self):\n        for p in self.parameters():\n            if p.dim() > 1:\n                nn.init.xavier_uniform_(p)\n\n    def forward(self, src, mask, query_embed, pos_embed):\n        # flatten NxCxHxW to HWxNxC\n        bs, c, h, w = src.shape\n        src = src.flatten(2).permute(2, 0, 1)\n        pos_embed = pos_embed.flatten(2).permute(2, 0, 1)\n        query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)\n        mask = mask.flatten(1)\n\n        tgt = torch.zeros_like(query_embed)\n        memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed)\n        hs = self.decoder(tgt, memory, memory_key_padding_mask=mask,\n                          pos=pos_embed, query_pos=query_embed)\n        return hs.transpose(1, 2), memory.permute(1, 2, 0).view(bs, c, h, w)\n\n\nclass TransformerEncoder(nn.Module):\n\n    def __init__(self, encoder_layer, num_layers, norm=None):\n        super().__init__()\n        self.layers = _get_clones(encoder_layer, num_layers)\n        self.num_layers = num_layers\n        self.norm = norm\n\n    def forward(self, src,\n                mask: Optional[Tensor] = None,\n                src_key_padding_mask: Optional[Tensor] = None,\n                pos: Optional[Tensor] = None):\n        output = src\n\n        for layer in self.layers:\n            output = layer(output, src_mask=mask,\n                           src_key_padding_mask=src_key_padding_mask, pos=pos)\n\n        if self.norm is not None:\n            output = self.norm(output)\n\n        return output\n\n\nclass TransformerDecoder(nn.Module):\n\n    def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):\n        super().__init__()\n        self.layers = _get_clones(decoder_layer, num_layers)\n        self.num_layers = num_layers\n        self.norm = norm\n        self.return_intermediate = return_intermediate\n\n    def forward(self, tgt, memory,\n                tgt_mask: Optional[Tensor] = None,\n                memory_mask: Optional[Tensor] = None,\n                tgt_key_padding_mask: Optional[Tensor] = None,\n                memory_key_padding_mask: Optional[Tensor] = None,\n                pos: Optional[Tensor] = None,\n                query_pos: Optional[Tensor] = None):\n        output = tgt\n\n        intermediate = []\n\n        for layer in self.layers:\n            output = layer(output, memory, tgt_mask=tgt_mask,\n                           memory_mask=memory_mask,\n                           tgt_key_padding_mask=tgt_key_padding_mask,\n                           memory_key_padding_mask=memory_key_padding_mask,\n                           pos=pos, query_pos=query_pos)\n            if self.return_intermediate:\n                intermediate.append(self.norm(output))\n\n        if self.norm is not None:\n            output = self.norm(output)\n            if self.return_intermediate:\n                intermediate.pop()\n                intermediate.append(output)\n\n        if self.return_intermediate:\n            return torch.stack(intermediate)\n\n        return output.unsqueeze(0)\n\n\nclass TransformerEncoderLayer(nn.Module):\n\n    def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,\n                 activation=\"relu\", normalize_before=False):\n        super().__init__()\n        self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\n        # Implementation of Feedforward model\n        self.linear1 = nn.Linear(d_model, dim_feedforward)\n        self.dropout = nn.Dropout(dropout)\n        self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n        self.norm1 = nn.LayerNorm(d_model)\n        self.norm2 = nn.LayerNorm(d_model)\n        self.dropout1 = nn.Dropout(dropout)\n        self.dropout2 = nn.Dropout(dropout)\n\n        self.activation = _get_activation_fn(activation)\n        self.normalize_before = normalize_before\n\n    def with_pos_embed(self, tensor, pos: Optional[Tensor]):\n        return tensor if pos is None else tensor + pos\n\n    def forward_post(self,\n                     src,\n                     src_mask: Optional[Tensor] = None,\n                     src_key_padding_mask: Optional[Tensor] = None,\n                     pos: Optional[Tensor] = None):\n        q = k = self.with_pos_embed(src, pos)\n        src2 = self.self_attn(q, k, value=src, attn_mask=src_mask,\n                              key_padding_mask=src_key_padding_mask)[0]\n        src = src + self.dropout1(src2)\n        src = self.norm1(src)\n        src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))\n        src = src + self.dropout2(src2)\n        src = self.norm2(src)\n        return src\n\n    def forward_pre(self, src,\n                    src_mask: Optional[Tensor] = None,\n                    src_key_padding_mask: Optional[Tensor] = None,\n                    pos: Optional[Tensor] = None):\n        src2 = self.norm1(src)\n        q = k = self.with_pos_embed(src2, pos)\n        src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask,\n                              key_padding_mask=src_key_padding_mask)[0]\n        src = src + self.dropout1(src2)\n        src2 = self.norm2(src)\n        src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))\n        src = src + self.dropout2(src2)\n        return src\n\n    def forward(self, src,\n                src_mask: Optional[Tensor] = None,\n                src_key_padding_mask: Optional[Tensor] = None,\n                pos: Optional[Tensor] = None):\n        if self.normalize_before:\n            return self.forward_pre(src, src_mask, src_key_padding_mask, pos)\n        return self.forward_post(src, src_mask, src_key_padding_mask, pos)\n\n\nclass TransformerDecoderLayer(nn.Module):\n\n    def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,\n                 activation=\"relu\", normalize_before=False):\n        super().__init__()\n        self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\n        self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\n        # Implementation of Feedforward model\n        self.linear1 = nn.Linear(d_model, dim_feedforward)\n        self.dropout = nn.Dropout(dropout)\n        self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n        self.norm1 = nn.LayerNorm(d_model)\n        self.norm2 = nn.LayerNorm(d_model)\n        self.norm3 = nn.LayerNorm(d_model)\n        self.dropout1 = nn.Dropout(dropout)\n        self.dropout2 = nn.Dropout(dropout)\n        self.dropout3 = nn.Dropout(dropout)\n\n        self.activation = _get_activation_fn(activation)\n        self.normalize_before = normalize_before\n\n    def with_pos_embed(self, tensor, pos: Optional[Tensor]):\n        return tensor if pos is None else tensor + pos\n\n    def forward_post(self, tgt, memory,\n                     tgt_mask: Optional[Tensor] = None,\n                     memory_mask: Optional[Tensor] = None,\n                     tgt_key_padding_mask: Optional[Tensor] = None,\n                     memory_key_padding_mask: Optional[Tensor] = None,\n                     pos: Optional[Tensor] = None,\n                     query_pos: Optional[Tensor] = None):\n        q = k = self.with_pos_embed(tgt, query_pos)\n        tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask,\n                              key_padding_mask=tgt_key_padding_mask)[0]\n        tgt = tgt + self.dropout1(tgt2)\n        tgt = self.norm1(tgt)\n        tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),\n                                   key=self.with_pos_embed(memory, pos),\n                                   value=memory, attn_mask=memory_mask,\n                                   key_padding_mask=memory_key_padding_mask)[0]\n        tgt = tgt + self.dropout2(tgt2)\n        tgt = self.norm2(tgt)\n        tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))\n        tgt = tgt + self.dropout3(tgt2)\n        tgt = self.norm3(tgt)\n        return tgt\n\n    def forward_pre(self, tgt, memory,\n                    tgt_mask: Optional[Tensor] = None,\n                    memory_mask: Optional[Tensor] = None,\n                    tgt_key_padding_mask: Optional[Tensor] = None,\n                    memory_key_padding_mask: Optional[Tensor] = None,\n                    pos: Optional[Tensor] = None,\n                    query_pos: Optional[Tensor] = None):\n        tgt2 = self.norm1(tgt)\n        q = k = self.with_pos_embed(tgt2, query_pos)\n        tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask,\n                              key_padding_mask=tgt_key_padding_mask)[0]\n        tgt = tgt + self.dropout1(tgt2)\n        tgt2 = self.norm2(tgt)\n        tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),\n                                   key=self.with_pos_embed(memory, pos),\n                                   value=memory, attn_mask=memory_mask,\n                                   key_padding_mask=memory_key_padding_mask)[0]\n        tgt = tgt + self.dropout2(tgt2)\n        tgt2 = self.norm3(tgt)\n        tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))\n        tgt = tgt + self.dropout3(tgt2)\n        return tgt\n\n    def forward(self, tgt, memory,\n                tgt_mask: Optional[Tensor] = None,\n                memory_mask: Optional[Tensor] = None,\n                tgt_key_padding_mask: Optional[Tensor] = None,\n                memory_key_padding_mask: Optional[Tensor] = None,\n                pos: Optional[Tensor] = None,\n                query_pos: Optional[Tensor] = None):\n        if self.normalize_before:\n            return self.forward_pre(tgt, memory, tgt_mask, memory_mask,\n                                    tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)\n        return self.forward_post(tgt, memory, tgt_mask, memory_mask,\n                                 tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos)\n\n\ndef _get_clones(module, N):\n    return nn.ModuleList([copy.deepcopy(module) for i in range(N)])\n\n\ndef build_transformer(args):\n    return Transformer(\n        d_model=args.hidden_dim,\n        dropout=args.dropout,\n        nhead=args.nheads,\n        dim_feedforward=args.dim_feedforward,\n        num_encoder_layers=args.enc_layers,\n        num_decoder_layers=args.dec_layers,\n        normalize_before=args.pre_norm,\n        return_intermediate_dec=True,\n    )\n\n\ndef _get_activation_fn(activation):\n    \"\"\"Return an activation function given a string\"\"\"\n    if activation == \"relu\":\n        return F.relu\n    if activation == \"gelu\":\n        return F.gelu\n    if activation == \"glu\":\n        return F.glu\n    raise RuntimeError(F\"activation should be relu/gelu, not {activation}.\")\n"
  },
  {
    "path": "requirements.txt",
    "content": "cython\ngit+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI&egg=pycocotools\nsubmitit\ntorch>=1.5.0\ntorchvision>=0.6.0\ngit+https://github.com/cocodataset/panopticapi.git#egg=panopticapi\nscipy\nonnx\nonnxruntime\n"
  },
  {
    "path": "run_with_submitit.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nA script to run multinode training with submitit.\n\"\"\"\nimport argparse\nimport os\nimport uuid\nfrom pathlib import Path\n\nimport main as detection\nimport submitit\n\n\ndef parse_args():\n    detection_parser = detection.get_args_parser()\n    parser = argparse.ArgumentParser(\"Submitit for detection\", parents=[detection_parser])\n    parser.add_argument(\"--ngpus\", default=8, type=int, help=\"Number of gpus to request on each node\")\n    parser.add_argument(\"--nodes\", default=4, type=int, help=\"Number of nodes to request\")\n    parser.add_argument(\"--timeout\", default=60, type=int, help=\"Duration of the job\")\n    parser.add_argument(\"--job_dir\", default=\"\", type=str, help=\"Job dir. Leave empty for automatic.\")\n    return parser.parse_args()\n\n\ndef get_shared_folder() -> Path:\n    user = os.getenv(\"USER\")\n    if Path(\"/checkpoint/\").is_dir():\n        p = Path(f\"/checkpoint/{user}/experiments\")\n        p.mkdir(exist_ok=True)\n        return p\n    raise RuntimeError(\"No shared folder available\")\n\n\ndef get_init_file():\n    # Init file must not exist, but it's parent dir must exist.\n    os.makedirs(str(get_shared_folder()), exist_ok=True)\n    init_file = get_shared_folder() / f\"{uuid.uuid4().hex}_init\"\n    if init_file.exists():\n        os.remove(str(init_file))\n    return init_file\n\n\nclass Trainer(object):\n    def __init__(self, args):\n        self.args = args\n\n    def __call__(self):\n        import main as detection\n\n        self._setup_gpu_args()\n        detection.main(self.args)\n\n    def checkpoint(self):\n        import os\n        import submitit\n        from pathlib import Path\n\n        self.args.dist_url = get_init_file().as_uri()\n        checkpoint_file = os.path.join(self.args.output_dir, \"checkpoint.pth\")\n        if os.path.exists(checkpoint_file):\n            self.args.resume = checkpoint_file\n        print(\"Requeuing \", self.args)\n        empty_trainer = type(self)(self.args)\n        return submitit.helpers.DelayedSubmission(empty_trainer)\n\n    def _setup_gpu_args(self):\n        import submitit\n        from pathlib import Path\n\n        job_env = submitit.JobEnvironment()\n        self.args.output_dir = Path(str(self.args.output_dir).replace(\"%j\", str(job_env.job_id)))\n        self.args.gpu = job_env.local_rank\n        self.args.rank = job_env.global_rank\n        self.args.world_size = job_env.num_tasks\n        print(f\"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}\")\n\n\ndef main():\n    args = parse_args()\n    if args.job_dir == \"\":\n        args.job_dir = get_shared_folder() / \"%j\"\n\n    # Note that the folder will depend on the job_id, to easily track experiments\n    executor = submitit.AutoExecutor(folder=args.job_dir, slurm_max_num_timeout=30)\n\n    # cluster setup is defined by environment variables\n    num_gpus_per_node = args.ngpus\n    nodes = args.nodes\n    timeout_min = args.timeout\n\n    executor.update_parameters(\n        mem_gb=40 * num_gpus_per_node,\n        gpus_per_node=num_gpus_per_node,\n        tasks_per_node=num_gpus_per_node,  # one task per GPU\n        cpus_per_task=10,\n        nodes=nodes,\n        timeout_min=timeout_min,  # max is 60 * 72\n    )\n\n    executor.update_parameters(name=\"detr\")\n\n    args.dist_url = get_init_file().as_uri()\n    args.output_dir = args.job_dir\n\n    trainer = Trainer(args)\n    job = executor.submit(trainer)\n\n    print(\"Submitted job_id:\", job.job_id)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "test_all.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport io\nimport unittest\n\nimport torch\nfrom torch import nn, Tensor\nfrom typing import List\n\nfrom models.matcher import HungarianMatcher\nfrom models.position_encoding import PositionEmbeddingSine, PositionEmbeddingLearned\nfrom models.backbone import Backbone, Joiner, BackboneBase\nfrom util import box_ops\nfrom util.misc import nested_tensor_from_tensor_list\nfrom hubconf import detr_resnet50, detr_resnet50_panoptic\n\n# onnxruntime requires python 3.5 or above\ntry:\n    import onnxruntime\nexcept ImportError:\n    onnxruntime = None\n\n\nclass Tester(unittest.TestCase):\n\n    def test_box_cxcywh_to_xyxy(self):\n        t = torch.rand(10, 4)\n        r = box_ops.box_xyxy_to_cxcywh(box_ops.box_cxcywh_to_xyxy(t))\n        self.assertLess((t - r).abs().max(), 1e-5)\n\n    @staticmethod\n    def indices_torch2python(indices):\n        return [(i.tolist(), j.tolist()) for i, j in indices]\n\n    def test_hungarian(self):\n        n_queries, n_targets, n_classes = 100, 15, 91\n        logits = torch.rand(1, n_queries, n_classes + 1)\n        boxes = torch.rand(1, n_queries, 4)\n        tgt_labels = torch.randint(high=n_classes, size=(n_targets,))\n        tgt_boxes = torch.rand(n_targets, 4)\n        matcher = HungarianMatcher()\n        targets = [{'labels': tgt_labels, 'boxes': tgt_boxes}]\n        indices_single = matcher({'pred_logits': logits, 'pred_boxes': boxes}, targets)\n        indices_batched = matcher({'pred_logits': logits.repeat(2, 1, 1),\n                                   'pred_boxes': boxes.repeat(2, 1, 1)}, targets * 2)\n        self.assertEqual(len(indices_single[0][0]), n_targets)\n        self.assertEqual(len(indices_single[0][1]), n_targets)\n        self.assertEqual(self.indices_torch2python(indices_single),\n                         self.indices_torch2python([indices_batched[0]]))\n        self.assertEqual(self.indices_torch2python(indices_single),\n                         self.indices_torch2python([indices_batched[1]]))\n\n        # test with empty targets\n        tgt_labels_empty = torch.randint(high=n_classes, size=(0,))\n        tgt_boxes_empty = torch.rand(0, 4)\n        targets_empty = [{'labels': tgt_labels_empty, 'boxes': tgt_boxes_empty}]\n        indices = matcher({'pred_logits': logits.repeat(2, 1, 1),\n                           'pred_boxes': boxes.repeat(2, 1, 1)}, targets + targets_empty)\n        self.assertEqual(len(indices[1][0]), 0)\n        indices = matcher({'pred_logits': logits.repeat(2, 1, 1),\n                           'pred_boxes': boxes.repeat(2, 1, 1)}, targets_empty * 2)\n        self.assertEqual(len(indices[0][0]), 0)\n\n    def test_position_encoding_script(self):\n        m1, m2 = PositionEmbeddingSine(), PositionEmbeddingLearned()\n        mm1, mm2 = torch.jit.script(m1), torch.jit.script(m2)  # noqa\n\n    def test_backbone_script(self):\n        backbone = Backbone('resnet50', True, False, False)\n        torch.jit.script(backbone)  # noqa\n\n    def test_model_script_detection(self):\n        model = detr_resnet50(pretrained=False).eval()\n        scripted_model = torch.jit.script(model)\n        x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)])\n        out = model(x)\n        out_script = scripted_model(x)\n        self.assertTrue(out[\"pred_logits\"].equal(out_script[\"pred_logits\"]))\n        self.assertTrue(out[\"pred_boxes\"].equal(out_script[\"pred_boxes\"]))\n\n    def test_model_script_panoptic(self):\n        model = detr_resnet50_panoptic(pretrained=False).eval()\n        scripted_model = torch.jit.script(model)\n        x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)])\n        out = model(x)\n        out_script = scripted_model(x)\n        self.assertTrue(out[\"pred_logits\"].equal(out_script[\"pred_logits\"]))\n        self.assertTrue(out[\"pred_boxes\"].equal(out_script[\"pred_boxes\"]))\n        self.assertTrue(out[\"pred_masks\"].equal(out_script[\"pred_masks\"]))\n\n    def test_model_detection_different_inputs(self):\n        model = detr_resnet50(pretrained=False).eval()\n        # support NestedTensor\n        x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)])\n        out = model(x)\n        self.assertIn('pred_logits', out)\n        # and 4d Tensor\n        x = torch.rand(1, 3, 200, 200)\n        out = model(x)\n        self.assertIn('pred_logits', out)\n        # and List[Tensor[C, H, W]]\n        x = torch.rand(3, 200, 200)\n        out = model([x])\n        self.assertIn('pred_logits', out)\n\n    def test_warpped_model_script_detection(self):\n        class WrappedDETR(nn.Module):\n            def __init__(self, model):\n                super().__init__()\n                self.model = model\n\n            def forward(self, inputs: List[Tensor]):\n                sample = nested_tensor_from_tensor_list(inputs)\n                return self.model(sample)\n\n        model = detr_resnet50(pretrained=False)\n        wrapped_model = WrappedDETR(model)\n        wrapped_model.eval()\n        scripted_model = torch.jit.script(wrapped_model)\n        x = [torch.rand(3, 200, 200), torch.rand(3, 200, 250)]\n        out = wrapped_model(x)\n        out_script = scripted_model(x)\n        self.assertTrue(out[\"pred_logits\"].equal(out_script[\"pred_logits\"]))\n        self.assertTrue(out[\"pred_boxes\"].equal(out_script[\"pred_boxes\"]))\n\n\n@unittest.skipIf(onnxruntime is None, 'ONNX Runtime unavailable')\nclass ONNXExporterTester(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        torch.manual_seed(123)\n\n    def run_model(self, model, inputs_list, tolerate_small_mismatch=False, do_constant_folding=True, dynamic_axes=None,\n                  output_names=None, input_names=None):\n        model.eval()\n\n        onnx_io = io.BytesIO()\n        # export to onnx with the first input\n        torch.onnx.export(model, inputs_list[0], onnx_io,\n                          do_constant_folding=do_constant_folding, opset_version=12,\n                          dynamic_axes=dynamic_axes, input_names=input_names, output_names=output_names)\n        # validate the exported model with onnx runtime\n        for test_inputs in inputs_list:\n            with torch.no_grad():\n                if isinstance(test_inputs, torch.Tensor) or isinstance(test_inputs, list):\n                    test_inputs = (nested_tensor_from_tensor_list(test_inputs),)\n                test_ouputs = model(*test_inputs)\n                if isinstance(test_ouputs, torch.Tensor):\n                    test_ouputs = (test_ouputs,)\n            self.ort_validate(onnx_io, test_inputs, test_ouputs, tolerate_small_mismatch)\n\n    def ort_validate(self, onnx_io, inputs, outputs, tolerate_small_mismatch=False):\n\n        inputs, _ = torch.jit._flatten(inputs)\n        outputs, _ = torch.jit._flatten(outputs)\n\n        def to_numpy(tensor):\n            if tensor.requires_grad:\n                return tensor.detach().cpu().numpy()\n            else:\n                return tensor.cpu().numpy()\n\n        inputs = list(map(to_numpy, inputs))\n        outputs = list(map(to_numpy, outputs))\n\n        ort_session = onnxruntime.InferenceSession(onnx_io.getvalue())\n        # compute onnxruntime output prediction\n        ort_inputs = dict((ort_session.get_inputs()[i].name, inpt) for i, inpt in enumerate(inputs))\n        ort_outs = ort_session.run(None, ort_inputs)\n        for i, element in enumerate(outputs):\n            try:\n                torch.testing.assert_allclose(element, ort_outs[i], rtol=1e-03, atol=1e-05)\n            except AssertionError as error:\n                if tolerate_small_mismatch:\n                    self.assertIn(\"(0.00%)\", str(error), str(error))\n                else:\n                    raise\n\n    def test_model_onnx_detection(self):\n        model = detr_resnet50(pretrained=False).eval()\n        dummy_image = torch.ones(1, 3, 800, 800) * 0.3\n        model(dummy_image)\n\n        # Test exported model on images of different size, or dummy input\n        self.run_model(\n            model,\n            [(torch.rand(1, 3, 750, 800),)],\n            input_names=[\"inputs\"],\n            output_names=[\"pred_logits\", \"pred_boxes\"],\n            tolerate_small_mismatch=True,\n        )\n\n    @unittest.skip(\"CI doesn't have enough memory\")\n    def test_model_onnx_detection_panoptic(self):\n        model = detr_resnet50_panoptic(pretrained=False).eval()\n        dummy_image = torch.ones(1, 3, 800, 800) * 0.3\n        model(dummy_image)\n\n        # Test exported model on images of different size, or dummy input\n        self.run_model(\n            model,\n            [(torch.rand(1, 3, 750, 800),)],\n            input_names=[\"inputs\"],\n            output_names=[\"pred_logits\", \"pred_boxes\", \"pred_masks\"],\n            tolerate_small_mismatch=True,\n        )\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tox.ini",
    "content": "[flake8]\nmax-line-length = 120\nignore = F401,E402,F403,W503,W504\n"
  },
  {
    "path": "util/__init__.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n"
  },
  {
    "path": "util/box_ops.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nUtilities for bounding box manipulation and GIoU.\n\"\"\"\nimport torch\nfrom torchvision.ops.boxes import box_area\n\n\ndef box_cxcywh_to_xyxy(x):\n    x_c, y_c, w, h = x.unbind(-1)\n    b = [(x_c - 0.5 * w), (y_c - 0.5 * h),\n         (x_c + 0.5 * w), (y_c + 0.5 * h)]\n    return torch.stack(b, dim=-1)\n\n\ndef box_xyxy_to_cxcywh(x):\n    x0, y0, x1, y1 = x.unbind(-1)\n    b = [(x0 + x1) / 2, (y0 + y1) / 2,\n         (x1 - x0), (y1 - y0)]\n    return torch.stack(b, dim=-1)\n\n\n# modified from torchvision to also return the union\ndef box_iou(boxes1, boxes2):\n    area1 = box_area(boxes1)\n    area2 = box_area(boxes2)\n\n    lt = torch.max(boxes1[:, None, :2], boxes2[:, :2])  # [N,M,2]\n    rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])  # [N,M,2]\n\n    wh = (rb - lt).clamp(min=0)  # [N,M,2]\n    inter = wh[:, :, 0] * wh[:, :, 1]  # [N,M]\n\n    union = area1[:, None] + area2 - inter\n\n    iou = inter / union\n    return iou, union\n\n\ndef generalized_box_iou(boxes1, boxes2):\n    \"\"\"\n    Generalized IoU from https://giou.stanford.edu/\n\n    The boxes should be in [x0, y0, x1, y1] format\n\n    Returns a [N, M] pairwise matrix, where N = len(boxes1)\n    and M = len(boxes2)\n    \"\"\"\n    # degenerate boxes gives inf / nan results\n    # so do an early check\n    assert (boxes1[:, 2:] >= boxes1[:, :2]).all()\n    assert (boxes2[:, 2:] >= boxes2[:, :2]).all()\n    iou, union = box_iou(boxes1, boxes2)\n\n    lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])\n    rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])\n\n    wh = (rb - lt).clamp(min=0)  # [N,M,2]\n    area = wh[:, :, 0] * wh[:, :, 1]\n\n    return iou - (area - union) / area\n\n\ndef masks_to_boxes(masks):\n    \"\"\"Compute the bounding boxes around the provided masks\n\n    The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.\n\n    Returns a [N, 4] tensors, with the boxes in xyxy format\n    \"\"\"\n    if masks.numel() == 0:\n        return torch.zeros((0, 4), device=masks.device)\n\n    h, w = masks.shape[-2:]\n\n    y = torch.arange(0, h, dtype=torch.float)\n    x = torch.arange(0, w, dtype=torch.float)\n    y, x = torch.meshgrid(y, x)\n\n    x_mask = (masks * x.unsqueeze(0))\n    x_max = x_mask.flatten(1).max(-1)[0]\n    x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]\n\n    y_mask = (masks * y.unsqueeze(0))\n    y_max = y_mask.flatten(1).max(-1)[0]\n    y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]\n\n    return torch.stack([x_min, y_min, x_max, y_max], 1)\n"
  },
  {
    "path": "util/misc.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nMisc functions, including distributed helpers.\n\nMostly copy-paste from torchvision references.\n\"\"\"\nimport os\nimport subprocess\nimport time\nfrom collections import defaultdict, deque\nimport datetime\nimport pickle\nfrom packaging import version\nfrom typing import Optional, List\n\nimport torch\nimport torch.distributed as dist\nfrom torch import Tensor\n\n# needed due to empty tensor bug in pytorch and torchvision 0.5\nimport torchvision\nif version.parse(torchvision.__version__) < version.parse('0.7'):\n    from torchvision.ops import _new_empty_tensor\n    from torchvision.ops.misc import _output_size\n\n\nclass SmoothedValue(object):\n    \"\"\"Track a series of values and provide access to smoothed values over a\n    window or the global series average.\n    \"\"\"\n\n    def __init__(self, window_size=20, fmt=None):\n        if fmt is None:\n            fmt = \"{median:.4f} ({global_avg:.4f})\"\n        self.deque = deque(maxlen=window_size)\n        self.total = 0.0\n        self.count = 0\n        self.fmt = fmt\n\n    def update(self, value, n=1):\n        self.deque.append(value)\n        self.count += n\n        self.total += value * n\n\n    def synchronize_between_processes(self):\n        \"\"\"\n        Warning: does not synchronize the deque!\n        \"\"\"\n        if not is_dist_avail_and_initialized():\n            return\n        t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')\n        dist.barrier()\n        dist.all_reduce(t)\n        t = t.tolist()\n        self.count = int(t[0])\n        self.total = t[1]\n\n    @property\n    def median(self):\n        d = torch.tensor(list(self.deque))\n        return d.median().item()\n\n    @property\n    def avg(self):\n        d = torch.tensor(list(self.deque), dtype=torch.float32)\n        return d.mean().item()\n\n    @property\n    def global_avg(self):\n        return self.total / self.count\n\n    @property\n    def max(self):\n        return max(self.deque)\n\n    @property\n    def value(self):\n        return self.deque[-1]\n\n    def __str__(self):\n        return self.fmt.format(\n            median=self.median,\n            avg=self.avg,\n            global_avg=self.global_avg,\n            max=self.max,\n            value=self.value)\n\n\ndef all_gather(data):\n    \"\"\"\n    Run all_gather on arbitrary picklable data (not necessarily tensors)\n    Args:\n        data: any picklable object\n    Returns:\n        list[data]: list of data gathered from each rank\n    \"\"\"\n    world_size = get_world_size()\n    if world_size == 1:\n        return [data]\n\n    # serialized to a Tensor\n    buffer = pickle.dumps(data)\n    storage = torch.ByteStorage.from_buffer(buffer)\n    tensor = torch.ByteTensor(storage).to(\"cuda\")\n\n    # obtain Tensor size of each rank\n    local_size = torch.tensor([tensor.numel()], device=\"cuda\")\n    size_list = [torch.tensor([0], device=\"cuda\") for _ in range(world_size)]\n    dist.all_gather(size_list, local_size)\n    size_list = [int(size.item()) for size in size_list]\n    max_size = max(size_list)\n\n    # receiving Tensor from all ranks\n    # we pad the tensor because torch all_gather does not support\n    # gathering tensors of different shapes\n    tensor_list = []\n    for _ in size_list:\n        tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=\"cuda\"))\n    if local_size != max_size:\n        padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device=\"cuda\")\n        tensor = torch.cat((tensor, padding), dim=0)\n    dist.all_gather(tensor_list, tensor)\n\n    data_list = []\n    for size, tensor in zip(size_list, tensor_list):\n        buffer = tensor.cpu().numpy().tobytes()[:size]\n        data_list.append(pickle.loads(buffer))\n\n    return data_list\n\n\ndef reduce_dict(input_dict, average=True):\n    \"\"\"\n    Args:\n        input_dict (dict): all the values will be reduced\n        average (bool): whether to do average or sum\n    Reduce the values in the dictionary from all processes so that all processes\n    have the averaged results. Returns a dict with the same fields as\n    input_dict, after reduction.\n    \"\"\"\n    world_size = get_world_size()\n    if world_size < 2:\n        return input_dict\n    with torch.no_grad():\n        names = []\n        values = []\n        # sort the keys so that they are consistent across processes\n        for k in sorted(input_dict.keys()):\n            names.append(k)\n            values.append(input_dict[k])\n        values = torch.stack(values, dim=0)\n        dist.all_reduce(values)\n        if average:\n            values /= world_size\n        reduced_dict = {k: v for k, v in zip(names, values)}\n    return reduced_dict\n\n\nclass MetricLogger(object):\n    def __init__(self, delimiter=\"\\t\"):\n        self.meters = defaultdict(SmoothedValue)\n        self.delimiter = delimiter\n\n    def update(self, **kwargs):\n        for k, v in kwargs.items():\n            if isinstance(v, torch.Tensor):\n                v = v.item()\n            assert isinstance(v, (float, int))\n            self.meters[k].update(v)\n\n    def __getattr__(self, attr):\n        if attr in self.meters:\n            return self.meters[attr]\n        if attr in self.__dict__:\n            return self.__dict__[attr]\n        raise AttributeError(\"'{}' object has no attribute '{}'\".format(\n            type(self).__name__, attr))\n\n    def __str__(self):\n        loss_str = []\n        for name, meter in self.meters.items():\n            loss_str.append(\n                \"{}: {}\".format(name, str(meter))\n            )\n        return self.delimiter.join(loss_str)\n\n    def synchronize_between_processes(self):\n        for meter in self.meters.values():\n            meter.synchronize_between_processes()\n\n    def add_meter(self, name, meter):\n        self.meters[name] = meter\n\n    def log_every(self, iterable, print_freq, header=None):\n        i = 0\n        if not header:\n            header = ''\n        start_time = time.time()\n        end = time.time()\n        iter_time = SmoothedValue(fmt='{avg:.4f}')\n        data_time = SmoothedValue(fmt='{avg:.4f}')\n        space_fmt = ':' + str(len(str(len(iterable)))) + 'd'\n        if torch.cuda.is_available():\n            log_msg = self.delimiter.join([\n                header,\n                '[{0' + space_fmt + '}/{1}]',\n                'eta: {eta}',\n                '{meters}',\n                'time: {time}',\n                'data: {data}',\n                'max mem: {memory:.0f}'\n            ])\n        else:\n            log_msg = self.delimiter.join([\n                header,\n                '[{0' + space_fmt + '}/{1}]',\n                'eta: {eta}',\n                '{meters}',\n                'time: {time}',\n                'data: {data}'\n            ])\n        MB = 1024.0 * 1024.0\n        for obj in iterable:\n            data_time.update(time.time() - end)\n            yield obj\n            iter_time.update(time.time() - end)\n            if i % print_freq == 0 or i == len(iterable) - 1:\n                eta_seconds = iter_time.global_avg * (len(iterable) - i)\n                eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n                if torch.cuda.is_available():\n                    print(log_msg.format(\n                        i, len(iterable), eta=eta_string,\n                        meters=str(self),\n                        time=str(iter_time), data=str(data_time),\n                        memory=torch.cuda.max_memory_allocated() / MB))\n                else:\n                    print(log_msg.format(\n                        i, len(iterable), eta=eta_string,\n                        meters=str(self),\n                        time=str(iter_time), data=str(data_time)))\n            i += 1\n            end = time.time()\n        total_time = time.time() - start_time\n        total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n        print('{} Total time: {} ({:.4f} s / it)'.format(\n            header, total_time_str, total_time / len(iterable)))\n\n\ndef get_sha():\n    cwd = os.path.dirname(os.path.abspath(__file__))\n\n    def _run(command):\n        return subprocess.check_output(command, cwd=cwd).decode('ascii').strip()\n    sha = 'N/A'\n    diff = \"clean\"\n    branch = 'N/A'\n    try:\n        sha = _run(['git', 'rev-parse', 'HEAD'])\n        subprocess.check_output(['git', 'diff'], cwd=cwd)\n        diff = _run(['git', 'diff-index', 'HEAD'])\n        diff = \"has uncommited changes\" if diff else \"clean\"\n        branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])\n    except Exception:\n        pass\n    message = f\"sha: {sha}, status: {diff}, branch: {branch}\"\n    return message\n\n\ndef collate_fn(batch):\n    batch = list(zip(*batch))\n    batch[0] = nested_tensor_from_tensor_list(batch[0])\n    return tuple(batch)\n\n\ndef _max_by_axis(the_list):\n    # type: (List[List[int]]) -> List[int]\n    maxes = the_list[0]\n    for sublist in the_list[1:]:\n        for index, item in enumerate(sublist):\n            maxes[index] = max(maxes[index], item)\n    return maxes\n\n\nclass NestedTensor(object):\n    def __init__(self, tensors, mask: Optional[Tensor]):\n        self.tensors = tensors\n        self.mask = mask\n\n    def to(self, device):\n        # type: (Device) -> NestedTensor # noqa\n        cast_tensor = self.tensors.to(device)\n        mask = self.mask\n        if mask is not None:\n            assert mask is not None\n            cast_mask = mask.to(device)\n        else:\n            cast_mask = None\n        return NestedTensor(cast_tensor, cast_mask)\n\n    def decompose(self):\n        return self.tensors, self.mask\n\n    def __repr__(self):\n        return str(self.tensors)\n\n\ndef nested_tensor_from_tensor_list(tensor_list: List[Tensor]):\n    # TODO make this more general\n    if tensor_list[0].ndim == 3:\n        if torchvision._is_tracing():\n            # nested_tensor_from_tensor_list() does not export well to ONNX\n            # call _onnx_nested_tensor_from_tensor_list() instead\n            return _onnx_nested_tensor_from_tensor_list(tensor_list)\n\n        # TODO make it support different-sized images\n        max_size = _max_by_axis([list(img.shape) for img in tensor_list])\n        # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list]))\n        batch_shape = [len(tensor_list)] + max_size\n        b, c, h, w = batch_shape\n        dtype = tensor_list[0].dtype\n        device = tensor_list[0].device\n        tensor = torch.zeros(batch_shape, dtype=dtype, device=device)\n        mask = torch.ones((b, h, w), dtype=torch.bool, device=device)\n        for img, pad_img, m in zip(tensor_list, tensor, mask):\n            pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)\n            m[: img.shape[1], :img.shape[2]] = False\n    else:\n        raise ValueError('not supported')\n    return NestedTensor(tensor, mask)\n\n\n# _onnx_nested_tensor_from_tensor_list() is an implementation of\n# nested_tensor_from_tensor_list() that is supported by ONNX tracing.\n@torch.jit.unused\ndef _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor:\n    max_size = []\n    for i in range(tensor_list[0].dim()):\n        max_size_i = torch.max(torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)).to(torch.int64)\n        max_size.append(max_size_i)\n    max_size = tuple(max_size)\n\n    # work around for\n    # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)\n    # m[: img.shape[1], :img.shape[2]] = False\n    # which is not yet supported in onnx\n    padded_imgs = []\n    padded_masks = []\n    for img in tensor_list:\n        padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))]\n        padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0]))\n        padded_imgs.append(padded_img)\n\n        m = torch.zeros_like(img[0], dtype=torch.int, device=img.device)\n        padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), \"constant\", 1)\n        padded_masks.append(padded_mask.to(torch.bool))\n\n    tensor = torch.stack(padded_imgs)\n    mask = torch.stack(padded_masks)\n\n    return NestedTensor(tensor, mask=mask)\n\n\ndef setup_for_distributed(is_master):\n    \"\"\"\n    This function disables printing when not in master process\n    \"\"\"\n    import builtins as __builtin__\n    builtin_print = __builtin__.print\n\n    def print(*args, **kwargs):\n        force = kwargs.pop('force', False)\n        if is_master or force:\n            builtin_print(*args, **kwargs)\n\n    __builtin__.print = print\n\n\ndef is_dist_avail_and_initialized():\n    if not dist.is_available():\n        return False\n    if not dist.is_initialized():\n        return False\n    return True\n\n\ndef get_world_size():\n    if not is_dist_avail_and_initialized():\n        return 1\n    return dist.get_world_size()\n\n\ndef get_rank():\n    if not is_dist_avail_and_initialized():\n        return 0\n    return dist.get_rank()\n\n\ndef is_main_process():\n    return get_rank() == 0\n\n\ndef save_on_master(*args, **kwargs):\n    if is_main_process():\n        torch.save(*args, **kwargs)\n\n\ndef init_distributed_mode(args):\n    if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:\n        args.rank = int(os.environ[\"RANK\"])\n        args.world_size = int(os.environ['WORLD_SIZE'])\n        args.gpu = int(os.environ['LOCAL_RANK'])\n    elif 'SLURM_PROCID' in os.environ:\n        args.rank = int(os.environ['SLURM_PROCID'])\n        args.gpu = args.rank % torch.cuda.device_count()\n    else:\n        print('Not using distributed mode')\n        args.distributed = False\n        return\n\n    args.distributed = True\n\n    torch.cuda.set_device(args.gpu)\n    args.dist_backend = 'nccl'\n    print('| distributed init (rank {}): {}'.format(\n        args.rank, args.dist_url), flush=True)\n    torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,\n                                         world_size=args.world_size, rank=args.rank)\n    torch.distributed.barrier()\n    setup_for_distributed(args.rank == 0)\n\n\n@torch.no_grad()\ndef accuracy(output, target, topk=(1,)):\n    \"\"\"Computes the precision@k for the specified values of k\"\"\"\n    if target.numel() == 0:\n        return [torch.zeros([], device=output.device)]\n    maxk = max(topk)\n    batch_size = target.size(0)\n\n    _, pred = output.topk(maxk, 1, True, True)\n    pred = pred.t()\n    correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n    res = []\n    for k in topk:\n        correct_k = correct[:k].view(-1).float().sum(0)\n        res.append(correct_k.mul_(100.0 / batch_size))\n    return res\n\n\ndef interpolate(input, size=None, scale_factor=None, mode=\"nearest\", align_corners=None):\n    # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor\n    \"\"\"\n    Equivalent to nn.functional.interpolate, but with support for empty batch sizes.\n    This will eventually be supported natively by PyTorch, and this\n    class can go away.\n    \"\"\"\n    if version.parse(torchvision.__version__) < version.parse('0.7'):\n        if input.numel() > 0:\n            return torch.nn.functional.interpolate(\n                input, size, scale_factor, mode, align_corners\n            )\n\n        output_shape = _output_size(2, input, size, scale_factor)\n        output_shape = list(input.shape[:-2]) + list(output_shape)\n        return _new_empty_tensor(input, output_shape)\n    else:\n        return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners)\n"
  },
  {
    "path": "util/plot_utils.py",
    "content": "\"\"\"\nPlotting utilities to visualize training logs.\n\"\"\"\nimport torch\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom pathlib import Path, PurePath\n\n\ndef plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'):\n    '''\n    Function to plot specific fields from training log(s). Plots both training and test results.\n\n    :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file\n              - fields = which results to plot from each log file - plots both training and test for each field.\n              - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots\n              - log_name = optional, name of log file if different than default 'log.txt'.\n\n    :: Outputs - matplotlib plots of results in fields, color coded for each log file.\n               - solid lines are training results, dashed lines are test results.\n\n    '''\n    func_name = \"plot_utils.py::plot_logs\"\n\n    # verify logs is a list of Paths (list[Paths]) or single Pathlib object Path,\n    # convert single Path to list to avoid 'not iterable' error\n\n    if not isinstance(logs, list):\n        if isinstance(logs, PurePath):\n            logs = [logs]\n            print(f\"{func_name} info: logs param expects a list argument, converted to list[Path].\")\n        else:\n            raise ValueError(f\"{func_name} - invalid argument for logs parameter.\\n \\\n            Expect list[Path] or single Path obj, received {type(logs)}\")\n\n    # Quality checks - verify valid dir(s), that every item in list is Path object, and that log_name exists in each dir\n    for i, dir in enumerate(logs):\n        if not isinstance(dir, PurePath):\n            raise ValueError(f\"{func_name} - non-Path object in logs argument of {type(dir)}: \\n{dir}\")\n        if not dir.exists():\n            raise ValueError(f\"{func_name} - invalid directory in logs argument:\\n{dir}\")\n        # verify log_name exists\n        fn = Path(dir / log_name)\n        if not fn.exists():\n            print(f\"-> missing {log_name}.  Have you gotten to Epoch 1 in training?\")\n            print(f\"--> full path of missing log file: {fn}\")\n            return\n\n    # load log file(s) and plot\n    dfs = [pd.read_json(Path(p) / log_name, lines=True) for p in logs]\n\n    fig, axs = plt.subplots(ncols=len(fields), figsize=(16, 5))\n\n    for df, color in zip(dfs, sns.color_palette(n_colors=len(logs))):\n        for j, field in enumerate(fields):\n            if field == 'mAP':\n                coco_eval = pd.DataFrame(\n                    np.stack(df.test_coco_eval_bbox.dropna().values)[:, 1]\n                ).ewm(com=ewm_col).mean()\n                axs[j].plot(coco_eval, c=color)\n            else:\n                df.interpolate().ewm(com=ewm_col).mean().plot(\n                    y=[f'train_{field}', f'test_{field}'],\n                    ax=axs[j],\n                    color=[color] * 2,\n                    style=['-', '--']\n                )\n    for ax, field in zip(axs, fields):\n        ax.legend([Path(p).name for p in logs])\n        ax.set_title(field)\n\n\ndef plot_precision_recall(files, naming_scheme='iter'):\n    if naming_scheme == 'exp_id':\n        # name becomes exp_id\n        names = [f.parts[-3] for f in files]\n    elif naming_scheme == 'iter':\n        names = [f.stem for f in files]\n    else:\n        raise ValueError(f'not supported {naming_scheme}')\n    fig, axs = plt.subplots(ncols=2, figsize=(16, 5))\n    for f, color, name in zip(files, sns.color_palette(\"Blues\", n_colors=len(files)), names):\n        data = torch.load(f)\n        # precision is n_iou, n_points, n_cat, n_area, max_det\n        precision = data['precision']\n        recall = data['params'].recThrs\n        scores = data['scores']\n        # take precision for all classes, all areas and 100 detections\n        precision = precision[0, :, :, 0, -1].mean(1)\n        scores = scores[0, :, :, 0, -1].mean(1)\n        prec = precision.mean()\n        rec = data['recall'][0, :, 0, -1].mean()\n        print(f'{naming_scheme} {name}: mAP@50={prec * 100: 05.1f}, ' +\n              f'score={scores.mean():0.3f}, ' +\n              f'f1={2 * prec * rec / (prec + rec + 1e-8):0.3f}'\n              )\n        axs[0].plot(recall, precision, c=color)\n        axs[1].plot(recall, scores, c=color)\n\n    axs[0].set_title('Precision / Recall')\n    axs[0].legend(names)\n    axs[1].set_title('Scores / Recall')\n    axs[1].legend(names)\n    return fig, axs\n"
  }
]