[
  {
    "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 \n\nIn the context of this project, we do not expect pull requests. \nIf you find a bug, or would like to suggest an improvement, please open an issue.\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 [yyyy] [name of copyright owner]\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": ":new: *Please check out our more recent [DINOv2](https://github.com/facebookresearch/dinov2) effort in the same line of work.*\n\n# Self-Supervised Vision Transformers with DINO\n\nPyTorch implementation and pretrained models for DINO. For details, see **Emerging Properties in Self-Supervised Vision Transformers**.  \n[[`blogpost`](https://ai.facebook.com/blog/dino-paws-computer-vision-with-self-supervised-transformers-and-10x-more-efficient-training)] [[`arXiv`](https://arxiv.org/abs/2104.14294)] [[`Yannic Kilcher's video`](https://www.youtube.com/watch?v=h3ij3F3cPIk)]\n\n<div align=\"center\">\n  <img width=\"100%\" alt=\"DINO illustration\" src=\".github/dino.gif\">\n</div>\n\n## Pretrained models\nYou can choose to download only the weights of the pretrained backbone used for downstream tasks, or the full checkpoint which contains backbone and projection head weights for both student and teacher networks. We also provide the backbone in `onnx` format, as well as detailed arguments and training/evaluation logs. Note that `DeiT-S` and `ViT-S` names refer exactly to the same architecture.\n\n<table>\n  <tr>\n    <th>arch</th>\n    <th>params</th>\n    <th>k-nn</th>\n    <th>linear</th>\n    <th colspan=\"6\">download</th>\n  </tr>\n  <tr>\n    <td>ViT-S/16</td>\n    <td>21M</td>\n    <td>74.5%</td>\n    <td>77.0%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deits16.onnx\">onnx</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain_eval_linear_log.txt\">eval logs</a></td>\n  </tr>\n  <tr>\n    <td>ViT-S/8</td>\n    <td>21M</td>\n    <td>78.3%</td>\n    <td>79.7%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deits8.onnx\">onnx</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_pretrain_eval_linear_log.txt\">eval logs</a></td>\n  </tr>\n  <tr>\n    <td>ViT-B/16</td>\n    <td>85M</td>\n    <td>76.1%</td>\n    <td>78.2%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitb16.onnx\">onnx</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain_eval_linear_log.txt\">eval logs</a></td>\n  </tr>\n  <tr>\n    <td>ViT-B/8</td>\n    <td>85M</td>\n    <td>77.4%</td>\n    <td>80.1%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitb8.onnx\">onnx</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_pretrain_eval_linear_log.txt\">eval logs</a></td>\n  </tr>\n  <tr>\n    <td>ResNet-50</td>\n    <td>23M</td>\n    <td>67.5%</td>\n    <td>75.3%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50.onnx\">onnx</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50_pretrain_eval_linear_log.txt\">eval logs</a></td>\n  </tr>\n</table>\n\nWe also release XCiT models ([[`arXiv`](https://arxiv.org/abs/2106.09681)] [[`code`](https://github.com/facebookresearch/xcit)]) trained with DINO:\n<table>\n  <tr>\n    <th>arch</th>\n    <th>params</th>\n    <th>k-nn</th>\n    <th>linear</th>\n    <th colspan=\"5\">download</th>\n  </tr>\n  <tr>\n    <td>xcit_small_12_p16</td>\n    <td>26M</td>\n    <td>76.0%</td>\n    <td>77.8%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain_eval_linear_log.txt\">eval</a></td>\n  </tr>\n  <tr>\n    <td>xcit_small_12_p8</td>\n    <td>26M</td>\n    <td>77.1%</td>\n    <td>79.2%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain_eval_linear_log.txt\">eval</a></td>\n  </tr>\n  <tr>\n    <td>xcit_medium_24_p16</td>\n    <td>84M</td>\n    <td>76.4%</td>\n    <td>78.8%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain_eval_linear_log.txt\">eval</a></td>\n  </tr>\n  <tr>\n    <td>xcit_medium_24_p8</td>\n    <td>84M</td>\n    <td>77.9%</td>\n    <td>80.3%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain.pth\">backbone only</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain_full_checkpoint.pth\">full ckpt</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/args.txt\">args</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain_log.txt\">logs</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain_eval_linear_log.txt\">eval</a></td>\n  </tr>\n</table>\n\n### Pretrained models on PyTorch Hub\n```python\nimport torch\nvits16 = torch.hub.load('facebookresearch/dino:main', 'dino_vits16')\nvits8 = torch.hub.load('facebookresearch/dino:main', 'dino_vits8')\nvitb16 = torch.hub.load('facebookresearch/dino:main', 'dino_vitb16')\nvitb8 = torch.hub.load('facebookresearch/dino:main', 'dino_vitb8')\nxcit_small_12_p16 = torch.hub.load('facebookresearch/dino:main', 'dino_xcit_small_12_p16')\nxcit_small_12_p8 = torch.hub.load('facebookresearch/dino:main', 'dino_xcit_small_12_p8')\nxcit_medium_24_p16 = torch.hub.load('facebookresearch/dino:main', 'dino_xcit_medium_24_p16')\nxcit_medium_24_p8 = torch.hub.load('facebookresearch/dino:main', 'dino_xcit_medium_24_p8')\nresnet50 = torch.hub.load('facebookresearch/dino:main', 'dino_resnet50')\n```\n\n## Training\n\n### Documentation\nPlease install [PyTorch](https://pytorch.org/) and download the [ImageNet](https://imagenet.stanford.edu/) dataset. This codebase has been developed with python version 3.6, PyTorch version 1.7.1, CUDA 11.0 and torchvision 0.8.2. The exact arguments to reproduce the models presented in our paper can be found in the `args` column of the [pretrained models section](https://github.com/facebookresearch/dino#pretrained-models). For a glimpse at the full documentation of DINO training please run:\n```\npython main_dino.py --help\n```\n\n### Vanilla DINO training :sauropod:\nRun DINO with ViT-small network on a single node with 8 GPUs for 100 epochs with the following command. Training time is 1.75 day and the resulting checkpoint should reach 69.3% on k-NN eval and 74.0% on linear eval. We provide [training](https://dl.fbaipublicfiles.com/dino/example_runs_logs/dino_vanilla_deitsmall16_log.txt) and [linear evaluation](https://dl.fbaipublicfiles.com/dino/example_runs_logs/dino_vanilla_deitsmall16_eval.txt) logs (with batch size 256 at evaluation time) for this run to help reproducibility.\n```\npython -m torch.distributed.launch --nproc_per_node=8 main_dino.py --arch vit_small --data_path /path/to/imagenet/train --output_dir /path/to/saving_dir\n```\n\n### Multi-node training\nWe use Slurm and [submitit](https://github.com/facebookincubator/submitit) (`pip install submitit`). To train on 2 nodes with 8 GPUs each (total 16 GPUs):\n```\npython run_with_submitit.py --nodes 2 --ngpus 8 --arch vit_small --data_path /path/to/imagenet/train --output_dir /path/to/saving_dir\n```\n\n<details>\n<summary>\nDINO with ViT-base network.\n</summary>\n\n```\npython run_with_submitit.py --nodes 2 --ngpus 8 --use_volta32 --arch vit_base  --data_path /path/to/imagenet/train --output_dir /path/to/saving_dir\n```\n\n</details>\n\n### Boosting DINO performance :t-rex:\nYou can improve the performance of the vanilla run by:\n- training for more epochs: `--epochs 300`,\n- increasing the teacher temperature: `--teacher_temp 0.07 --warmup_teacher_temp_epochs 30`.\n- removing last layer normalization (only safe with `--arch vit_small`): `--norm_last_layer false`,\n\n<details>\n<summary>\nFull command.\n</summary>\n\n```\npython run_with_submitit.py --arch vit_small --epochs 300 --teacher_temp 0.07 --warmup_teacher_temp_epochs 30 --norm_last_layer false --data_path /path/to/imagenet/train --output_dir /path/to/saving_dir\n```\n\n</details>\n\nThe resulting pretrained model should reach 73.3% on k-NN eval and 76.0% on linear eval. Training time is 2.6 days with 16 GPUs. We provide [training](https://dl.fbaipublicfiles.com/dino/example_runs_logs/dino_boost_deitsmall16_log.txt) and [linear evaluation](https://dl.fbaipublicfiles.com/dino/example_runs_logs/dino_boost_deitsmall16_eval.txt) logs (with batch size 256 at evaluation time) for this run to help reproducibility.\n\n### ResNet-50 and other convnets trainings\nThis code also works for training DINO on convolutional networks, like ResNet-50 for example. We highly recommend to adapt some optimization arguments in this case. For example following is a command to train DINO on ResNet-50 on a single node with 8 GPUs for 100 epochs. We provide [training logs](https://dl.fbaipublicfiles.com/dino/example_runs_logs/dino_rn50_log.txt) and [final checkpoint](https://dl.fbaipublicfiles.com/dino/example_runs_logs/dino_rn50_checkpoint.pth) for this run.\n```\npython -m torch.distributed.launch --nproc_per_node=8 main_dino.py --arch resnet50 --optimizer sgd --lr 0.03 --weight_decay 1e-4 --weight_decay_end 1e-4 --global_crops_scale 0.14 1 --local_crops_scale 0.05 0.14 --data_path /path/to/imagenet/train --output_dir /path/to/saving_dir\n```\n\n## Self-attention visualization\nYou can look at the self-attention of the [CLS] token on the different heads of the last layer by running:\n```\npython visualize_attention.py\n```\n\n<div align=\"center\">\n  <img width=\"100%\" alt=\"Self-attention from a Vision Transformer with 8x8 patches trained with DINO\" src=\".github/attention_maps.png\">\n</div>\n\n## Self-attention video generation\nYou can generate videos like the one on the blog post with `video_generation.py`.\n\nhttps://user-images.githubusercontent.com/46140458/116817761-47885e80-ab68-11eb-9975-d61d5a919e13.mp4\n\nExtract frames from input video and generate attention video:\n```\npython video_generation.py  --pretrained_weights dino_deitsmall8_pretrain.pth \\\n    --input_path input/video.mp4 \\\n    --output_path output/ \\\n    --fps 25\n```\n\nUse folder of frames already extracted and generate attention video:\n```\npython video_generation.py  --pretrained_weights dino_deitsmall8_pretrain.pth \\\n    --input_path output/frames/ \\\n    --output_path output/ \\\n    --resize 256 \\\n```\n\nOnly generate video from folder of attention maps images:\n```\npython video_generation.py --input_path output/attention \\\n    --output_path output/ \\\n    --video_only \\\n    --video_format avi\n```\n\n\n## Evaluation: k-NN classification on ImageNet\nTo evaluate a simple k-NN classifier with a single GPU on a pre-trained model, run:\n```\npython -m torch.distributed.launch --nproc_per_node=1 eval_knn.py --data_path /path/to/imagenet\n```\nIf you choose not to specify `--pretrained_weights`, then DINO reference weights are used by default. If you want instead to evaluate checkpoints from a run of your own, you can run for example:\n```\npython -m torch.distributed.launch --nproc_per_node=1 eval_knn.py --pretrained_weights /path/to/checkpoint.pth --checkpoint_key teacher --data_path /path/to/imagenet \n```\n\n## Evaluation: Linear classification on ImageNet\nTo train a supervised linear classifier on frozen weights on a single node with 8 gpus, run:\n```\npython -m torch.distributed.launch --nproc_per_node=8 eval_linear.py --data_path /path/to/imagenet\n```\n\nWe release the logs and weights from evaluating the different models:\n\n<table>\n  <tr>\n    <th>arch</th>\n    <th>top-1 ImageNet</th>\n    <th colspan=\"2\">linear evaluation</th>\n  </tr>\n  <tr>\n    <td>ViT-S/16</td>\n    <td>77.0%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>ViT-S/8</td>\n    <td>79.7%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>ViT-B/16</td>\n    <td>78.2%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>ViT-B/8</td>\n    <td>80.1%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>xcit_small_12_p16</td>\n    <td>77.8%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>xcit_small_12_p8</td>\n    <td>79.2%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>xcit_medium_24_p16</td>\n    <td>78.8%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>xcit_medium_24_p8</td>\n    <td>80.3%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n  <tr>\n    <td>ResNet-50</td>\n    <td>75.3%</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50_linearweights.pth\">linear weights</a></td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50_pretrain_eval_linear_log.txt\">logs</a></td>\n  </tr>\n</table>\n\nYou can check the performance of the pretrained weights on ImageNet validation set by running the following command lines:\n```\npython eval_linear.py --evaluate --arch vit_small --patch_size 16 --data_path /path/to/imagenet/train\n```\n\n```\npython eval_linear.py --evaluate --arch vit_small --patch_size 8 --data_path /path/to/imagenet/train\n```\n\n```\npython eval_linear.py --evaluate --arch vit_base --patch_size 16 --n_last_blocks 1 --avgpool_patchtokens true --data_path /path/to/imagenet/train\n```\n\n```\npython eval_linear.py --evaluate --arch vit_base --patch_size 8 --n_last_blocks 1 --avgpool_patchtokens true --data_path /path/to/imagenet/train\n```\n\n```\npython eval_linear.py --evaluate --arch resnet50 --data_path /path/to/imagenet/train\n```\n\n## Evaluation: DAVIS 2017 Video object segmentation\nPlease verify that you're using pytorch version 1.7.1 since we are not able to reproduce the results with most recent pytorch 1.8.1 at the moment.\n\n**Step 1: Prepare DAVIS 2017 data**  \n```\ncd $HOME\ngit clone https://github.com/davisvideochallenge/davis-2017 && cd davis-2017\n./data/get_davis.sh\n```\n\n**Step 2: Video object segmentation**  \n```\npython eval_video_segmentation.py --data_path $HOME/davis-2017/DAVIS/ --output_dir /path/to/saving_dir\n```\n\n**Step 3: Evaluate the obtained segmentation**  \n```\ngit clone https://github.com/davisvideochallenge/davis2017-evaluation $HOME/davis2017-evaluation\npython $HOME/davis2017-evaluation/evaluation_method.py --task semi-supervised --results_path /path/to/saving_dir --davis_path $HOME/davis-2017/DAVIS/\n```\n\n## Evaluation: Image Retrieval on revisited Oxford and Paris\nStep 1: Prepare revisited Oxford and Paris by following [this repo](https://github.com/filipradenovic/revisitop).\n\nStep 2: Image retrieval (if you do not specify weights with `--pretrained_weights` then by default [DINO weights pretrained on Google Landmark v2 dataset](https://dl.fbaipublicfiles.com/dino/dino_vitsmall16_googlelandmark_pretrain/dino_vitsmall16_googlelandmark_pretrain.pth) will be used).\n\nParis:\n```\npython -m torch.distributed.launch --use_env --nproc_per_node=1 eval_image_retrieval.py --imsize 512 --multiscale 1 --data_path /path/to/revisited_paris_oxford/ --dataset rparis6k\n```\n\nOxford:\n```\npython -m torch.distributed.launch --use_env --nproc_per_node=1 eval_image_retrieval.py --imsize 224 --multiscale 0 --data_path /path/to/revisited_paris_oxford/ --dataset roxford5k\n```\n\n## Evaluation: Copy detection on Copydays\nStep 1: Prepare [Copydays dataset](https://lear.inrialpes.fr/~jegou/data.php#copydays).\n\nStep 2 (opt): Prepare a set of image distractors and a set of images on which to learn the whitening operator.\nIn our paper, we use 10k random images from YFCC100M as distractors and 20k random images from YFCC100M (different from the distractors) for computing the whitening operation.\n\nStep 3: Run copy detection:\n```\npython -m torch.distributed.launch --use_env --nproc_per_node=1 eval_copy_detection.py --data_path /path/to/copydays/ --whitening_path /path/to/whitening_data/ --distractors_path /path/to/distractors/\n```\nWe report result on the strong subset. For example in the stdout from the command above we get: `eval on strong mAP=0.858`.\n\n## License\nThis repository is released under the Apache 2.0 license as found in the [LICENSE](LICENSE) file.\n\n## Citation\nIf you find this repository useful, please consider giving a star :star: and citation :t-rex::\n```\n@inproceedings{caron2021emerging,\n  title={Emerging Properties in Self-Supervised Vision Transformers},\n  author={Caron, Mathilde and Touvron, Hugo and Misra, Ishan and J\\'egou, Herv\\'e  and Mairal, Julien and Bojanowski, Piotr and Joulin, Armand},\n  booktitle={Proceedings of the International Conference on Computer Vision (ICCV)},\n  year={2021}\n}\n```\n"
  },
  {
    "path": "eval_copy_detection.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport os\nimport sys\nimport pickle\nimport argparse\n\nimport torch\nfrom torch import nn\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nfrom torchvision import models as torchvision_models\nfrom torchvision import transforms as pth_transforms\nfrom PIL import Image, ImageFile\nimport numpy as np\n\nimport utils\nimport vision_transformer as vits\nfrom eval_knn import extract_features\n\n\nclass CopydaysDataset():\n    def __init__(self, basedir):\n        self.basedir = basedir\n        self.block_names = (\n            ['original', 'strong'] +\n            ['jpegqual/%d' % i for i in\n             [3, 5, 8, 10, 15, 20, 30, 50, 75]] +\n            ['crops/%d' % i for i in\n             [10, 15, 20, 30, 40, 50, 60, 70, 80]])\n        self.nblocks = len(self.block_names)\n\n        self.query_blocks = range(self.nblocks)\n        self.q_block_sizes = np.ones(self.nblocks, dtype=int) * 157\n        self.q_block_sizes[1] = 229\n        # search only among originals\n        self.database_blocks = [0]\n\n    def get_block(self, i):\n        dirname = self.basedir + '/' + self.block_names[i]\n        fnames = [dirname + '/' + fname\n                  for fname in sorted(os.listdir(dirname))\n                  if fname.endswith('.jpg')]\n        return fnames\n\n    def get_block_filenames(self, subdir_name):\n        dirname = self.basedir + '/' + subdir_name\n        return [fname\n                for fname in sorted(os.listdir(dirname))\n                if fname.endswith('.jpg')]\n\n    def eval_result(self, ids, distances):\n        j0 = 0\n        for i in range(self.nblocks):\n            j1 = j0 + self.q_block_sizes[i]\n            block_name = self.block_names[i]\n            I = ids[j0:j1]   # block size\n            sum_AP = 0\n            if block_name != 'strong':\n                # 1:1 mapping of files to names\n                positives_per_query = [[i] for i in range(j1 - j0)]\n            else:\n                originals = self.get_block_filenames('original')\n                strongs = self.get_block_filenames('strong')\n\n                # check if prefixes match\n                positives_per_query = [\n                    [j for j, bname in enumerate(originals)\n                     if bname[:4] == qname[:4]]\n                    for qname in strongs]\n\n            for qno, Iline in enumerate(I):\n                positives = positives_per_query[qno]\n                ranks = []\n                for rank, bno in enumerate(Iline):\n                    if bno in positives:\n                        ranks.append(rank)\n                sum_AP += score_ap_from_ranks_1(ranks, len(positives))\n\n            print(\"eval on %s mAP=%.3f\" % (\n                block_name, sum_AP / (j1 - j0)))\n            j0 = j1\n\n\n# from the Holidays evaluation package\ndef score_ap_from_ranks_1(ranks, nres):\n    \"\"\" Compute the average precision of one search.\n    ranks = ordered list of ranks of true positives\n    nres  = total number of positives in dataset\n    \"\"\"\n\n    # accumulate trapezoids in PR-plot\n    ap = 0.0\n\n    # All have an x-size of:\n    recall_step = 1.0 / nres\n\n    for ntp, rank in enumerate(ranks):\n\n        # y-size on left side of trapezoid:\n        # ntp = nb of true positives so far\n        # rank = nb of retrieved items so far\n        if rank == 0:\n            precision_0 = 1.0\n        else:\n            precision_0 = ntp / float(rank)\n\n        # y-size on right side of trapezoid:\n        # ntp and rank are increased by one\n        precision_1 = (ntp + 1) / float(rank + 1)\n\n        ap += (precision_1 + precision_0) * recall_step / 2.0\n\n    return ap\n\n\nclass ImgListDataset(torch.utils.data.Dataset):\n    def __init__(self, img_list, transform=None):\n        self.samples = img_list\n        self.transform = transform\n\n    def __getitem__(self, i):\n        with open(self.samples[i], 'rb') as f:\n            img = Image.open(f)\n            img = img.convert('RGB')\n        if self.transform is not None:\n            img = self.transform(img)\n        return img, i\n\n    def __len__(self):\n        return len(self.samples)\n\n\ndef is_image_file(s):\n    ext = s.split(\".\")[-1]\n    if ext in ['jpg', 'jpeg', 'png', 'ppm', 'bmp', 'pgm', 'tif', 'tiff', 'webp']:\n        return True\n    return False\n\n\n@torch.no_grad()\ndef extract_features(image_list, model, args):\n    transform = pth_transforms.Compose([\n        pth_transforms.Resize((args.imsize, args.imsize), interpolation=3),\n        pth_transforms.ToTensor(),\n        pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n    ])\n    tempdataset = ImgListDataset(image_list, transform=transform)\n    data_loader = torch.utils.data.DataLoader(tempdataset, batch_size=args.batch_size_per_gpu,\n        num_workers=args.num_workers, drop_last=False,\n        sampler=torch.utils.data.DistributedSampler(tempdataset, shuffle=False))\n    features = None\n    for samples, index in utils.MetricLogger(delimiter=\"  \").log_every(data_loader, 10):\n        samples, index = samples.cuda(non_blocking=True), index.cuda(non_blocking=True)\n        feats = model.get_intermediate_layers(samples, n=1)[0].clone()\n\n        cls_output_token = feats[:, 0, :]  #  [CLS] token\n        # GeM with exponent 4 for output patch tokens\n        b, h, w, d = len(samples), int(samples.shape[-2] / model.patch_embed.patch_size), int(samples.shape[-1] / model.patch_embed.patch_size), feats.shape[-1]\n        feats = feats[:, 1:, :].reshape(b, h, w, d)\n        feats = feats.clamp(min=1e-6).permute(0, 3, 1, 2)\n        feats = nn.functional.avg_pool2d(feats.pow(4), (h, w)).pow(1. / 4).reshape(b, -1)\n        # concatenate [CLS] token and GeM pooled patch tokens\n        feats = torch.cat((cls_output_token, feats), dim=1)\n\n        # init storage feature matrix\n        if dist.get_rank() == 0 and features is None:\n            features = torch.zeros(len(data_loader.dataset), feats.shape[-1])\n            if args.use_cuda:\n                features = features.cuda(non_blocking=True)\n\n        # get indexes from all processes\n        y_all = torch.empty(dist.get_world_size(), index.size(0), dtype=index.dtype, device=index.device)\n        y_l = list(y_all.unbind(0))\n        y_all_reduce = torch.distributed.all_gather(y_l, index, async_op=True)\n        y_all_reduce.wait()\n        index_all = torch.cat(y_l)\n\n        # share features between processes\n        feats_all = torch.empty(dist.get_world_size(), feats.size(0), feats.size(1),\n                                dtype=feats.dtype, device=feats.device)\n        output_l = list(feats_all.unbind(0))\n        output_all_reduce = torch.distributed.all_gather(output_l, feats, async_op=True)\n        output_all_reduce.wait()\n\n        # update storage feature matrix\n        if dist.get_rank() == 0:\n            if args.use_cuda:\n                features.index_copy_(0, index_all, torch.cat(output_l))\n            else:\n                features.index_copy_(0, index_all.cpu(), torch.cat(output_l).cpu())\n    return features  # features is still None for every rank which is not 0 (main)\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('Copy detection on Copydays')\n    parser.add_argument('--data_path', default='/path/to/copydays/', type=str,\n        help=\"See https://lear.inrialpes.fr/~jegou/data.php#copydays\")\n    parser.add_argument('--whitening_path', default='/path/to/whitening_data/', type=str,\n        help=\"\"\"Path to directory with images used for computing the whitening operator.\n        In our paper, we use 20k random images from YFCC100M.\"\"\")\n    parser.add_argument('--distractors_path', default='/path/to/distractors/', type=str,\n        help=\"Path to directory with distractors images. In our paper, we use 10k random images from YFCC100M.\")\n    parser.add_argument('--imsize', default=320, type=int, help='Image size (square image)')\n    parser.add_argument('--batch_size_per_gpu', default=16, type=int, help='Per-GPU batch-size')\n    parser.add_argument('--pretrained_weights', default='', type=str, help=\"Path to pretrained weights to evaluate.\")\n    parser.add_argument('--use_cuda', default=True, type=utils.bool_flag)\n    parser.add_argument('--arch', default='vit_base', type=str, help='Architecture')\n    parser.add_argument('--patch_size', default=8, type=int, help='Patch resolution of the model.')\n    parser.add_argument(\"--checkpoint_key\", default=\"teacher\", type=str,\n        help='Key to use in the checkpoint (example: \"teacher\")')\n    parser.add_argument('--num_workers', default=10, type=int, help='Number of data loading workers per GPU.')\n    parser.add_argument(\"--dist_url\", default=\"env://\", type=str, help=\"\"\"url used to set up\n        distributed training; see https://pytorch.org/docs/stable/distributed.html\"\"\")\n    parser.add_argument(\"--local_rank\", default=0, type=int, help=\"Please ignore and do not set this argument.\")\n    args = parser.parse_args()\n\n    utils.init_distributed_mode(args)\n    print(\"git:\\n  {}\\n\".format(utils.get_sha()))\n    print(\"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())))\n    cudnn.benchmark = True\n\n    # ============ building network ... ============\n    if \"vit\" in args.arch:\n        model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0)\n        print(f\"Model {args.arch} {args.patch_size}x{args.patch_size} built.\")\n    else:\n        print(f\"Architecture {args.arch} non supported\")\n        sys.exit(1)\n    if args.use_cuda:\n        model.cuda()\n    model.eval()\n    utils.load_pretrained_weights(model, args.pretrained_weights, args.checkpoint_key, args.arch, args.patch_size)\n\n    dataset = CopydaysDataset(args.data_path)\n\n    # ============ Extract features ... ============\n    # extract features for queries\n    queries = []\n    for q in dataset.query_blocks:\n        queries.append(extract_features(dataset.get_block(q), model, args))\n    if utils.get_rank() == 0:\n        queries = torch.cat(queries)\n        print(f\"Extraction of queries features done. Shape: {queries.shape}\")\n\n    # extract features for database\n    database = []\n    for b in dataset.database_blocks:\n        database.append(extract_features(dataset.get_block(b), model, args))\n\n    # extract features for distractors\n    if os.path.isdir(args.distractors_path):\n        print(\"Using distractors...\")\n        list_distractors = [os.path.join(args.distractors_path, s) for s in os.listdir(args.distractors_path) if is_image_file(s)]\n        database.append(extract_features(list_distractors, model, args))\n    if utils.get_rank() == 0:\n        database = torch.cat(database)\n        print(f\"Extraction of database and distractors features done. Shape: {database.shape}\")\n\n    # ============ Whitening ... ============\n    if os.path.isdir(args.whitening_path):\n        print(f\"Extracting features on images from {args.whitening_path} for learning the whitening operator.\")\n        list_whit = [os.path.join(args.whitening_path, s) for s in os.listdir(args.whitening_path) if is_image_file(s)]\n        features_for_whitening = extract_features(list_whit, model, args)\n        if utils.get_rank() == 0:\n            # center\n            mean_feature = torch.mean(features_for_whitening, dim=0)\n            database -= mean_feature\n            queries -= mean_feature\n            pca = utils.PCA(dim=database.shape[-1], whit=0.5)\n            # compute covariance\n            cov = torch.mm(features_for_whitening.T, features_for_whitening) / features_for_whitening.shape[0]\n            pca.train_pca(cov.cpu().numpy())\n            database = pca.apply(database)\n            queries = pca.apply(queries)\n\n    # ============ Copy detection ... ============\n    if utils.get_rank() == 0:\n        # l2 normalize the features\n        database = nn.functional.normalize(database, dim=1, p=2)\n        queries = nn.functional.normalize(queries, dim=1, p=2)\n\n        # similarity\n        similarity = torch.mm(queries, database.T)\n        distances, indices = similarity.topk(20, largest=True, sorted=True)\n\n        # evaluate\n        retrieved = dataset.eval_result(indices, distances)\n    dist.barrier()\n\n"
  },
  {
    "path": "eval_image_retrieval.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport os\nimport sys\nimport pickle\nimport argparse\n\nimport torch\nfrom torch import nn\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nfrom torchvision import models as torchvision_models\nfrom torchvision import transforms as pth_transforms\nfrom PIL import Image, ImageFile\nimport numpy as np\n\nimport utils\nimport vision_transformer as vits\nfrom eval_knn import extract_features\n\n\nclass OxfordParisDataset(torch.utils.data.Dataset):\n    def __init__(self, dir_main, dataset, split, transform=None, imsize=None):\n        if dataset not in ['roxford5k', 'rparis6k']:\n            raise ValueError('Unknown dataset: {}!'.format(dataset))\n\n        # loading imlist, qimlist, and gnd, in cfg as a dict\n        gnd_fname = os.path.join(dir_main, dataset, 'gnd_{}.pkl'.format(dataset))\n        with open(gnd_fname, 'rb') as f:\n            cfg = pickle.load(f)\n        cfg['gnd_fname'] = gnd_fname\n        cfg['ext'] = '.jpg'\n        cfg['qext'] = '.jpg'\n        cfg['dir_data'] = os.path.join(dir_main, dataset)\n        cfg['dir_images'] = os.path.join(cfg['dir_data'], 'jpg')\n        cfg['n'] = len(cfg['imlist'])\n        cfg['nq'] = len(cfg['qimlist'])\n        cfg['im_fname'] = config_imname\n        cfg['qim_fname'] = config_qimname\n        cfg['dataset'] = dataset\n        self.cfg = cfg\n\n        self.samples = cfg[\"qimlist\"] if split == \"query\" else cfg[\"imlist\"]\n        self.transform = transform\n        self.imsize = imsize\n\n    def __len__(self):\n        return len(self.samples)\n\n    def __getitem__(self, index):\n        path = os.path.join(self.cfg[\"dir_images\"], self.samples[index] + \".jpg\")\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with open(path, 'rb') as f:\n            img = Image.open(f)\n            img = img.convert('RGB')\n        if self.imsize is not None:\n            img.thumbnail((self.imsize, self.imsize), Image.ANTIALIAS)\n        if self.transform is not None:\n            img = self.transform(img)\n        return img, index\n\n\ndef config_imname(cfg, i):\n    return os.path.join(cfg['dir_images'], cfg['imlist'][i] + cfg['ext'])\n\n\ndef config_qimname(cfg, i):\n    return os.path.join(cfg['dir_images'], cfg['qimlist'][i] + cfg['qext'])\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('Image Retrieval on revisited Paris and Oxford')\n    parser.add_argument('--data_path', default='/path/to/revisited_paris_oxford/', type=str)\n    parser.add_argument('--dataset', default='roxford5k', type=str, choices=['roxford5k', 'rparis6k'])\n    parser.add_argument('--multiscale', default=False, type=utils.bool_flag)\n    parser.add_argument('--imsize', default=224, type=int, help='Image size')\n    parser.add_argument('--pretrained_weights', default='', type=str, help=\"Path to pretrained weights to evaluate.\")\n    parser.add_argument('--use_cuda', default=True, type=utils.bool_flag)\n    parser.add_argument('--arch', default='vit_small', type=str, help='Architecture')\n    parser.add_argument('--patch_size', default=16, type=int, help='Patch resolution of the model.')\n    parser.add_argument(\"--checkpoint_key\", default=\"teacher\", type=str,\n        help='Key to use in the checkpoint (example: \"teacher\")')\n    parser.add_argument('--num_workers', default=10, type=int, help='Number of data loading workers per GPU.')\n    parser.add_argument(\"--dist_url\", default=\"env://\", type=str, help=\"\"\"url used to set up\n        distributed training; see https://pytorch.org/docs/stable/distributed.html\"\"\")\n    parser.add_argument(\"--local_rank\", default=0, type=int, help=\"Please ignore and do not set this argument.\")\n    args = parser.parse_args()\n\n    utils.init_distributed_mode(args)\n    print(\"git:\\n  {}\\n\".format(utils.get_sha()))\n    print(\"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())))\n    cudnn.benchmark = True\n\n    # ============ preparing data ... ============\n    transform = pth_transforms.Compose([\n        pth_transforms.ToTensor(),\n        pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n    ])\n    dataset_train = OxfordParisDataset(args.data_path, args.dataset, split=\"train\", transform=transform, imsize=args.imsize)\n    dataset_query = OxfordParisDataset(args.data_path, args.dataset, split=\"query\", transform=transform, imsize=args.imsize)\n    sampler = torch.utils.data.DistributedSampler(dataset_train, shuffle=False)\n    data_loader_train = torch.utils.data.DataLoader(\n        dataset_train,\n        sampler=sampler,\n        batch_size=1,\n        num_workers=args.num_workers,\n        pin_memory=True,\n        drop_last=False,\n    )\n    data_loader_query = torch.utils.data.DataLoader(\n        dataset_query,\n        batch_size=1,\n        num_workers=args.num_workers,\n        pin_memory=True,\n        drop_last=False,\n    )\n    print(f\"train: {len(dataset_train)} imgs / query: {len(dataset_query)} imgs\")\n\n    # ============ building network ... ============\n    if \"vit\" in args.arch:\n        model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0)\n        print(f\"Model {args.arch} {args.patch_size}x{args.patch_size} built.\")\n    elif \"xcit\" in args.arch:\n        model = torch.hub.load('facebookresearch/xcit:main', args.arch, num_classes=0)\n    elif args.arch in torchvision_models.__dict__.keys():\n        model = torchvision_models.__dict__[args.arch](num_classes=0)\n    else:\n        print(f\"Architecture {args.arch} non supported\")\n        sys.exit(1)\n    if args.use_cuda:\n        model.cuda()\n    model.eval()\n\n    # load pretrained weights\n    if os.path.isfile(args.pretrained_weights):\n        state_dict = torch.load(args.pretrained_weights, map_location=\"cpu\")\n        if args.checkpoint_key is not None and args.checkpoint_key in state_dict:\n            print(f\"Take key {args.checkpoint_key} in provided checkpoint dict\")\n            state_dict = state_dict[args.checkpoint_key]\n        # remove `module.` prefix\n        state_dict = {k.replace(\"module.\", \"\"): v for k, v in state_dict.items()}\n        # remove `backbone.` prefix induced by multicrop wrapper\n        state_dict = {k.replace(\"backbone.\", \"\"): v for k, v in state_dict.items()}\n        msg = model.load_state_dict(state_dict, strict=False)\n        print('Pretrained weights found at {} and loaded with msg: {}'.format(args.pretrained_weights, msg))\n    elif args.arch == \"vit_small\" and args.patch_size == 16:\n        print(\"Since no pretrained weights have been provided, we load pretrained DINO weights on Google Landmark v2.\")\n        model.load_state_dict(torch.hub.load_state_dict_from_url(url=\"https://dl.fbaipublicfiles.com/dino/dino_vitsmall16_googlelandmark_pretrain/dino_vitsmall16_googlelandmark_pretrain.pth\"))\n    else:\n        print(\"Warning: We use random weights.\")\n\n    ############################################################################\n    # Step 1: extract features\n    train_features = extract_features(model, data_loader_train, args.use_cuda, multiscale=args.multiscale)\n    query_features = extract_features(model, data_loader_query, args.use_cuda, multiscale=args.multiscale)\n\n    if utils.get_rank() == 0:  # only rank 0 will work from now on\n        # normalize features\n        train_features = nn.functional.normalize(train_features, dim=1, p=2)\n        query_features = nn.functional.normalize(query_features, dim=1, p=2)\n\n        ############################################################################\n        # Step 2: similarity\n        sim = torch.mm(train_features, query_features.T)\n        ranks = torch.argsort(-sim, dim=0).cpu().numpy()\n\n        ############################################################################\n        # Step 3: evaluate\n        gnd = dataset_train.cfg['gnd']\n        # evaluate ranks\n        ks = [1, 5, 10]\n        # search for easy & hard\n        gnd_t = []\n        for i in range(len(gnd)):\n            g = {}\n            g['ok'] = np.concatenate([gnd[i]['easy'], gnd[i]['hard']])\n            g['junk'] = np.concatenate([gnd[i]['junk']])\n            gnd_t.append(g)\n        mapM, apsM, mprM, prsM = utils.compute_map(ranks, gnd_t, ks)\n        # search for hard\n        gnd_t = []\n        for i in range(len(gnd)):\n            g = {}\n            g['ok'] = np.concatenate([gnd[i]['hard']])\n            g['junk'] = np.concatenate([gnd[i]['junk'], gnd[i]['easy']])\n            gnd_t.append(g)\n        mapH, apsH, mprH, prsH = utils.compute_map(ranks, gnd_t, ks)\n        print('>> {}: mAP M: {}, H: {}'.format(args.dataset, np.around(mapM*100, decimals=2), np.around(mapH*100, decimals=2)))\n        print('>> {}: mP@k{} M: {}, H: {}'.format(args.dataset, np.array(ks), np.around(mprM*100, decimals=2), np.around(mprH*100, decimals=2)))\n    dist.barrier()\n"
  },
  {
    "path": "eval_knn.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport os\nimport sys\nimport argparse\n\nimport torch\nfrom torch import nn\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nfrom torchvision import datasets\nfrom torchvision import transforms as pth_transforms\nfrom torchvision import models as torchvision_models\n\nimport utils\nimport vision_transformer as vits\n\n\ndef extract_feature_pipeline(args):\n    # ============ preparing data ... ============\n    transform = pth_transforms.Compose([\n        pth_transforms.Resize(256, interpolation=3),\n        pth_transforms.CenterCrop(224),\n        pth_transforms.ToTensor(),\n        pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n    ])\n    dataset_train = ReturnIndexDataset(os.path.join(args.data_path, \"train\"), transform=transform)\n    dataset_val = ReturnIndexDataset(os.path.join(args.data_path, \"val\"), transform=transform)\n    sampler = torch.utils.data.DistributedSampler(dataset_train, shuffle=False)\n    data_loader_train = torch.utils.data.DataLoader(\n        dataset_train,\n        sampler=sampler,\n        batch_size=args.batch_size_per_gpu,\n        num_workers=args.num_workers,\n        pin_memory=True,\n        drop_last=False,\n    )\n    data_loader_val = torch.utils.data.DataLoader(\n        dataset_val,\n        batch_size=args.batch_size_per_gpu,\n        num_workers=args.num_workers,\n        pin_memory=True,\n        drop_last=False,\n    )\n    print(f\"Data loaded with {len(dataset_train)} train and {len(dataset_val)} val imgs.\")\n\n    # ============ building network ... ============\n    if \"vit\" in args.arch:\n        model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0)\n        print(f\"Model {args.arch} {args.patch_size}x{args.patch_size} built.\")\n    elif \"xcit\" in args.arch:\n        model = torch.hub.load('facebookresearch/xcit:main', args.arch, num_classes=0)\n    elif args.arch in torchvision_models.__dict__.keys():\n        model = torchvision_models.__dict__[args.arch](num_classes=0)\n        model.fc = nn.Identity()\n    else:\n        print(f\"Architecture {args.arch} non supported\")\n        sys.exit(1)\n    model.cuda()\n    utils.load_pretrained_weights(model, args.pretrained_weights, args.checkpoint_key, args.arch, args.patch_size)\n    model.eval()\n\n    # ============ extract features ... ============\n    print(\"Extracting features for train set...\")\n    train_features = extract_features(model, data_loader_train, args.use_cuda)\n    print(\"Extracting features for val set...\")\n    test_features = extract_features(model, data_loader_val, args.use_cuda)\n\n    if utils.get_rank() == 0:\n        train_features = nn.functional.normalize(train_features, dim=1, p=2)\n        test_features = nn.functional.normalize(test_features, dim=1, p=2)\n\n    train_labels = torch.tensor([s[-1] for s in dataset_train.samples]).long()\n    test_labels = torch.tensor([s[-1] for s in dataset_val.samples]).long()\n    # save features and labels\n    if args.dump_features and dist.get_rank() == 0:\n        torch.save(train_features.cpu(), os.path.join(args.dump_features, \"trainfeat.pth\"))\n        torch.save(test_features.cpu(), os.path.join(args.dump_features, \"testfeat.pth\"))\n        torch.save(train_labels.cpu(), os.path.join(args.dump_features, \"trainlabels.pth\"))\n        torch.save(test_labels.cpu(), os.path.join(args.dump_features, \"testlabels.pth\"))\n    return train_features, test_features, train_labels, test_labels\n\n\n@torch.no_grad()\ndef extract_features(model, data_loader, use_cuda=True, multiscale=False):\n    metric_logger = utils.MetricLogger(delimiter=\"  \")\n    features = None\n    for samples, index in metric_logger.log_every(data_loader, 10):\n        samples = samples.cuda(non_blocking=True)\n        index = index.cuda(non_blocking=True)\n        if multiscale:\n            feats = utils.multi_scale(samples, model)\n        else:\n            feats = model(samples).clone()\n\n        # init storage feature matrix\n        if dist.get_rank() == 0 and features is None:\n            features = torch.zeros(len(data_loader.dataset), feats.shape[-1])\n            if use_cuda:\n                features = features.cuda(non_blocking=True)\n            print(f\"Storing features into tensor of shape {features.shape}\")\n\n        # get indexes from all processes\n        y_all = torch.empty(dist.get_world_size(), index.size(0), dtype=index.dtype, device=index.device)\n        y_l = list(y_all.unbind(0))\n        y_all_reduce = torch.distributed.all_gather(y_l, index, async_op=True)\n        y_all_reduce.wait()\n        index_all = torch.cat(y_l)\n\n        # share features between processes\n        feats_all = torch.empty(\n            dist.get_world_size(),\n            feats.size(0),\n            feats.size(1),\n            dtype=feats.dtype,\n            device=feats.device,\n        )\n        output_l = list(feats_all.unbind(0))\n        output_all_reduce = torch.distributed.all_gather(output_l, feats, async_op=True)\n        output_all_reduce.wait()\n\n        # update storage feature matrix\n        if dist.get_rank() == 0:\n            if use_cuda:\n                features.index_copy_(0, index_all, torch.cat(output_l))\n            else:\n                features.index_copy_(0, index_all.cpu(), torch.cat(output_l).cpu())\n    return features\n\n\n@torch.no_grad()\ndef knn_classifier(train_features, train_labels, test_features, test_labels, k, T, num_classes=1000):\n    top1, top5, total = 0.0, 0.0, 0\n    train_features = train_features.t()\n    num_test_images, num_chunks = test_labels.shape[0], 100\n    imgs_per_chunk = num_test_images // num_chunks\n    retrieval_one_hot = torch.zeros(k, num_classes).to(train_features.device)\n    for idx in range(0, num_test_images, imgs_per_chunk):\n        # get the features for test images\n        features = test_features[\n            idx : min((idx + imgs_per_chunk), num_test_images), :\n        ]\n        targets = test_labels[idx : min((idx + imgs_per_chunk), num_test_images)]\n        batch_size = targets.shape[0]\n\n        # calculate the dot product and compute top-k neighbors\n        similarity = torch.mm(features, train_features)\n        distances, indices = similarity.topk(k, largest=True, sorted=True)\n        candidates = train_labels.view(1, -1).expand(batch_size, -1)\n        retrieved_neighbors = torch.gather(candidates, 1, indices)\n\n        retrieval_one_hot.resize_(batch_size * k, num_classes).zero_()\n        retrieval_one_hot.scatter_(1, retrieved_neighbors.view(-1, 1), 1)\n        distances_transform = distances.clone().div_(T).exp_()\n        probs = torch.sum(\n            torch.mul(\n                retrieval_one_hot.view(batch_size, -1, num_classes),\n                distances_transform.view(batch_size, -1, 1),\n            ),\n            1,\n        )\n        _, predictions = probs.sort(1, True)\n\n        # find the predictions that match the target\n        correct = predictions.eq(targets.data.view(-1, 1))\n        top1 = top1 + correct.narrow(1, 0, 1).sum().item()\n        top5 = top5 + correct.narrow(1, 0, min(5, k)).sum().item()  # top5 does not make sense if k < 5\n        total += targets.size(0)\n    top1 = top1 * 100.0 / total\n    top5 = top5 * 100.0 / total\n    return top1, top5\n\n\nclass ReturnIndexDataset(datasets.ImageFolder):\n    def __getitem__(self, idx):\n        img, lab = super(ReturnIndexDataset, self).__getitem__(idx)\n        return img, idx\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('Evaluation with weighted k-NN on ImageNet')\n    parser.add_argument('--batch_size_per_gpu', default=128, type=int, help='Per-GPU batch-size')\n    parser.add_argument('--nb_knn', default=[10, 20, 100, 200], nargs='+', type=int,\n        help='Number of NN to use. 20 is usually working the best.')\n    parser.add_argument('--temperature', default=0.07, type=float,\n        help='Temperature used in the voting coefficient')\n    parser.add_argument('--pretrained_weights', default='', type=str, help=\"Path to pretrained weights to evaluate.\")\n    parser.add_argument('--use_cuda', default=True, type=utils.bool_flag,\n        help=\"Should we store the features on GPU? We recommend setting this to False if you encounter OOM\")\n    parser.add_argument('--arch', default='vit_small', type=str, help='Architecture')\n    parser.add_argument('--patch_size', default=16, type=int, help='Patch resolution of the model.')\n    parser.add_argument(\"--checkpoint_key\", default=\"teacher\", type=str,\n        help='Key to use in the checkpoint (example: \"teacher\")')\n    parser.add_argument('--dump_features', default=None,\n        help='Path where to save computed features, empty for no saving')\n    parser.add_argument('--load_features', default=None, help=\"\"\"If the features have\n        already been computed, where to find them.\"\"\")\n    parser.add_argument('--num_workers', default=10, type=int, help='Number of data loading workers per GPU.')\n    parser.add_argument(\"--dist_url\", default=\"env://\", type=str, help=\"\"\"url used to set up\n        distributed training; see https://pytorch.org/docs/stable/distributed.html\"\"\")\n    parser.add_argument(\"--local_rank\", default=0, type=int, help=\"Please ignore and do not set this argument.\")\n    parser.add_argument('--data_path', default='/path/to/imagenet/', type=str)\n    args = parser.parse_args()\n\n    utils.init_distributed_mode(args)\n    print(\"git:\\n  {}\\n\".format(utils.get_sha()))\n    print(\"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())))\n    cudnn.benchmark = True\n\n    if args.load_features:\n        train_features = torch.load(os.path.join(args.load_features, \"trainfeat.pth\"))\n        test_features = torch.load(os.path.join(args.load_features, \"testfeat.pth\"))\n        train_labels = torch.load(os.path.join(args.load_features, \"trainlabels.pth\"))\n        test_labels = torch.load(os.path.join(args.load_features, \"testlabels.pth\"))\n    else:\n        # need to extract features !\n        train_features, test_features, train_labels, test_labels = extract_feature_pipeline(args)\n\n    if utils.get_rank() == 0:\n        if args.use_cuda:\n            train_features = train_features.cuda()\n            test_features = test_features.cuda()\n            train_labels = train_labels.cuda()\n            test_labels = test_labels.cuda()\n\n        print(\"Features are ready!\\nStart the k-NN classification.\")\n        for k in args.nb_knn:\n            top1, top5 = knn_classifier(train_features, train_labels,\n                test_features, test_labels, k, args.temperature)\n            print(f\"{k}-NN classifier result: Top1: {top1}, Top5: {top5}\")\n    dist.barrier()\n"
  },
  {
    "path": "eval_linear.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport os\nimport argparse\nimport json\nfrom pathlib import Path\n\nimport torch\nfrom torch import nn\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nfrom torchvision import datasets\nfrom torchvision import transforms as pth_transforms\nfrom torchvision import models as torchvision_models\n\nimport utils\nimport vision_transformer as vits\n\n\ndef eval_linear(args):\n    utils.init_distributed_mode(args)\n    print(\"git:\\n  {}\\n\".format(utils.get_sha()))\n    print(\"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())))\n    cudnn.benchmark = True\n\n    # ============ building network ... ============\n    # if the network is a Vision Transformer (i.e. vit_tiny, vit_small, vit_base)\n    if args.arch in vits.__dict__.keys():\n        model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0)\n        embed_dim = model.embed_dim * (args.n_last_blocks + int(args.avgpool_patchtokens))\n    # if the network is a XCiT\n    elif \"xcit\" in args.arch:\n        model = torch.hub.load('facebookresearch/xcit:main', args.arch, num_classes=0)\n        embed_dim = model.embed_dim\n    # otherwise, we check if the architecture is in torchvision models\n    elif args.arch in torchvision_models.__dict__.keys():\n        model = torchvision_models.__dict__[args.arch]()\n        embed_dim = model.fc.weight.shape[1]\n        model.fc = nn.Identity()\n    else:\n        print(f\"Unknow architecture: {args.arch}\")\n        sys.exit(1)\n    model.cuda()\n    model.eval()\n    # load weights to evaluate\n    utils.load_pretrained_weights(model, args.pretrained_weights, args.checkpoint_key, args.arch, args.patch_size)\n    print(f\"Model {args.arch} built.\")\n\n    linear_classifier = LinearClassifier(embed_dim, num_labels=args.num_labels)\n    linear_classifier = linear_classifier.cuda()\n    linear_classifier = nn.parallel.DistributedDataParallel(linear_classifier, device_ids=[args.gpu])\n\n    # ============ preparing data ... ============\n    val_transform = pth_transforms.Compose([\n        pth_transforms.Resize(256, interpolation=3),\n        pth_transforms.CenterCrop(224),\n        pth_transforms.ToTensor(),\n        pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n    ])\n    dataset_val = datasets.ImageFolder(os.path.join(args.data_path, \"val\"), transform=val_transform)\n    val_loader = torch.utils.data.DataLoader(\n        dataset_val,\n        batch_size=args.batch_size_per_gpu,\n        num_workers=args.num_workers,\n        pin_memory=True,\n    )\n\n    if args.evaluate:\n        utils.load_pretrained_linear_weights(linear_classifier, args.arch, args.patch_size)\n        test_stats = validate_network(val_loader, model, linear_classifier, args.n_last_blocks, args.avgpool_patchtokens)\n        print(f\"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%\")\n        return\n\n    train_transform = pth_transforms.Compose([\n        pth_transforms.RandomResizedCrop(224),\n        pth_transforms.RandomHorizontalFlip(),\n        pth_transforms.ToTensor(),\n        pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n    ])\n    dataset_train = datasets.ImageFolder(os.path.join(args.data_path, \"train\"), transform=train_transform)\n    sampler = torch.utils.data.distributed.DistributedSampler(dataset_train)\n    train_loader = torch.utils.data.DataLoader(\n        dataset_train,\n        sampler=sampler,\n        batch_size=args.batch_size_per_gpu,\n        num_workers=args.num_workers,\n        pin_memory=True,\n    )\n    print(f\"Data loaded with {len(dataset_train)} train and {len(dataset_val)} val imgs.\")\n\n    # set optimizer\n    optimizer = torch.optim.SGD(\n        linear_classifier.parameters(),\n        args.lr * (args.batch_size_per_gpu * utils.get_world_size()) / 256., # linear scaling rule\n        momentum=0.9,\n        weight_decay=0, # we do not apply weight decay\n    )\n    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs, eta_min=0)\n\n    # Optionally resume from a checkpoint\n    to_restore = {\"epoch\": 0, \"best_acc\": 0.}\n    utils.restart_from_checkpoint(\n        os.path.join(args.output_dir, \"checkpoint.pth.tar\"),\n        run_variables=to_restore,\n        state_dict=linear_classifier,\n        optimizer=optimizer,\n        scheduler=scheduler,\n    )\n    start_epoch = to_restore[\"epoch\"]\n    best_acc = to_restore[\"best_acc\"]\n\n    for epoch in range(start_epoch, args.epochs):\n        train_loader.sampler.set_epoch(epoch)\n\n        train_stats = train(model, linear_classifier, optimizer, train_loader, epoch, args.n_last_blocks, args.avgpool_patchtokens)\n        scheduler.step()\n\n        log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},\n                     'epoch': epoch}\n        if epoch % args.val_freq == 0 or epoch == args.epochs - 1:\n            test_stats = validate_network(val_loader, model, linear_classifier, args.n_last_blocks, args.avgpool_patchtokens)\n            print(f\"Accuracy at epoch {epoch} of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%\")\n            best_acc = max(best_acc, test_stats[\"acc1\"])\n            print(f'Max accuracy so far: {best_acc:.2f}%')\n            log_stats = {**{k: v for k, v in log_stats.items()},\n                         **{f'test_{k}': v for k, v in test_stats.items()}}\n        if utils.is_main_process():\n            with (Path(args.output_dir) / \"log.txt\").open(\"a\") as f:\n                f.write(json.dumps(log_stats) + \"\\n\")\n            save_dict = {\n                \"epoch\": epoch + 1,\n                \"state_dict\": linear_classifier.state_dict(),\n                \"optimizer\": optimizer.state_dict(),\n                \"scheduler\": scheduler.state_dict(),\n                \"best_acc\": best_acc,\n            }\n            torch.save(save_dict, os.path.join(args.output_dir, \"checkpoint.pth.tar\"))\n    print(\"Training of the supervised linear classifier on frozen features completed.\\n\"\n                \"Top-1 test accuracy: {acc:.1f}\".format(acc=best_acc))\n\n\ndef train(model, linear_classifier, optimizer, loader, epoch, n, avgpool):\n    linear_classifier.train()\n    metric_logger = utils.MetricLogger(delimiter=\"  \")\n    metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}'))\n    header = 'Epoch: [{}]'.format(epoch)\n    for (inp, target) in metric_logger.log_every(loader, 20, header):\n        # move to gpu\n        inp = inp.cuda(non_blocking=True)\n        target = target.cuda(non_blocking=True)\n\n        # forward\n        with torch.no_grad():\n            if \"vit\" in args.arch:\n                intermediate_output = model.get_intermediate_layers(inp, n)\n                output = torch.cat([x[:, 0] for x in intermediate_output], dim=-1)\n                if avgpool:\n                    output = torch.cat((output.unsqueeze(-1), torch.mean(intermediate_output[-1][:, 1:], dim=1).unsqueeze(-1)), dim=-1)\n                    output = output.reshape(output.shape[0], -1)\n            else:\n                output = model(inp)\n        output = linear_classifier(output)\n\n        # compute cross entropy loss\n        loss = nn.CrossEntropyLoss()(output, target)\n\n        # compute the gradients\n        optimizer.zero_grad()\n        loss.backward()\n\n        # step\n        optimizer.step()\n\n        # log \n        torch.cuda.synchronize()\n        metric_logger.update(loss=loss.item())\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 validate_network(val_loader, model, linear_classifier, n, avgpool):\n    linear_classifier.eval()\n    metric_logger = utils.MetricLogger(delimiter=\"  \")\n    header = 'Test:'\n    for inp, target in metric_logger.log_every(val_loader, 20, header):\n        # move to gpu\n        inp = inp.cuda(non_blocking=True)\n        target = target.cuda(non_blocking=True)\n\n        # forward\n        with torch.no_grad():\n            if \"vit\" in args.arch:\n                intermediate_output = model.get_intermediate_layers(inp, n)\n                output = torch.cat([x[:, 0] for x in intermediate_output], dim=-1)\n                if avgpool:\n                    output = torch.cat((output.unsqueeze(-1), torch.mean(intermediate_output[-1][:, 1:], dim=1).unsqueeze(-1)), dim=-1)\n                    output = output.reshape(output.shape[0], -1)\n            else:\n                output = model(inp)\n        output = linear_classifier(output)\n        loss = nn.CrossEntropyLoss()(output, target)\n\n        if linear_classifier.module.num_labels >= 5:\n            acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))\n        else:\n            acc1, = utils.accuracy(output, target, topk=(1,))\n\n        batch_size = inp.shape[0]\n        metric_logger.update(loss=loss.item())\n        metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)\n        if linear_classifier.module.num_labels >= 5:\n            metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)\n    if linear_classifier.module.num_labels >= 5:\n        print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}'\n          .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss))\n    else:\n        print('* Acc@1 {top1.global_avg:.3f} loss {losses.global_avg:.3f}'\n          .format(top1=metric_logger.acc1, losses=metric_logger.loss))\n    return {k: meter.global_avg for k, meter in metric_logger.meters.items()}\n\n\nclass LinearClassifier(nn.Module):\n    \"\"\"Linear layer to train on top of frozen features\"\"\"\n    def __init__(self, dim, num_labels=1000):\n        super(LinearClassifier, self).__init__()\n        self.num_labels = num_labels\n        self.linear = nn.Linear(dim, num_labels)\n        self.linear.weight.data.normal_(mean=0.0, std=0.01)\n        self.linear.bias.data.zero_()\n\n    def forward(self, x):\n        # flatten\n        x = x.view(x.size(0), -1)\n\n        # linear layer\n        return self.linear(x)\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('Evaluation with linear classification on ImageNet')\n    parser.add_argument('--n_last_blocks', default=4, type=int, help=\"\"\"Concatenate [CLS] tokens\n        for the `n` last blocks. We use `n=4` when evaluating ViT-Small and `n=1` with ViT-Base.\"\"\")\n    parser.add_argument('--avgpool_patchtokens', default=False, type=utils.bool_flag,\n        help=\"\"\"Whether ot not to concatenate the global average pooled features to the [CLS] token.\n        We typically set this to False for ViT-Small and to True with ViT-Base.\"\"\")\n    parser.add_argument('--arch', default='vit_small', type=str, help='Architecture')\n    parser.add_argument('--patch_size', default=16, type=int, help='Patch resolution of the model.')\n    parser.add_argument('--pretrained_weights', default='', type=str, help=\"Path to pretrained weights to evaluate.\")\n    parser.add_argument(\"--checkpoint_key\", default=\"teacher\", type=str, help='Key to use in the checkpoint (example: \"teacher\")')\n    parser.add_argument('--epochs', default=100, type=int, help='Number of epochs of training.')\n    parser.add_argument(\"--lr\", default=0.001, type=float, help=\"\"\"Learning rate at the beginning of\n        training (highest LR used during training). The learning rate is linearly scaled\n        with the batch size, and specified here for a reference batch size of 256.\n        We recommend tweaking the LR depending on the checkpoint evaluated.\"\"\")\n    parser.add_argument('--batch_size_per_gpu', default=128, type=int, help='Per-GPU batch-size')\n    parser.add_argument(\"--dist_url\", default=\"env://\", type=str, help=\"\"\"url used to set up\n        distributed training; see https://pytorch.org/docs/stable/distributed.html\"\"\")\n    parser.add_argument(\"--local_rank\", default=0, type=int, help=\"Please ignore and do not set this argument.\")\n    parser.add_argument('--data_path', default='/path/to/imagenet/', type=str)\n    parser.add_argument('--num_workers', default=10, type=int, help='Number of data loading workers per GPU.')\n    parser.add_argument('--val_freq', default=1, type=int, help=\"Epoch frequency for validation.\")\n    parser.add_argument('--output_dir', default=\".\", help='Path to save logs and checkpoints')\n    parser.add_argument('--num_labels', default=1000, type=int, help='Number of labels for linear classifier')\n    parser.add_argument('--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set')\n    args = parser.parse_args()\n    eval_linear(args)\n"
  },
  {
    "path": "eval_video_segmentation.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"\nSome parts are taken from https://github.com/Liusifei/UVC\n\"\"\"\nimport os\nimport copy\nimport glob\nimport queue\nfrom urllib.request import urlopen\nimport argparse\nimport numpy as np\nfrom tqdm import tqdm\n\nimport cv2\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom PIL import Image\nfrom torchvision import transforms\n\nimport utils\nimport vision_transformer as vits\n\n\n@torch.no_grad()\ndef eval_video_tracking_davis(args, model, frame_list, video_dir, first_seg, seg_ori, color_palette):\n    \"\"\"\n    Evaluate tracking on a video given first frame & segmentation\n    \"\"\"\n    video_folder = os.path.join(args.output_dir, video_dir.split('/')[-1])\n    os.makedirs(video_folder, exist_ok=True)\n\n    # The queue stores the n preceeding frames\n    que = queue.Queue(args.n_last_frames)\n\n    # first frame\n    frame1, ori_h, ori_w = read_frame(frame_list[0])\n    # extract first frame feature\n    frame1_feat = extract_feature(model, frame1).T #  dim x h*w\n\n    # saving first segmentation\n    out_path = os.path.join(video_folder, \"00000.png\")\n    imwrite_indexed(out_path, seg_ori, color_palette)\n    mask_neighborhood = None\n    for cnt in tqdm(range(1, len(frame_list))):\n        frame_tar = read_frame(frame_list[cnt])[0]\n\n        # we use the first segmentation and the n previous ones\n        used_frame_feats = [frame1_feat] + [pair[0] for pair in list(que.queue)]\n        used_segs = [first_seg] + [pair[1] for pair in list(que.queue)]\n\n        frame_tar_avg, feat_tar, mask_neighborhood = label_propagation(args, model, frame_tar, used_frame_feats, used_segs, mask_neighborhood)\n\n        # pop out oldest frame if neccessary\n        if que.qsize() == args.n_last_frames:\n            que.get()\n        # push current results into queue\n        seg = copy.deepcopy(frame_tar_avg)\n        que.put([feat_tar, seg])\n\n        # upsampling & argmax\n        frame_tar_avg = F.interpolate(frame_tar_avg, scale_factor=args.patch_size, mode='bilinear', align_corners=False, recompute_scale_factor=False)[0]\n        frame_tar_avg = norm_mask(frame_tar_avg)\n        _, frame_tar_seg = torch.max(frame_tar_avg, dim=0)\n\n        # saving to disk\n        frame_tar_seg = np.array(frame_tar_seg.squeeze().cpu(), dtype=np.uint8)\n        frame_tar_seg = np.array(Image.fromarray(frame_tar_seg).resize((ori_w, ori_h), 0))\n        frame_nm = frame_list[cnt].split('/')[-1].replace(\".jpg\", \".png\")\n        imwrite_indexed(os.path.join(video_folder, frame_nm), frame_tar_seg, color_palette)\n\n\ndef restrict_neighborhood(h, w):\n    # We restrict the set of source nodes considered to a spatial neighborhood of the query node (i.e. ``local attention'')\n    mask = torch.zeros(h, w, h, w)\n    for i in range(h):\n        for j in range(w):\n            for p in range(2 * args.size_mask_neighborhood + 1):\n                for q in range(2 * args.size_mask_neighborhood + 1):\n                    if i - args.size_mask_neighborhood + p < 0 or i - args.size_mask_neighborhood + p >= h:\n                        continue\n                    if j - args.size_mask_neighborhood + q < 0 or j - args.size_mask_neighborhood + q >= w:\n                        continue\n                    mask[i, j, i - args.size_mask_neighborhood + p, j - args.size_mask_neighborhood + q] = 1\n\n    mask = mask.reshape(h * w, h * w)\n    return mask.cuda(non_blocking=True)\n\n\ndef norm_mask(mask):\n    c, h, w = mask.size()\n    for cnt in range(c):\n        mask_cnt = mask[cnt,:,:]\n        if(mask_cnt.max() > 0):\n            mask_cnt = (mask_cnt - mask_cnt.min())\n            mask_cnt = mask_cnt/mask_cnt.max()\n            mask[cnt,:,:] = mask_cnt\n    return mask\n\n\ndef label_propagation(args, model, frame_tar, list_frame_feats, list_segs, mask_neighborhood=None):\n    \"\"\"\n    propagate segs of frames in list_frames to frame_tar\n    \"\"\"\n    ## we only need to extract feature of the target frame\n    feat_tar, h, w = extract_feature(model, frame_tar, return_h_w=True)\n\n    return_feat_tar = feat_tar.T # dim x h*w\n\n    ncontext = len(list_frame_feats)\n    feat_sources = torch.stack(list_frame_feats) # nmb_context x dim x h*w\n\n    feat_tar = F.normalize(feat_tar, dim=1, p=2)\n    feat_sources = F.normalize(feat_sources, dim=1, p=2)\n\n    feat_tar = feat_tar.unsqueeze(0).repeat(ncontext, 1, 1)\n    aff = torch.exp(torch.bmm(feat_tar, feat_sources) / 0.1) # nmb_context x h*w (tar: query) x h*w (source: keys)\n\n    if args.size_mask_neighborhood > 0:\n        if mask_neighborhood is None:\n            mask_neighborhood = restrict_neighborhood(h, w)\n            mask_neighborhood = mask_neighborhood.unsqueeze(0).repeat(ncontext, 1, 1)\n        aff *= mask_neighborhood\n\n    aff = aff.transpose(2, 1).reshape(-1, h * w) # nmb_context*h*w (source: keys) x h*w (tar: queries)\n    tk_val, _ = torch.topk(aff, dim=0, k=args.topk)\n    tk_val_min, _ = torch.min(tk_val, dim=0)\n    aff[aff < tk_val_min] = 0\n\n    aff = aff / torch.sum(aff, keepdim=True, axis=0)\n\n    list_segs = [s.cuda() for s in list_segs]\n    segs = torch.cat(list_segs)\n    nmb_context, C, h, w = segs.shape\n    segs = segs.reshape(nmb_context, C, -1).transpose(2, 1).reshape(-1, C).T # C x nmb_context*h*w\n    seg_tar = torch.mm(segs, aff)\n    seg_tar = seg_tar.reshape(1, C, h, w)\n    return seg_tar, return_feat_tar, mask_neighborhood\n \n\ndef extract_feature(model, frame, return_h_w=False):\n    \"\"\"Extract one frame feature everytime.\"\"\"\n    out = model.get_intermediate_layers(frame.unsqueeze(0).cuda(), n=1)[0]\n    out = out[:, 1:, :]  # we discard the [CLS] token\n    h, w = int(frame.shape[1] / model.patch_embed.patch_size), int(frame.shape[2] / model.patch_embed.patch_size)\n    dim = out.shape[-1]\n    out = out[0].reshape(h, w, dim)\n    out = out.reshape(-1, dim)\n    if return_h_w:\n        return out, h, w\n    return out\n\n\ndef imwrite_indexed(filename, array, color_palette):\n    \"\"\" Save indexed png for DAVIS.\"\"\"\n    if np.atleast_3d(array).shape[2] != 1:\n      raise Exception(\"Saving indexed PNGs requires 2D array.\")\n\n    im = Image.fromarray(array)\n    im.putpalette(color_palette.ravel())\n    im.save(filename, format='PNG')\n\n\ndef to_one_hot(y_tensor, n_dims=None):\n    \"\"\"\n    Take integer y (tensor or variable) with n dims &\n    convert it to 1-hot representation with n+1 dims.\n    \"\"\"\n    if(n_dims is None):\n        n_dims = int(y_tensor.max()+ 1)\n    _,h,w = y_tensor.size()\n    y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1)\n    n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1\n    y_one_hot = torch.zeros(y_tensor.size()[0], n_dims).scatter_(1, y_tensor, 1)\n    y_one_hot = y_one_hot.view(h,w,n_dims)\n    return y_one_hot.permute(2, 0, 1).unsqueeze(0)\n\n\ndef read_frame_list(video_dir):\n    frame_list = [img for img in glob.glob(os.path.join(video_dir,\"*.jpg\"))]\n    frame_list = sorted(frame_list)\n    return frame_list\n\n\ndef read_frame(frame_dir, scale_size=[480]):\n    \"\"\"\n    read a single frame & preprocess\n    \"\"\"\n    img = cv2.imread(frame_dir)\n    ori_h, ori_w, _ = img.shape\n    if len(scale_size) == 1:\n        if(ori_h > ori_w):\n            tw = scale_size[0]\n            th = (tw * ori_h) / ori_w\n            th = int((th // 64) * 64)\n        else:\n            th = scale_size[0]\n            tw = (th * ori_w) / ori_h\n            tw = int((tw // 64) * 64)\n    else:\n        th, tw = scale_size\n    img = cv2.resize(img, (tw, th))\n    img = img.astype(np.float32)\n    img = img / 255.0\n    img = img[:, :, ::-1]\n    img = np.transpose(img.copy(), (2, 0, 1))\n    img = torch.from_numpy(img).float()\n    img = color_normalize(img)\n    return img, ori_h, ori_w\n\n\ndef read_seg(seg_dir, factor, scale_size=[480]):\n    seg = Image.open(seg_dir)\n    _w, _h = seg.size # note PIL.Image.Image's size is (w, h)\n    if len(scale_size) == 1:\n        if(_w > _h):\n            _th = scale_size[0]\n            _tw = (_th * _w) / _h\n            _tw = int((_tw // 64) * 64)\n        else:\n            _tw = scale_size[0]\n            _th = (_tw * _h) / _w\n            _th = int((_th // 64) * 64)\n    else:\n        _th = scale_size[1]\n        _tw = scale_size[0]\n    small_seg = np.array(seg.resize((_tw // factor, _th // factor), 0))\n    small_seg = torch.from_numpy(small_seg.copy()).contiguous().float().unsqueeze(0)\n    return to_one_hot(small_seg), np.asarray(seg)\n\n\ndef color_normalize(x, mean=[0.485, 0.456, 0.406], std=[0.228, 0.224, 0.225]):\n    for t, m, s in zip(x, mean, std):\n        t.sub_(m)\n        t.div_(s)\n    return x\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('Evaluation with video object segmentation on DAVIS 2017')\n    parser.add_argument('--pretrained_weights', default='', type=str, help=\"Path to pretrained weights to evaluate.\")\n    parser.add_argument('--arch', default='vit_small', type=str,\n        choices=['vit_tiny', 'vit_small', 'vit_base'], help='Architecture (support only ViT atm).')\n    parser.add_argument('--patch_size', default=16, type=int, help='Patch resolution of the model.')\n    parser.add_argument(\"--checkpoint_key\", default=\"teacher\", type=str, help='Key to use in the checkpoint (example: \"teacher\")')\n    parser.add_argument('--output_dir', default=\".\", help='Path where to save segmentations')\n    parser.add_argument('--data_path', default='/path/to/davis/', type=str)\n    parser.add_argument(\"--n_last_frames\", type=int, default=7, help=\"number of preceeding frames\")\n    parser.add_argument(\"--size_mask_neighborhood\", default=12, type=int,\n        help=\"We restrict the set of source nodes considered to a spatial neighborhood of the query node\")\n    parser.add_argument(\"--topk\", type=int, default=5, help=\"accumulate label from top k neighbors\")\n    parser.add_argument(\"--bs\", type=int, default=6, help=\"Batch size, try to reduce if OOM\")\n    args = parser.parse_args()\n\n    print(\"git:\\n  {}\\n\".format(utils.get_sha()))\n    print(\"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())))\n\n    # building network\n    model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0)\n    print(f\"Model {args.arch} {args.patch_size}x{args.patch_size} built.\")\n    model.cuda()\n    utils.load_pretrained_weights(model, args.pretrained_weights, args.checkpoint_key, args.arch, args.patch_size)\n    for param in model.parameters():\n        param.requires_grad = False\n    model.eval()\n\n    color_palette = []\n    for line in urlopen(\"https://raw.githubusercontent.com/Liusifei/UVC/master/libs/data/palette.txt\"):\n        color_palette.append([int(i) for i in line.decode(\"utf-8\").split('\\n')[0].split(\" \")])\n    color_palette = np.asarray(color_palette, dtype=np.uint8).reshape(-1,3)\n\n    video_list = open(os.path.join(args.data_path, \"ImageSets/2017/val.txt\")).readlines()\n    for i, video_name in enumerate(video_list):\n        video_name = video_name.strip()\n        print(f'[{i}/{len(video_list)}] Begin to segmentate video {video_name}.')\n        video_dir = os.path.join(args.data_path, \"JPEGImages/480p/\", video_name)\n        frame_list = read_frame_list(video_dir)\n        seg_path = frame_list[0].replace(\"JPEGImages\", \"Annotations\").replace(\"jpg\", \"png\")\n        first_seg, seg_ori = read_seg(seg_path, args.patch_size)\n        eval_video_tracking_davis(args, model, frame_list, video_dir, first_seg, seg_ori, color_palette)\n"
  },
  {
    "path": "hubconf.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport torch\nfrom torchvision.models.resnet import resnet50\n\nimport vision_transformer as vits\n\ndependencies = [\"torch\", \"torchvision\"]\n\n\ndef dino_vits16(pretrained=True, **kwargs):\n    \"\"\"\n    ViT-Small/16x16 pre-trained with DINO.\n    Achieves 74.5% top-1 accuracy on ImageNet with k-NN classification.\n    \"\"\"\n    model = vits.__dict__[\"vit_small\"](patch_size=16, num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n\n\ndef dino_vits8(pretrained=True, **kwargs):\n    \"\"\"\n    ViT-Small/8x8 pre-trained with DINO.\n    Achieves 78.3% top-1 accuracy on ImageNet with k-NN classification.\n    \"\"\"\n    model = vits.__dict__[\"vit_small\"](patch_size=8, num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n\n\ndef dino_vitb16(pretrained=True, **kwargs):\n    \"\"\"\n    ViT-Base/16x16 pre-trained with DINO.\n    Achieves 76.1% top-1 accuracy on ImageNet with k-NN classification.\n    \"\"\"\n    model = vits.__dict__[\"vit_base\"](patch_size=16, num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n\n\ndef dino_vitb8(pretrained=True, **kwargs):\n    \"\"\"\n    ViT-Base/8x8 pre-trained with DINO.\n    Achieves 77.4% top-1 accuracy on ImageNet with k-NN classification.\n    \"\"\"\n    model = vits.__dict__[\"vit_base\"](patch_size=8, num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n\n\ndef dino_resnet50(pretrained=True, **kwargs):\n    \"\"\"\n    ResNet-50 pre-trained with DINO.\n    Achieves 75.3% top-1 accuracy on ImageNet linear evaluation benchmark (requires to train `fc`).\n    \"\"\"\n    model = resnet50(pretrained=False, **kwargs)\n    model.fc = torch.nn.Identity()\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_resnet50_pretrain/dino_resnet50_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=False)\n    return model\n\n\ndef dino_xcit_small_12_p16(pretrained=True, **kwargs):\n    \"\"\"\n    XCiT-Small-12/16 pre-trained with DINO.\n    \"\"\"\n    model = torch.hub.load('facebookresearch/xcit:main', \"xcit_small_12_p16\", num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n\n\ndef dino_xcit_small_12_p8(pretrained=True, **kwargs):\n    \"\"\"\n    XCiT-Small-12/8 pre-trained with DINO.\n    \"\"\"\n    model = torch.hub.load('facebookresearch/xcit:main', \"xcit_small_12_p8\", num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n\n\ndef dino_xcit_medium_24_p16(pretrained=True, **kwargs):\n    \"\"\"\n    XCiT-Medium-24/16 pre-trained with DINO.\n    \"\"\"\n    model = torch.hub.load('facebookresearch/xcit:main', \"xcit_medium_24_p16\", num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n\n\ndef dino_xcit_medium_24_p8(pretrained=True, **kwargs):\n    \"\"\"\n    XCiT-Medium-24/8 pre-trained with DINO.\n    \"\"\"\n    model = torch.hub.load('facebookresearch/xcit:main', \"xcit_medium_24_p8\", num_classes=0, **kwargs)\n    if pretrained:\n        state_dict = torch.hub.load_state_dict_from_url(\n            url=\"https://dl.fbaipublicfiles.com/dino/dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain.pth\",\n            map_location=\"cpu\",\n        )\n        model.load_state_dict(state_dict, strict=True)\n    return model\n"
  },
  {
    "path": "main_dino.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport argparse\nimport os\nimport sys\nimport datetime\nimport time\nimport math\nimport json\nfrom pathlib import Path\n\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision import models as torchvision_models\n\nimport utils\nimport vision_transformer as vits\nfrom vision_transformer import DINOHead\n\ntorchvision_archs = sorted(name for name in torchvision_models.__dict__\n    if name.islower() and not name.startswith(\"__\")\n    and callable(torchvision_models.__dict__[name]))\n\ndef get_args_parser():\n    parser = argparse.ArgumentParser('DINO', add_help=False)\n\n    # Model parameters\n    parser.add_argument('--arch', default='vit_small', type=str,\n        choices=['vit_tiny', 'vit_small', 'vit_base', 'xcit', 'deit_tiny', 'deit_small'] \\\n                + torchvision_archs + torch.hub.list(\"facebookresearch/xcit:main\"),\n        help=\"\"\"Name of architecture to train. For quick experiments with ViTs,\n        we recommend using vit_tiny or vit_small.\"\"\")\n    parser.add_argument('--patch_size', default=16, type=int, help=\"\"\"Size in pixels\n        of input square patches - default 16 (for 16x16 patches). Using smaller\n        values leads to better performance but requires more memory. Applies only\n        for ViTs (vit_tiny, vit_small and vit_base). If <16, we recommend disabling\n        mixed precision training (--use_fp16 false) to avoid unstabilities.\"\"\")\n    parser.add_argument('--out_dim', default=65536, type=int, help=\"\"\"Dimensionality of\n        the DINO head output. For complex and large datasets large values (like 65k) work well.\"\"\")\n    parser.add_argument('--norm_last_layer', default=True, type=utils.bool_flag,\n        help=\"\"\"Whether or not to weight normalize the last layer of the DINO head.\n        Not normalizing leads to better performance but can make the training unstable.\n        In our experiments, we typically set this paramater to False with vit_small and True with vit_base.\"\"\")\n    parser.add_argument('--momentum_teacher', default=0.996, type=float, help=\"\"\"Base EMA\n        parameter for teacher update. The value is increased to 1 during training with cosine schedule.\n        We recommend setting a higher value with small batches: for example use 0.9995 with batch size of 256.\"\"\")\n    parser.add_argument('--use_bn_in_head', default=False, type=utils.bool_flag,\n        help=\"Whether to use batch normalizations in projection head (Default: False)\")\n\n    # Temperature teacher parameters\n    parser.add_argument('--warmup_teacher_temp', default=0.04, type=float,\n        help=\"\"\"Initial value for the teacher temperature: 0.04 works well in most cases.\n        Try decreasing it if the training loss does not decrease.\"\"\")\n    parser.add_argument('--teacher_temp', default=0.04, type=float, help=\"\"\"Final value (after linear warmup)\n        of the teacher temperature. For most experiments, anything above 0.07 is unstable. We recommend\n        starting with the default value of 0.04 and increase this slightly if needed.\"\"\")\n    parser.add_argument('--warmup_teacher_temp_epochs', default=0, type=int,\n        help='Number of warmup epochs for the teacher temperature (Default: 30).')\n\n    # Training/Optimization parameters\n    parser.add_argument('--use_fp16', type=utils.bool_flag, default=True, help=\"\"\"Whether or not\n        to use half precision for training. Improves training time and memory requirements,\n        but can provoke instability and slight decay of performance. We recommend disabling\n        mixed precision if the loss is unstable, if reducing the patch size or if training with bigger ViTs.\"\"\")\n    parser.add_argument('--weight_decay', type=float, default=0.04, help=\"\"\"Initial value of the\n        weight decay. With ViT, a smaller value at the beginning of training works well.\"\"\")\n    parser.add_argument('--weight_decay_end', type=float, default=0.4, help=\"\"\"Final value of the\n        weight decay. We use a cosine schedule for WD and using a larger decay by\n        the end of training improves performance for ViTs.\"\"\")\n    parser.add_argument('--clip_grad', type=float, default=3.0, help=\"\"\"Maximal parameter\n        gradient norm if using gradient clipping. Clipping with norm .3 ~ 1.0 can\n        help optimization for larger ViT architectures. 0 for disabling.\"\"\")\n    parser.add_argument('--batch_size_per_gpu', default=64, type=int,\n        help='Per-GPU batch-size : number of distinct images loaded on one GPU.')\n    parser.add_argument('--epochs', default=100, type=int, help='Number of epochs of training.')\n    parser.add_argument('--freeze_last_layer', default=1, type=int, help=\"\"\"Number of epochs\n        during which we keep the output layer fixed. Typically doing so during\n        the first epoch helps training. Try increasing this value if the loss does not decrease.\"\"\")\n    parser.add_argument(\"--lr\", default=0.0005, type=float, help=\"\"\"Learning rate at the end of\n        linear warmup (highest LR used during training). The learning rate is linearly scaled\n        with the batch size, and specified here for a reference batch size of 256.\"\"\")\n    parser.add_argument(\"--warmup_epochs\", default=10, type=int,\n        help=\"Number of epochs for the linear learning-rate warm up.\")\n    parser.add_argument('--min_lr', type=float, default=1e-6, help=\"\"\"Target LR at the\n        end of optimization. We use a cosine LR schedule with linear warmup.\"\"\")\n    parser.add_argument('--optimizer', default='adamw', type=str,\n        choices=['adamw', 'sgd', 'lars'], help=\"\"\"Type of optimizer. We recommend using adamw with ViTs.\"\"\")\n    parser.add_argument('--drop_path_rate', type=float, default=0.1, help=\"stochastic depth rate\")\n\n    # Multi-crop parameters\n    parser.add_argument('--global_crops_scale', type=float, nargs='+', default=(0.4, 1.),\n        help=\"\"\"Scale range of the cropped image before resizing, relatively to the origin image.\n        Used for large global view cropping. When disabling multi-crop (--local_crops_number 0), we\n        recommand using a wider range of scale (\"--global_crops_scale 0.14 1.\" for example)\"\"\")\n    parser.add_argument('--local_crops_number', type=int, default=8, help=\"\"\"Number of small\n        local views to generate. Set this parameter to 0 to disable multi-crop training.\n        When disabling multi-crop we recommend to use \"--global_crops_scale 0.14 1.\" \"\"\")\n    parser.add_argument('--local_crops_scale', type=float, nargs='+', default=(0.05, 0.4),\n        help=\"\"\"Scale range of the cropped image before resizing, relatively to the origin image.\n        Used for small local view cropping of multi-crop.\"\"\")\n\n    # Misc\n    parser.add_argument('--data_path', default='/path/to/imagenet/train/', type=str,\n        help='Please specify path to the ImageNet training data.')\n    parser.add_argument('--output_dir', default=\".\", type=str, help='Path to save logs and checkpoints.')\n    parser.add_argument('--saveckp_freq', default=20, type=int, help='Save checkpoint every x epochs.')\n    parser.add_argument('--seed', default=0, type=int, help='Random seed.')\n    parser.add_argument('--num_workers', default=10, type=int, help='Number of data loading workers per GPU.')\n    parser.add_argument(\"--dist_url\", default=\"env://\", type=str, help=\"\"\"url used to set up\n        distributed training; see https://pytorch.org/docs/stable/distributed.html\"\"\")\n    parser.add_argument(\"--local_rank\", default=0, type=int, help=\"Please ignore and do not set this argument.\")\n    return parser\n\n\ndef train_dino(args):\n    utils.init_distributed_mode(args)\n    utils.fix_random_seeds(args.seed)\n    print(\"git:\\n  {}\\n\".format(utils.get_sha()))\n    print(\"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())))\n    cudnn.benchmark = True\n\n    # ============ preparing data ... ============\n    transform = DataAugmentationDINO(\n        args.global_crops_scale,\n        args.local_crops_scale,\n        args.local_crops_number,\n    )\n    dataset = datasets.ImageFolder(args.data_path, transform=transform)\n    sampler = torch.utils.data.DistributedSampler(dataset, shuffle=True)\n    data_loader = torch.utils.data.DataLoader(\n        dataset,\n        sampler=sampler,\n        batch_size=args.batch_size_per_gpu,\n        num_workers=args.num_workers,\n        pin_memory=True,\n        drop_last=True,\n    )\n    print(f\"Data loaded: there are {len(dataset)} images.\")\n\n    # ============ building student and teacher networks ... ============\n    # we changed the name DeiT-S for ViT-S to avoid confusions\n    args.arch = args.arch.replace(\"deit\", \"vit\")\n    # if the network is a Vision Transformer (i.e. vit_tiny, vit_small, vit_base)\n    if args.arch in vits.__dict__.keys():\n        student = vits.__dict__[args.arch](\n            patch_size=args.patch_size,\n            drop_path_rate=args.drop_path_rate,  # stochastic depth\n        )\n        teacher = vits.__dict__[args.arch](patch_size=args.patch_size)\n        embed_dim = student.embed_dim\n    # if the network is a XCiT\n    elif args.arch in torch.hub.list(\"facebookresearch/xcit:main\"):\n        student = torch.hub.load('facebookresearch/xcit:main', args.arch,\n                                 pretrained=False, drop_path_rate=args.drop_path_rate)\n        teacher = torch.hub.load('facebookresearch/xcit:main', args.arch, pretrained=False)\n        embed_dim = student.embed_dim\n    # otherwise, we check if the architecture is in torchvision models\n    elif args.arch in torchvision_models.__dict__.keys():\n        student = torchvision_models.__dict__[args.arch]()\n        teacher = torchvision_models.__dict__[args.arch]()\n        embed_dim = student.fc.weight.shape[1]\n    else:\n        print(f\"Unknow architecture: {args.arch}\")\n\n    # multi-crop wrapper handles forward with inputs of different resolutions\n    student = utils.MultiCropWrapper(student, DINOHead(\n        embed_dim,\n        args.out_dim,\n        use_bn=args.use_bn_in_head,\n        norm_last_layer=args.norm_last_layer,\n    ))\n    teacher = utils.MultiCropWrapper(\n        teacher,\n        DINOHead(embed_dim, args.out_dim, args.use_bn_in_head),\n    )\n    # move networks to gpu\n    student, teacher = student.cuda(), teacher.cuda()\n    # synchronize batch norms (if any)\n    if utils.has_batchnorms(student):\n        student = nn.SyncBatchNorm.convert_sync_batchnorm(student)\n        teacher = nn.SyncBatchNorm.convert_sync_batchnorm(teacher)\n\n        # we need DDP wrapper to have synchro batch norms working...\n        teacher = nn.parallel.DistributedDataParallel(teacher, device_ids=[args.gpu])\n        teacher_without_ddp = teacher.module\n    else:\n        # teacher_without_ddp and teacher are the same thing\n        teacher_without_ddp = teacher\n    student = nn.parallel.DistributedDataParallel(student, device_ids=[args.gpu])\n    # teacher and student start with the same weights\n    teacher_without_ddp.load_state_dict(student.module.state_dict())\n    # there is no backpropagation through the teacher, so no need for gradients\n    for p in teacher.parameters():\n        p.requires_grad = False\n    print(f\"Student and Teacher are built: they are both {args.arch} network.\")\n\n    # ============ preparing loss ... ============\n    dino_loss = DINOLoss(\n        args.out_dim,\n        args.local_crops_number + 2,  # total number of crops = 2 global crops + local_crops_number\n        args.warmup_teacher_temp,\n        args.teacher_temp,\n        args.warmup_teacher_temp_epochs,\n        args.epochs,\n    ).cuda()\n\n    # ============ preparing optimizer ... ============\n    params_groups = utils.get_params_groups(student)\n    if args.optimizer == \"adamw\":\n        optimizer = torch.optim.AdamW(params_groups)  # to use with ViTs\n    elif args.optimizer == \"sgd\":\n        optimizer = torch.optim.SGD(params_groups, lr=0, momentum=0.9)  # lr is set by scheduler\n    elif args.optimizer == \"lars\":\n        optimizer = utils.LARS(params_groups)  # to use with convnet and large batches\n    # for mixed precision training\n    fp16_scaler = None\n    if args.use_fp16:\n        fp16_scaler = torch.cuda.amp.GradScaler()\n\n    # ============ init schedulers ... ============\n    lr_schedule = utils.cosine_scheduler(\n        args.lr * (args.batch_size_per_gpu * utils.get_world_size()) / 256.,  # linear scaling rule\n        args.min_lr,\n        args.epochs, len(data_loader),\n        warmup_epochs=args.warmup_epochs,\n    )\n    wd_schedule = utils.cosine_scheduler(\n        args.weight_decay,\n        args.weight_decay_end,\n        args.epochs, len(data_loader),\n    )\n    # momentum parameter is increased to 1. during training with a cosine schedule\n    momentum_schedule = utils.cosine_scheduler(args.momentum_teacher, 1,\n                                               args.epochs, len(data_loader))\n    print(f\"Loss, optimizer and schedulers ready.\")\n\n    # ============ optionally resume training ... ============\n    to_restore = {\"epoch\": 0}\n    utils.restart_from_checkpoint(\n        os.path.join(args.output_dir, \"checkpoint.pth\"),\n        run_variables=to_restore,\n        student=student,\n        teacher=teacher,\n        optimizer=optimizer,\n        fp16_scaler=fp16_scaler,\n        dino_loss=dino_loss,\n    )\n    start_epoch = to_restore[\"epoch\"]\n\n    start_time = time.time()\n    print(\"Starting DINO training !\")\n    for epoch in range(start_epoch, args.epochs):\n        data_loader.sampler.set_epoch(epoch)\n\n        # ============ training one epoch of DINO ... ============\n        train_stats = train_one_epoch(student, teacher, teacher_without_ddp, dino_loss,\n            data_loader, optimizer, lr_schedule, wd_schedule, momentum_schedule,\n            epoch, fp16_scaler, args)\n\n        # ============ writing logs ... ============\n        save_dict = {\n            'student': student.state_dict(),\n            'teacher': teacher.state_dict(),\n            'optimizer': optimizer.state_dict(),\n            'epoch': epoch + 1,\n            'args': args,\n            'dino_loss': dino_loss.state_dict(),\n        }\n        if fp16_scaler is not None:\n            save_dict['fp16_scaler'] = fp16_scaler.state_dict()\n        utils.save_on_master(save_dict, os.path.join(args.output_dir, 'checkpoint.pth'))\n        if args.saveckp_freq and epoch % args.saveckp_freq == 0:\n            utils.save_on_master(save_dict, os.path.join(args.output_dir, f'checkpoint{epoch:04}.pth'))\n        log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},\n                     'epoch': epoch}\n        if utils.is_main_process():\n            with (Path(args.output_dir) / \"log.txt\").open(\"a\") as f:\n                f.write(json.dumps(log_stats) + \"\\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\ndef train_one_epoch(student, teacher, teacher_without_ddp, dino_loss, data_loader,\n                    optimizer, lr_schedule, wd_schedule, momentum_schedule,epoch,\n                    fp16_scaler, args):\n    metric_logger = utils.MetricLogger(delimiter=\"  \")\n    header = 'Epoch: [{}/{}]'.format(epoch, args.epochs)\n    for it, (images, _) in enumerate(metric_logger.log_every(data_loader, 10, header)):\n        # update weight decay and learning rate according to their schedule\n        it = len(data_loader) * epoch + it  # global training iteration\n        for i, param_group in enumerate(optimizer.param_groups):\n            param_group[\"lr\"] = lr_schedule[it]\n            if i == 0:  # only the first group is regularized\n                param_group[\"weight_decay\"] = wd_schedule[it]\n\n        # move images to gpu\n        images = [im.cuda(non_blocking=True) for im in images]\n        # teacher and student forward passes + compute dino loss\n        with torch.cuda.amp.autocast(fp16_scaler is not None):\n            teacher_output = teacher(images[:2])  # only the 2 global views pass through the teacher\n            student_output = student(images)\n            loss = dino_loss(student_output, teacher_output, epoch)\n\n        if not math.isfinite(loss.item()):\n            print(\"Loss is {}, stopping training\".format(loss.item()), force=True)\n            sys.exit(1)\n\n        # student update\n        optimizer.zero_grad()\n        param_norms = None\n        if fp16_scaler is None:\n            loss.backward()\n            if args.clip_grad:\n                param_norms = utils.clip_gradients(student, args.clip_grad)\n            utils.cancel_gradients_last_layer(epoch, student,\n                                              args.freeze_last_layer)\n            optimizer.step()\n        else:\n            fp16_scaler.scale(loss).backward()\n            if args.clip_grad:\n                fp16_scaler.unscale_(optimizer)  # unscale the gradients of optimizer's assigned params in-place\n                param_norms = utils.clip_gradients(student, args.clip_grad)\n            utils.cancel_gradients_last_layer(epoch, student,\n                                              args.freeze_last_layer)\n            fp16_scaler.step(optimizer)\n            fp16_scaler.update()\n\n        # EMA update for the teacher\n        with torch.no_grad():\n            m = momentum_schedule[it]  # momentum parameter\n            for param_q, param_k in zip(student.module.parameters(), teacher_without_ddp.parameters()):\n                param_k.data.mul_(m).add_((1 - m) * param_q.detach().data)\n\n        # logging\n        torch.cuda.synchronize()\n        metric_logger.update(loss=loss.item())\n        metric_logger.update(lr=optimizer.param_groups[0][\"lr\"])\n        metric_logger.update(wd=optimizer.param_groups[0][\"weight_decay\"])\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\nclass DINOLoss(nn.Module):\n    def __init__(self, out_dim, ncrops, warmup_teacher_temp, teacher_temp,\n                 warmup_teacher_temp_epochs, nepochs, student_temp=0.1,\n                 center_momentum=0.9):\n        super().__init__()\n        self.student_temp = student_temp\n        self.center_momentum = center_momentum\n        self.ncrops = ncrops\n        self.register_buffer(\"center\", torch.zeros(1, out_dim))\n        # we apply a warm up for the teacher temperature because\n        # a too high temperature makes the training instable at the beginning\n        self.teacher_temp_schedule = np.concatenate((\n            np.linspace(warmup_teacher_temp,\n                        teacher_temp, warmup_teacher_temp_epochs),\n            np.ones(nepochs - warmup_teacher_temp_epochs) * teacher_temp\n        ))\n\n    def forward(self, student_output, teacher_output, epoch):\n        \"\"\"\n        Cross-entropy between softmax outputs of the teacher and student networks.\n        \"\"\"\n        student_out = student_output / self.student_temp\n        student_out = student_out.chunk(self.ncrops)\n\n        # teacher centering and sharpening\n        temp = self.teacher_temp_schedule[epoch]\n        teacher_out = F.softmax((teacher_output - self.center) / temp, dim=-1)\n        teacher_out = teacher_out.detach().chunk(2)\n\n        total_loss = 0\n        n_loss_terms = 0\n        for iq, q in enumerate(teacher_out):\n            for v in range(len(student_out)):\n                if v == iq:\n                    # we skip cases where student and teacher operate on the same view\n                    continue\n                loss = torch.sum(-q * F.log_softmax(student_out[v], dim=-1), dim=-1)\n                total_loss += loss.mean()\n                n_loss_terms += 1\n        total_loss /= n_loss_terms\n        self.update_center(teacher_output)\n        return total_loss\n\n    @torch.no_grad()\n    def update_center(self, teacher_output):\n        \"\"\"\n        Update center used for teacher output.\n        \"\"\"\n        batch_center = torch.sum(teacher_output, dim=0, keepdim=True)\n        dist.all_reduce(batch_center)\n        batch_center = batch_center / (len(teacher_output) * dist.get_world_size())\n\n        # ema update\n        self.center = self.center * self.center_momentum + batch_center * (1 - self.center_momentum)\n\n\nclass DataAugmentationDINO(object):\n    def __init__(self, global_crops_scale, local_crops_scale, local_crops_number):\n        flip_and_color_jitter = transforms.Compose([\n            transforms.RandomHorizontalFlip(p=0.5),\n            transforms.RandomApply(\n                [transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)],\n                p=0.8\n            ),\n            transforms.RandomGrayscale(p=0.2),\n        ])\n        normalize = transforms.Compose([\n            transforms.ToTensor(),\n            transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n        ])\n\n        # first global crop\n        self.global_transfo1 = transforms.Compose([\n            transforms.RandomResizedCrop(224, scale=global_crops_scale, interpolation=Image.BICUBIC),\n            flip_and_color_jitter,\n            utils.GaussianBlur(1.0),\n            normalize,\n        ])\n        # second global crop\n        self.global_transfo2 = transforms.Compose([\n            transforms.RandomResizedCrop(224, scale=global_crops_scale, interpolation=Image.BICUBIC),\n            flip_and_color_jitter,\n            utils.GaussianBlur(0.1),\n            utils.Solarization(0.2),\n            normalize,\n        ])\n        # transformation for the local small crops\n        self.local_crops_number = local_crops_number\n        self.local_transfo = transforms.Compose([\n            transforms.RandomResizedCrop(96, scale=local_crops_scale, interpolation=Image.BICUBIC),\n            flip_and_color_jitter,\n            utils.GaussianBlur(p=0.5),\n            normalize,\n        ])\n\n    def __call__(self, image):\n        crops = []\n        crops.append(self.global_transfo1(image))\n        crops.append(self.global_transfo2(image))\n        for _ in range(self.local_crops_number):\n            crops.append(self.local_transfo(image))\n        return crops\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('DINO', parents=[get_args_parser()])\n    args = parser.parse_args()\n    Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n    train_dino(args)\n"
  },
  {
    "path": "run_with_submitit.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"\nA script to run multinode training with submitit.\nAlmost copy-paste from https://github.com/facebookresearch/deit/blob/main/run_with_submitit.py\n\"\"\"\nimport argparse\nimport os\nimport uuid\nfrom pathlib import Path\n\nimport main_dino\nimport submitit\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\"Submitit for DINO\", parents=[main_dino.get_args_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=2, type=int, help=\"Number of nodes to request\")\n    parser.add_argument(\"--timeout\", default=2800, type=int, help=\"Duration of the job\")\n\n    parser.add_argument(\"--partition\", default=\"learnfair\", type=str, help=\"Partition where to submit\")\n    parser.add_argument(\"--use_volta32\", action='store_true', help=\"Big models? Use this\")\n    parser.add_argument('--comment', default=\"\", type=str,\n                        help='Comment to pass to scheduler, e.g. priority message')\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_dino\n\n        self._setup_gpu_args()\n        main_dino.train_dino(self.args)\n\n    def checkpoint(self):\n        import os\n        import submitit\n\n        self.args.dist_url = get_init_file().as_uri()\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.output_dir == \"\":\n        args.output_dir = get_shared_folder() / \"%j\"\n    Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n    executor = submitit.AutoExecutor(folder=args.output_dir, slurm_max_num_timeout=30)\n\n    num_gpus_per_node = args.ngpus\n    nodes = args.nodes\n    timeout_min = args.timeout\n\n    partition = args.partition\n    kwargs = {}\n    if args.use_volta32:\n        kwargs['slurm_constraint'] = 'volta32gb'\n    if args.comment:\n        kwargs['slurm_comment'] = args.comment\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        # Below are cluster dependent parameters\n        slurm_partition=partition,\n        slurm_signal_delay_s=120,\n        **kwargs\n    )\n\n    executor.update_parameters(name=\"dino\")\n\n    args.dist_url = get_init_file().as_uri()\n\n    trainer = Trainer(args)\n    job = executor.submit(trainer)\n\n    print(f\"Submitted job_id: {job.job_id}\")\n    print(f\"Logs and checkpoints will be saved at: {args.output_dir}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "utils.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"\nMisc functions.\n\nMostly copy-paste from torchvision references or other public repos like DETR:\nhttps://github.com/facebookresearch/detr/blob/master/util/misc.py\n\"\"\"\nimport os\nimport sys\nimport time\nimport math\nimport random\nimport datetime\nimport subprocess\nfrom collections import defaultdict, deque\n\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.distributed as dist\nfrom PIL import ImageFilter, ImageOps\n\n\nclass GaussianBlur(object):\n    \"\"\"\n    Apply Gaussian Blur to the PIL image.\n    \"\"\"\n    def __init__(self, p=0.5, radius_min=0.1, radius_max=2.):\n        self.prob = p\n        self.radius_min = radius_min\n        self.radius_max = radius_max\n\n    def __call__(self, img):\n        do_it = random.random() <= self.prob\n        if not do_it:\n            return img\n\n        return img.filter(\n            ImageFilter.GaussianBlur(\n                radius=random.uniform(self.radius_min, self.radius_max)\n            )\n        )\n\n\nclass Solarization(object):\n    \"\"\"\n    Apply Solarization to the PIL image.\n    \"\"\"\n    def __init__(self, p):\n        self.p = p\n\n    def __call__(self, img):\n        if random.random() < self.p:\n            return ImageOps.solarize(img)\n        else:\n            return img\n\n\ndef load_pretrained_weights(model, pretrained_weights, checkpoint_key, model_name, patch_size):\n    if os.path.isfile(pretrained_weights):\n        state_dict = torch.load(pretrained_weights, map_location=\"cpu\")\n        if checkpoint_key is not None and checkpoint_key in state_dict:\n            print(f\"Take key {checkpoint_key} in provided checkpoint dict\")\n            state_dict = state_dict[checkpoint_key]\n        # remove `module.` prefix\n        state_dict = {k.replace(\"module.\", \"\"): v for k, v in state_dict.items()}\n        # remove `backbone.` prefix induced by multicrop wrapper\n        state_dict = {k.replace(\"backbone.\", \"\"): v for k, v in state_dict.items()}\n        msg = model.load_state_dict(state_dict, strict=False)\n        print('Pretrained weights found at {} and loaded with msg: {}'.format(pretrained_weights, msg))\n    else:\n        print(\"Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate.\")\n        url = None\n        if model_name == \"vit_small\" and patch_size == 16:\n            url = \"dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth\"\n        elif model_name == \"vit_small\" and patch_size == 8:\n            url = \"dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth\"\n        elif model_name == \"vit_base\" and patch_size == 16:\n            url = \"dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth\"\n        elif model_name == \"vit_base\" and patch_size == 8:\n            url = \"dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth\"\n        elif model_name == \"xcit_small_12_p16\":\n            url = \"dino_xcit_small_12_p16_pretrain/dino_xcit_small_12_p16_pretrain.pth\"\n        elif model_name == \"xcit_small_12_p8\":\n            url = \"dino_xcit_small_12_p8_pretrain/dino_xcit_small_12_p8_pretrain.pth\"\n        elif model_name == \"xcit_medium_24_p16\":\n            url = \"dino_xcit_medium_24_p16_pretrain/dino_xcit_medium_24_p16_pretrain.pth\"\n        elif model_name == \"xcit_medium_24_p8\":\n            url = \"dino_xcit_medium_24_p8_pretrain/dino_xcit_medium_24_p8_pretrain.pth\"\n        elif model_name == \"resnet50\":\n            url = \"dino_resnet50_pretrain/dino_resnet50_pretrain.pth\"\n        if url is not None:\n            print(\"Since no pretrained weights have been provided, we load the reference pretrained DINO weights.\")\n            state_dict = torch.hub.load_state_dict_from_url(url=\"https://dl.fbaipublicfiles.com/dino/\" + url)\n            model.load_state_dict(state_dict, strict=True)\n        else:\n            print(\"There is no reference weights available for this model => We use random weights.\")\n\n\ndef load_pretrained_linear_weights(linear_classifier, model_name, patch_size):\n    url = None\n    if model_name == \"vit_small\" and patch_size == 16:\n        url = \"dino_deitsmall16_pretrain/dino_deitsmall16_linearweights.pth\"\n    elif model_name == \"vit_small\" and patch_size == 8:\n        url = \"dino_deitsmall8_pretrain/dino_deitsmall8_linearweights.pth\"\n    elif model_name == \"vit_base\" and patch_size == 16:\n        url = \"dino_vitbase16_pretrain/dino_vitbase16_linearweights.pth\"\n    elif model_name == \"vit_base\" and patch_size == 8:\n        url = \"dino_vitbase8_pretrain/dino_vitbase8_linearweights.pth\"\n    elif model_name == \"resnet50\":\n        url = \"dino_resnet50_pretrain/dino_resnet50_linearweights.pth\"\n    if url is not None:\n        print(\"We load the reference pretrained linear weights.\")\n        state_dict = torch.hub.load_state_dict_from_url(url=\"https://dl.fbaipublicfiles.com/dino/\" + url)[\"state_dict\"]\n        linear_classifier.load_state_dict(state_dict, strict=True)\n    else:\n        print(\"We use random linear weights.\")\n\n\ndef clip_gradients(model, clip):\n    norms = []\n    for name, p in model.named_parameters():\n        if p.grad is not None:\n            param_norm = p.grad.data.norm(2)\n            norms.append(param_norm.item())\n            clip_coef = clip / (param_norm + 1e-6)\n            if clip_coef < 1:\n                p.grad.data.mul_(clip_coef)\n    return norms\n\n\ndef cancel_gradients_last_layer(epoch, model, freeze_last_layer):\n    if epoch >= freeze_last_layer:\n        return\n    for n, p in model.named_parameters():\n        if \"last_layer\" in n:\n            p.grad = None\n\n\ndef restart_from_checkpoint(ckp_path, run_variables=None, **kwargs):\n    \"\"\"\n    Re-start from checkpoint\n    \"\"\"\n    if not os.path.isfile(ckp_path):\n        return\n    print(\"Found checkpoint at {}\".format(ckp_path))\n\n    # open checkpoint file\n    checkpoint = torch.load(ckp_path, map_location=\"cpu\")\n\n    # key is what to look for in the checkpoint file\n    # value is the object to load\n    # example: {'state_dict': model}\n    for key, value in kwargs.items():\n        if key in checkpoint and value is not None:\n            try:\n                msg = value.load_state_dict(checkpoint[key], strict=False)\n                print(\"=> loaded '{}' from checkpoint '{}' with msg {}\".format(key, ckp_path, msg))\n            except TypeError:\n                try:\n                    msg = value.load_state_dict(checkpoint[key])\n                    print(\"=> loaded '{}' from checkpoint: '{}'\".format(key, ckp_path))\n                except ValueError:\n                    print(\"=> failed to load '{}' from checkpoint: '{}'\".format(key, ckp_path))\n        else:\n            print(\"=> key '{}' not found in checkpoint: '{}'\".format(key, ckp_path))\n\n    # re load variable important for the run\n    if run_variables is not None:\n        for var_name in run_variables:\n            if var_name in checkpoint:\n                run_variables[var_name] = checkpoint[var_name]\n\n\ndef cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0):\n    warmup_schedule = np.array([])\n    warmup_iters = warmup_epochs * niter_per_ep\n    if warmup_epochs > 0:\n        warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)\n\n    iters = np.arange(epochs * niter_per_ep - warmup_iters)\n    schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters)))\n\n    schedule = np.concatenate((warmup_schedule, schedule))\n    assert len(schedule) == epochs * niter_per_ep\n    return schedule\n\n\ndef bool_flag(s):\n    \"\"\"\n    Parse boolean arguments from the command line.\n    \"\"\"\n    FALSY_STRINGS = {\"off\", \"false\", \"0\"}\n    TRUTHY_STRINGS = {\"on\", \"true\", \"1\"}\n    if s.lower() in FALSY_STRINGS:\n        return False\n    elif s.lower() in TRUTHY_STRINGS:\n        return True\n    else:\n        raise argparse.ArgumentTypeError(\"invalid value for a boolean flag\")\n\n\ndef fix_random_seeds(seed=31):\n    \"\"\"\n    Fix random seeds.\n    \"\"\"\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    np.random.seed(seed)\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:.6f} ({global_avg:.6f})\"\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 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:.6f}')\n        data_time = SmoothedValue(fmt='{avg:.6f}')\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: {} ({:.6f} 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 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 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 init_distributed_mode(args):\n    # launched with torch.distributed.launch\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    # launched with submitit on a slurm cluster\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    # launched naively with `python main_dino.py`\n    # we manually add MASTER_ADDR and MASTER_PORT to env variables\n    elif torch.cuda.is_available():\n        print('Will run the code on one GPU.')\n        args.rank, args.gpu, args.world_size = 0, 0, 1\n        os.environ['MASTER_ADDR'] = '127.0.0.1'\n        os.environ['MASTER_PORT'] = '29500'\n    else:\n        print('Does not support training without GPU.')\n        sys.exit(1)\n\n    dist.init_process_group(\n        backend=\"nccl\",\n        init_method=args.dist_url,\n        world_size=args.world_size,\n        rank=args.rank,\n    )\n\n    torch.cuda.set_device(args.gpu)\n    print('| distributed init (rank {}): {}'.format(\n        args.rank, args.dist_url), flush=True)\n    dist.barrier()\n    setup_for_distributed(args.rank == 0)\n\n\ndef accuracy(output, target, topk=(1,)):\n    \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n    maxk = max(topk)\n    batch_size = target.size(0)\n    _, pred = output.topk(maxk, 1, True, True)\n    pred = pred.t()\n    correct = pred.eq(target.reshape(1, -1).expand_as(pred))\n    return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]\n\n\ndef _no_grad_trunc_normal_(tensor, mean, std, a, b):\n    # Cut & paste from PyTorch official master until it's in a few official releases - RW\n    # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf\n    def norm_cdf(x):\n        # Computes standard normal cumulative distribution function\n        return (1. + math.erf(x / math.sqrt(2.))) / 2.\n\n    if (mean < a - 2 * std) or (mean > b + 2 * std):\n        warnings.warn(\"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. \"\n                      \"The distribution of values may be incorrect.\",\n                      stacklevel=2)\n\n    with torch.no_grad():\n        # Values are generated by using a truncated uniform distribution and\n        # then using the inverse CDF for the normal distribution.\n        # Get upper and lower cdf values\n        l = norm_cdf((a - mean) / std)\n        u = norm_cdf((b - mean) / std)\n\n        # Uniformly fill tensor with values from [l, u], then translate to\n        # [2l-1, 2u-1].\n        tensor.uniform_(2 * l - 1, 2 * u - 1)\n\n        # Use inverse cdf transform for normal distribution to get truncated\n        # standard normal\n        tensor.erfinv_()\n\n        # Transform to proper mean, std\n        tensor.mul_(std * math.sqrt(2.))\n        tensor.add_(mean)\n\n        # Clamp to ensure it's in the proper range\n        tensor.clamp_(min=a, max=b)\n        return tensor\n\n\ndef trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):\n    # type: (Tensor, float, float, float, float) -> Tensor\n    return _no_grad_trunc_normal_(tensor, mean, std, a, b)\n\n\nclass LARS(torch.optim.Optimizer):\n    \"\"\"\n    Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py\n    \"\"\"\n    def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, eta=0.001,\n                 weight_decay_filter=None, lars_adaptation_filter=None):\n        defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum,\n                        eta=eta, weight_decay_filter=weight_decay_filter,\n                        lars_adaptation_filter=lars_adaptation_filter)\n        super().__init__(params, defaults)\n\n    @torch.no_grad()\n    def step(self):\n        for g in self.param_groups:\n            for p in g['params']:\n                dp = p.grad\n\n                if dp is None:\n                    continue\n\n                if p.ndim != 1:\n                    dp = dp.add(p, alpha=g['weight_decay'])\n\n                if p.ndim != 1:\n                    param_norm = torch.norm(p)\n                    update_norm = torch.norm(dp)\n                    one = torch.ones_like(param_norm)\n                    q = torch.where(param_norm > 0.,\n                                    torch.where(update_norm > 0,\n                                                (g['eta'] * param_norm / update_norm), one), one)\n                    dp = dp.mul(q)\n\n                param_state = self.state[p]\n                if 'mu' not in param_state:\n                    param_state['mu'] = torch.zeros_like(p)\n                mu = param_state['mu']\n                mu.mul_(g['momentum']).add_(dp)\n\n                p.add_(mu, alpha=-g['lr'])\n\n\nclass MultiCropWrapper(nn.Module):\n    \"\"\"\n    Perform forward pass separately on each resolution input.\n    The inputs corresponding to a single resolution are clubbed and single\n    forward is run on the same resolution inputs. Hence we do several\n    forward passes = number of different resolutions used. We then\n    concatenate all the output features and run the head forward on these\n    concatenated features.\n    \"\"\"\n    def __init__(self, backbone, head):\n        super(MultiCropWrapper, self).__init__()\n        # disable layers dedicated to ImageNet labels classification\n        backbone.fc, backbone.head = nn.Identity(), nn.Identity()\n        self.backbone = backbone\n        self.head = head\n\n    def forward(self, x):\n        # convert to list\n        if not isinstance(x, list):\n            x = [x]\n        idx_crops = torch.cumsum(torch.unique_consecutive(\n            torch.tensor([inp.shape[-1] for inp in x]),\n            return_counts=True,\n        )[1], 0)\n        start_idx, output = 0, torch.empty(0).to(x[0].device)\n        for end_idx in idx_crops:\n            _out = self.backbone(torch.cat(x[start_idx: end_idx]))\n            # The output is a tuple with XCiT model. See:\n            # https://github.com/facebookresearch/xcit/blob/master/xcit.py#L404-L405\n            if isinstance(_out, tuple):\n                _out = _out[0]\n            # accumulate outputs\n            output = torch.cat((output, _out))\n            start_idx = end_idx\n        # Run the head forward on the concatenated features.\n        return self.head(output)\n\n\ndef get_params_groups(model):\n    regularized = []\n    not_regularized = []\n    for name, param in model.named_parameters():\n        if not param.requires_grad:\n            continue\n        # we do not regularize biases nor Norm parameters\n        if name.endswith(\".bias\") or len(param.shape) == 1:\n            not_regularized.append(param)\n        else:\n            regularized.append(param)\n    return [{'params': regularized}, {'params': not_regularized, 'weight_decay': 0.}]\n\n\ndef has_batchnorms(model):\n    bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)\n    for name, module in model.named_modules():\n        if isinstance(module, bn_types):\n            return True\n    return False\n\n\nclass PCA():\n    \"\"\"\n    Class to  compute and apply PCA.\n    \"\"\"\n    def __init__(self, dim=256, whit=0.5):\n        self.dim = dim\n        self.whit = whit\n        self.mean = None\n\n    def train_pca(self, cov):\n        \"\"\"\n        Takes a covariance matrix (np.ndarray) as input.\n        \"\"\"\n        d, v = np.linalg.eigh(cov)\n        eps = d.max() * 1e-5\n        n_0 = (d < eps).sum()\n        if n_0 > 0:\n            d[d < eps] = eps\n\n        # total energy\n        totenergy = d.sum()\n\n        # sort eigenvectors with eigenvalues order\n        idx = np.argsort(d)[::-1][:self.dim]\n        d = d[idx]\n        v = v[:, idx]\n\n        print(\"keeping %.2f %% of the energy\" % (d.sum() / totenergy * 100.0))\n\n        # for the whitening\n        d = np.diag(1. / d**self.whit)\n\n        # principal components\n        self.dvt = np.dot(d, v.T)\n\n    def apply(self, x):\n        # input is from numpy\n        if isinstance(x, np.ndarray):\n            if self.mean is not None:\n                x -= self.mean\n            return np.dot(self.dvt, x.T).T\n\n        # input is from torch and is on GPU\n        if x.is_cuda:\n            if self.mean is not None:\n                x -= torch.cuda.FloatTensor(self.mean)\n            return torch.mm(torch.cuda.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1)\n\n        # input if from torch, on CPU\n        if self.mean is not None:\n            x -= torch.FloatTensor(self.mean)\n        return torch.mm(torch.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1)\n\n\ndef compute_ap(ranks, nres):\n    \"\"\"\n    Computes average precision for given ranked indexes.\n    Arguments\n    ---------\n    ranks : zerro-based ranks of positive images\n    nres  : number of positive images\n    Returns\n    -------\n    ap    : average precision\n    \"\"\"\n\n    # number of images ranked by the system\n    nimgranks = len(ranks)\n\n    # accumulate trapezoids in PR-plot\n    ap = 0\n\n    recall_step = 1. / nres\n\n    for j in np.arange(nimgranks):\n        rank = ranks[j]\n\n        if rank == 0:\n            precision_0 = 1.\n        else:\n            precision_0 = float(j) / rank\n\n        precision_1 = float(j + 1) / (rank + 1)\n\n        ap += (precision_0 + precision_1) * recall_step / 2.\n\n    return ap\n\n\ndef compute_map(ranks, gnd, kappas=[]):\n    \"\"\"\n    Computes the mAP for a given set of returned results.\n         Usage:\n           map = compute_map (ranks, gnd)\n                 computes mean average precsion (map) only\n           map, aps, pr, prs = compute_map (ranks, gnd, kappas)\n                 computes mean average precision (map), average precision (aps) for each query\n                 computes mean precision at kappas (pr), precision at kappas (prs) for each query\n         Notes:\n         1) ranks starts from 0, ranks.shape = db_size X #queries\n         2) The junk results (e.g., the query itself) should be declared in the gnd stuct array\n         3) If there are no positive images for some query, that query is excluded from the evaluation\n    \"\"\"\n\n    map = 0.\n    nq = len(gnd) # number of queries\n    aps = np.zeros(nq)\n    pr = np.zeros(len(kappas))\n    prs = np.zeros((nq, len(kappas)))\n    nempty = 0\n\n    for i in np.arange(nq):\n        qgnd = np.array(gnd[i]['ok'])\n\n        # no positive images, skip from the average\n        if qgnd.shape[0] == 0:\n            aps[i] = float('nan')\n            prs[i, :] = float('nan')\n            nempty += 1\n            continue\n\n        try:\n            qgndj = np.array(gnd[i]['junk'])\n        except:\n            qgndj = np.empty(0)\n\n        # sorted positions of positive and junk images (0 based)\n        pos  = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgnd)]\n        junk = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgndj)]\n\n        k = 0;\n        ij = 0;\n        if len(junk):\n            # decrease positions of positives based on the number of\n            # junk images appearing before them\n            ip = 0\n            while (ip < len(pos)):\n                while (ij < len(junk) and pos[ip] > junk[ij]):\n                    k += 1\n                    ij += 1\n                pos[ip] = pos[ip] - k\n                ip += 1\n\n        # compute ap\n        ap = compute_ap(pos, len(qgnd))\n        map = map + ap\n        aps[i] = ap\n\n        # compute precision @ k\n        pos += 1 # get it to 1-based\n        for j in np.arange(len(kappas)):\n            kq = min(max(pos), kappas[j]); \n            prs[i, j] = (pos <= kq).sum() / kq\n        pr = pr + prs[i, :]\n\n    map = map / (nq - nempty)\n    pr = pr / (nq - nempty)\n\n    return map, aps, pr, prs\n\n\ndef multi_scale(samples, model):\n    v = None\n    for s in [1, 1/2**(1/2), 1/2]:  # we use 3 different scales\n        if s == 1:\n            inp = samples.clone()\n        else:\n            inp = nn.functional.interpolate(samples, scale_factor=s, mode='bilinear', align_corners=False)\n        feats = model(inp).clone()\n        if v is None:\n            v = feats\n        else:\n            v += feats\n    v /= 3\n    v /= v.norm()\n    return v\n"
  },
  {
    "path": "video_generation.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport os\nimport glob\nimport sys\nimport argparse\nimport cv2\n\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom torchvision import transforms as pth_transforms\nimport numpy as np\nfrom PIL import Image\n\nimport utils\nimport vision_transformer as vits\n\n\nFOURCC = {\n    \"mp4\": cv2.VideoWriter_fourcc(*\"MP4V\"),\n    \"avi\": cv2.VideoWriter_fourcc(*\"XVID\"),\n}\nDEVICE = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\n\nclass VideoGenerator:\n    def __init__(self, args):\n        self.args = args\n        # self.model = None\n        # Don't need to load model if you only want a video\n        if not self.args.video_only:\n            self.model = self.__load_model()\n\n    def run(self):\n        if self.args.input_path is None:\n            print(f\"Provided input path {self.args.input_path} is non valid.\")\n            sys.exit(1)\n        else:\n            if self.args.video_only:\n                self._generate_video_from_images(\n                    self.args.input_path, self.args.output_path\n                )\n            else:\n                # If input path exists\n                if os.path.exists(self.args.input_path):\n                    # If input is a video file\n                    if os.path.isfile(self.args.input_path):\n                        frames_folder = os.path.join(self.args.output_path, \"frames\")\n                        attention_folder = os.path.join(\n                            self.args.output_path, \"attention\"\n                        )\n\n                        os.makedirs(frames_folder, exist_ok=True)\n                        os.makedirs(attention_folder, exist_ok=True)\n\n                        self._extract_frames_from_video(\n                            self.args.input_path, frames_folder\n                        )\n\n                        self._inference(\n                            frames_folder,\n                            attention_folder,\n                        )\n\n                        self._generate_video_from_images(\n                            attention_folder, self.args.output_path\n                        )\n\n                    # If input is a folder of already extracted frames\n                    if os.path.isdir(self.args.input_path):\n                        attention_folder = os.path.join(\n                            self.args.output_path, \"attention\"\n                        )\n\n                        os.makedirs(attention_folder, exist_ok=True)\n\n                        self._inference(self.args.input_path, attention_folder)\n\n                        self._generate_video_from_images(\n                            attention_folder, self.args.output_path\n                        )\n\n                # If input path doesn't exists\n                else:\n                    print(f\"Provided input path {self.args.input_path} doesn't exists.\")\n                    sys.exit(1)\n\n    def _extract_frames_from_video(self, inp: str, out: str):\n        vidcap = cv2.VideoCapture(inp)\n        self.args.fps = vidcap.get(cv2.CAP_PROP_FPS)\n\n        print(f\"Video: {inp} ({self.args.fps} fps)\")\n        print(f\"Extracting frames to {out}\")\n\n        success, image = vidcap.read()\n        count = 0\n        while success:\n            cv2.imwrite(\n                os.path.join(out, f\"frame-{count:04}.jpg\"),\n                image,\n            )\n            success, image = vidcap.read()\n            count += 1\n\n    def _generate_video_from_images(self, inp: str, out: str):\n        img_array = []\n        attention_images_list = sorted(glob.glob(os.path.join(inp, \"attn-*.jpg\")))\n\n        # Get size of the first image\n        with open(attention_images_list[0], \"rb\") as f:\n            img = Image.open(f)\n            img = img.convert(\"RGB\")\n            size = (img.width, img.height)\n            img_array.append(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))\n\n        print(f\"Generating video {size} to {out}\")\n\n        for filename in tqdm(attention_images_list[1:]):\n            with open(filename, \"rb\") as f:\n                img = Image.open(f)\n                img = img.convert(\"RGB\")\n                img_array.append(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))\n\n        out = cv2.VideoWriter(\n            os.path.join(out, \"video.\" + self.args.video_format),\n            FOURCC[self.args.video_format],\n            self.args.fps,\n            size,\n        )\n\n        for i in range(len(img_array)):\n            out.write(img_array[i])\n        out.release()\n        print(\"Done\")\n\n    def _inference(self, inp: str, out: str):\n        print(f\"Generating attention images to {out}\")\n\n        for img_path in tqdm(sorted(glob.glob(os.path.join(inp, \"*.jpg\")))):\n            with open(img_path, \"rb\") as f:\n                img = Image.open(f)\n                img = img.convert(\"RGB\")\n\n            if self.args.resize is not None:\n                transform = pth_transforms.Compose(\n                    [\n                        pth_transforms.ToTensor(),\n                        pth_transforms.Resize(self.args.resize),\n                        pth_transforms.Normalize(\n                            (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)\n                        ),\n                    ]\n                )\n            else:\n                transform = pth_transforms.Compose(\n                    [\n                        pth_transforms.ToTensor(),\n                        pth_transforms.Normalize(\n                            (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)\n                        ),\n                    ]\n                )\n\n            img = transform(img)\n\n            # make the image divisible by the patch size\n            w, h = (\n                img.shape[1] - img.shape[1] % self.args.patch_size,\n                img.shape[2] - img.shape[2] % self.args.patch_size,\n            )\n            img = img[:, :w, :h].unsqueeze(0)\n\n            w_featmap = img.shape[-2] // self.args.patch_size\n            h_featmap = img.shape[-1] // self.args.patch_size\n\n            attentions = self.model.get_last_selfattention(img.to(DEVICE))\n\n            nh = attentions.shape[1]  # number of head\n\n            # we keep only the output patch attention\n            attentions = attentions[0, :, 0, 1:].reshape(nh, -1)\n\n            # we keep only a certain percentage of the mass\n            val, idx = torch.sort(attentions)\n            val /= torch.sum(val, dim=1, keepdim=True)\n            cumval = torch.cumsum(val, dim=1)\n            th_attn = cumval > (1 - self.args.threshold)\n            idx2 = torch.argsort(idx)\n            for head in range(nh):\n                th_attn[head] = th_attn[head][idx2[head]]\n            th_attn = th_attn.reshape(nh, w_featmap, h_featmap).float()\n            # interpolate\n            th_attn = (\n                nn.functional.interpolate(\n                    th_attn.unsqueeze(0),\n                    scale_factor=self.args.patch_size,\n                    mode=\"nearest\",\n                )[0]\n                .cpu()\n                .numpy()\n            )\n\n            attentions = attentions.reshape(nh, w_featmap, h_featmap)\n            attentions = (\n                nn.functional.interpolate(\n                    attentions.unsqueeze(0),\n                    scale_factor=self.args.patch_size,\n                    mode=\"nearest\",\n                )[0]\n                .cpu()\n                .numpy()\n            )\n\n            # save attentions heatmaps\n            fname = os.path.join(out, \"attn-\" + os.path.basename(img_path))\n            plt.imsave(\n                fname=fname,\n                arr=sum(\n                    attentions[i] * 1 / attentions.shape[0]\n                    for i in range(attentions.shape[0])\n                ),\n                cmap=\"inferno\",\n                format=\"jpg\",\n            )\n\n    def __load_model(self):\n        # build model\n        model = vits.__dict__[self.args.arch](\n            patch_size=self.args.patch_size, num_classes=0\n        )\n        for p in model.parameters():\n            p.requires_grad = False\n        model.eval()\n        model.to(DEVICE)\n\n        if os.path.isfile(self.args.pretrained_weights):\n            state_dict = torch.load(self.args.pretrained_weights, map_location=\"cpu\")\n            if (\n                self.args.checkpoint_key is not None\n                and self.args.checkpoint_key in state_dict\n            ):\n                print(\n                    f\"Take key {self.args.checkpoint_key} in provided checkpoint dict\"\n                )\n                state_dict = state_dict[self.args.checkpoint_key]\n            state_dict = {k.replace(\"module.\", \"\"): v for k, v in state_dict.items()}\n            # remove `backbone.` prefix induced by multicrop wrapper\n            state_dict = {k.replace(\"backbone.\", \"\"): v for k, v in state_dict.items()}\n            msg = model.load_state_dict(state_dict, strict=False)\n            print(\n                \"Pretrained weights found at {} and loaded with msg: {}\".format(\n                    self.args.pretrained_weights, msg\n                )\n            )\n        else:\n            print(\n                \"Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate.\"\n            )\n            url = None\n            if self.args.arch == \"vit_small\" and self.args.patch_size == 16:\n                url = \"dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth\"\n            elif self.args.arch == \"vit_small\" and self.args.patch_size == 8:\n                url = \"dino_deitsmall8_300ep_pretrain/dino_deitsmall8_300ep_pretrain.pth\"  # model used for visualizations in our paper\n            elif self.args.arch == \"vit_base\" and self.args.patch_size == 16:\n                url = \"dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth\"\n            elif self.args.arch == \"vit_base\" and self.args.patch_size == 8:\n                url = \"dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth\"\n            if url is not None:\n                print(\n                    \"Since no pretrained weights have been provided, we load the reference pretrained DINO weights.\"\n                )\n                state_dict = torch.hub.load_state_dict_from_url(\n                    url=\"https://dl.fbaipublicfiles.com/dino/\" + url\n                )\n                model.load_state_dict(state_dict, strict=True)\n            else:\n                print(\n                    \"There is no reference weights available for this model => We use random weights.\"\n                )\n        return model\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(\"Generation self-attention video\")\n    parser.add_argument(\n        \"--arch\",\n        default=\"vit_small\",\n        type=str,\n        choices=[\"vit_tiny\", \"vit_small\", \"vit_base\"],\n        help=\"Architecture (support only ViT atm).\",\n    )\n    parser.add_argument(\n        \"--patch_size\", default=8, type=int, help=\"Patch resolution of the self.model.\"\n    )\n    parser.add_argument(\n        \"--pretrained_weights\",\n        default=\"\",\n        type=str,\n        help=\"Path to pretrained weights to load.\",\n    )\n    parser.add_argument(\n        \"--checkpoint_key\",\n        default=\"teacher\",\n        type=str,\n        help='Key to use in the checkpoint (example: \"teacher\")',\n    )\n    parser.add_argument(\n        \"--input_path\",\n        required=True,\n        type=str,\n        help=\"\"\"Path to a video file if you want to extract frames\n            or to a folder of images already extracted by yourself.\n            or to a folder of attention images.\"\"\",\n    )\n    parser.add_argument(\n        \"--output_path\",\n        default=\"./\",\n        type=str,\n        help=\"\"\"Path to store a folder of frames and / or a folder of attention images.\n            and / or a final video. Default to current directory.\"\"\",\n    )\n    parser.add_argument(\n        \"--threshold\",\n        type=float,\n        default=0.6,\n        help=\"\"\"We visualize masks\n        obtained by thresholding the self-attention maps to keep xx percent of the mass.\"\"\",\n    )\n    parser.add_argument(\n        \"--resize\",\n        default=None,\n        type=int,\n        nargs=\"+\",\n        help=\"\"\"Apply a resize transformation to input image(s). Use if OOM error.\n        Usage (single or W H): --resize 512, --resize 720 1280\"\"\",\n    )\n    parser.add_argument(\n        \"--video_only\",\n        action=\"store_true\",\n        help=\"\"\"Use this flag if you only want to generate a video and not all attention images.\n            If used, --input_path must be set to the folder of attention images. Ex: ./attention/\"\"\",\n    )\n    parser.add_argument(\n        \"--fps\",\n        default=30.0,\n        type=float,\n        help=\"FPS of input / output video. Automatically set if you extract frames from a video.\",\n    )\n    parser.add_argument(\n        \"--video_format\",\n        default=\"mp4\",\n        type=str,\n        choices=[\"mp4\", \"avi\"],\n        help=\"Format of generated video (mp4 or avi).\",\n    )\n\n    return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n    args = parse_args()\n\n    vg = VideoGenerator(args)\n    vg.run()\n"
  },
  {
    "path": "vision_transformer.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"\nMostly copy-paste from timm library.\nhttps://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py\n\"\"\"\nimport math\nfrom functools import partial\n\nimport torch\nimport torch.nn as nn\n\nfrom utils import trunc_normal_\n\n\ndef drop_path(x, drop_prob: float = 0., training: bool = False):\n    if drop_prob == 0. or not training:\n        return x\n    keep_prob = 1 - drop_prob\n    shape = (x.shape[0],) + (1,) * (x.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets\n    random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)\n    random_tensor.floor_()  # binarize\n    output = x.div(keep_prob) * random_tensor\n    return output\n\n\nclass DropPath(nn.Module):\n    \"\"\"Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).\n    \"\"\"\n    def __init__(self, drop_prob=None):\n        super(DropPath, self).__init__()\n        self.drop_prob = drop_prob\n\n    def forward(self, x):\n        return drop_path(x, self.drop_prob, self.training)\n\n\nclass Mlp(nn.Module):\n    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n        super().__init__()\n        out_features = out_features or in_features\n        hidden_features = hidden_features or in_features\n        self.fc1 = nn.Linear(in_features, hidden_features)\n        self.act = act_layer()\n        self.fc2 = nn.Linear(hidden_features, out_features)\n        self.drop = nn.Dropout(drop)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        x = self.act(x)\n        x = self.drop(x)\n        x = self.fc2(x)\n        x = self.drop(x)\n        return x\n\n\nclass Attention(nn.Module):\n    def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):\n        super().__init__()\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n        self.scale = qk_scale or head_dim ** -0.5\n\n        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n        self.attn_drop = nn.Dropout(attn_drop)\n        self.proj = nn.Linear(dim, dim)\n        self.proj_drop = nn.Dropout(proj_drop)\n\n    def forward(self, x):\n        B, N, C = x.shape\n        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n        q, k, v = qkv[0], qkv[1], qkv[2]\n\n        attn = (q @ k.transpose(-2, -1)) * self.scale\n        attn = attn.softmax(dim=-1)\n        attn = self.attn_drop(attn)\n\n        x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n        x = self.proj(x)\n        x = self.proj_drop(x)\n        return x, attn\n\n\nclass Block(nn.Module):\n    def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,\n                 drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):\n        super().__init__()\n        self.norm1 = norm_layer(dim)\n        self.attn = Attention(\n            dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\n        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n        self.norm2 = norm_layer(dim)\n        mlp_hidden_dim = int(dim * mlp_ratio)\n        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n    def forward(self, x, return_attention=False):\n        y, attn = self.attn(self.norm1(x))\n        if return_attention:\n            return attn\n        x = x + self.drop_path(y)\n        x = x + self.drop_path(self.mlp(self.norm2(x)))\n        return x\n\n\nclass PatchEmbed(nn.Module):\n    \"\"\" Image to Patch Embedding\n    \"\"\"\n    def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):\n        super().__init__()\n        num_patches = (img_size // patch_size) * (img_size // patch_size)\n        self.img_size = img_size\n        self.patch_size = patch_size\n        self.num_patches = num_patches\n\n        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)\n\n    def forward(self, x):\n        B, C, H, W = x.shape\n        x = self.proj(x).flatten(2).transpose(1, 2)\n        return x\n\n\nclass VisionTransformer(nn.Module):\n    \"\"\" Vision Transformer \"\"\"\n    def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,\n                 num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,\n                 drop_path_rate=0., norm_layer=nn.LayerNorm, **kwargs):\n        super().__init__()\n        self.num_features = self.embed_dim = embed_dim\n\n        self.patch_embed = PatchEmbed(\n            img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)\n        num_patches = self.patch_embed.num_patches\n\n        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))\n        self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))\n        self.pos_drop = nn.Dropout(p=drop_rate)\n\n        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]  # stochastic depth decay rule\n        self.blocks = nn.ModuleList([\n            Block(\n                dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,\n                drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)\n            for i in range(depth)])\n        self.norm = norm_layer(embed_dim)\n\n        # Classifier head\n        self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n\n        trunc_normal_(self.pos_embed, std=.02)\n        trunc_normal_(self.cls_token, std=.02)\n        self.apply(self._init_weights)\n\n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            trunc_normal_(m.weight, std=.02)\n            if isinstance(m, nn.Linear) and m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n        elif isinstance(m, nn.LayerNorm):\n            nn.init.constant_(m.bias, 0)\n            nn.init.constant_(m.weight, 1.0)\n\n    def interpolate_pos_encoding(self, x, w, h):\n        npatch = x.shape[1] - 1\n        N = self.pos_embed.shape[1] - 1\n        if npatch == N and w == h:\n            return self.pos_embed\n        class_pos_embed = self.pos_embed[:, 0]\n        patch_pos_embed = self.pos_embed[:, 1:]\n        dim = x.shape[-1]\n        w0 = w // self.patch_embed.patch_size\n        h0 = h // self.patch_embed.patch_size\n        # we add a small number to avoid floating point error in the interpolation\n        # see discussion at https://github.com/facebookresearch/dino/issues/8\n        w0, h0 = w0 + 0.1, h0 + 0.1\n        patch_pos_embed = nn.functional.interpolate(\n            patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),\n            scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),\n            mode='bicubic',\n        )\n        assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]\n        patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)\n        return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)\n\n    def prepare_tokens(self, x):\n        B, nc, w, h = x.shape\n        x = self.patch_embed(x)  # patch linear embedding\n\n        # add the [CLS] token to the embed patch tokens\n        cls_tokens = self.cls_token.expand(B, -1, -1)\n        x = torch.cat((cls_tokens, x), dim=1)\n\n        # add positional encoding to each token\n        x = x + self.interpolate_pos_encoding(x, w, h)\n\n        return self.pos_drop(x)\n\n    def forward(self, x):\n        x = self.prepare_tokens(x)\n        for blk in self.blocks:\n            x = blk(x)\n        x = self.norm(x)\n        return x[:, 0]\n\n    def get_last_selfattention(self, x):\n        x = self.prepare_tokens(x)\n        for i, blk in enumerate(self.blocks):\n            if i < len(self.blocks) - 1:\n                x = blk(x)\n            else:\n                # return attention of the last block\n                return blk(x, return_attention=True)\n\n    def get_intermediate_layers(self, x, n=1):\n        x = self.prepare_tokens(x)\n        # we return the output tokens from the `n` last blocks\n        output = []\n        for i, blk in enumerate(self.blocks):\n            x = blk(x)\n            if len(self.blocks) - i <= n:\n                output.append(self.norm(x))\n        return output\n\n\ndef vit_tiny(patch_size=16, **kwargs):\n    model = VisionTransformer(\n        patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,\n        qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n    return model\n\n\ndef vit_small(patch_size=16, **kwargs):\n    model = VisionTransformer(\n        patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,\n        qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n    return model\n\n\ndef vit_base(patch_size=16, **kwargs):\n    model = VisionTransformer(\n        patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,\n        qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\n    return model\n\n\nclass DINOHead(nn.Module):\n    def __init__(self, in_dim, out_dim, use_bn=False, norm_last_layer=True, nlayers=3, hidden_dim=2048, bottleneck_dim=256):\n        super().__init__()\n        nlayers = max(nlayers, 1)\n        if nlayers == 1:\n            self.mlp = nn.Linear(in_dim, bottleneck_dim)\n        else:\n            layers = [nn.Linear(in_dim, hidden_dim)]\n            if use_bn:\n                layers.append(nn.BatchNorm1d(hidden_dim))\n            layers.append(nn.GELU())\n            for _ in range(nlayers - 2):\n                layers.append(nn.Linear(hidden_dim, hidden_dim))\n                if use_bn:\n                    layers.append(nn.BatchNorm1d(hidden_dim))\n                layers.append(nn.GELU())\n            layers.append(nn.Linear(hidden_dim, bottleneck_dim))\n            self.mlp = nn.Sequential(*layers)\n        self.apply(self._init_weights)\n        self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))\n        self.last_layer.weight_g.data.fill_(1)\n        if norm_last_layer:\n            self.last_layer.weight_g.requires_grad = False\n\n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            trunc_normal_(m.weight, std=.02)\n            if isinstance(m, nn.Linear) and m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n\n    def forward(self, x):\n        x = self.mlp(x)\n        x = nn.functional.normalize(x, dim=-1, p=2)\n        x = self.last_layer(x)\n        return x\n"
  },
  {
    "path": "visualize_attention.py",
    "content": "# Copyright (c) Facebook, Inc. and its affiliates.\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.\nimport os\nimport sys\nimport argparse\nimport cv2\nimport random\nimport colorsys\nimport requests\nfrom io import BytesIO\n\nimport skimage.io\nfrom skimage.measure import find_contours\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom torchvision import transforms as pth_transforms\nimport numpy as np\nfrom PIL import Image\n\nimport utils\nimport vision_transformer as vits\n\n\ndef apply_mask(image, mask, color, alpha=0.5):\n    for c in range(3):\n        image[:, :, c] = image[:, :, c] * (1 - alpha * mask) + alpha * mask * color[c] * 255\n    return image\n\n\ndef random_colors(N, bright=True):\n    \"\"\"\n    Generate random colors.\n    \"\"\"\n    brightness = 1.0 if bright else 0.7\n    hsv = [(i / N, 1, brightness) for i in range(N)]\n    colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\n    random.shuffle(colors)\n    return colors\n\n\ndef display_instances(image, mask, fname=\"test\", figsize=(5, 5), blur=False, contour=True, alpha=0.5):\n    fig = plt.figure(figsize=figsize, frameon=False)\n    ax = plt.Axes(fig, [0., 0., 1., 1.])\n    ax.set_axis_off()\n    fig.add_axes(ax)\n    ax = plt.gca()\n\n    N = 1\n    mask = mask[None, :, :]\n    # Generate random colors\n    colors = random_colors(N)\n\n    # Show area outside image boundaries.\n    height, width = image.shape[:2]\n    margin = 0\n    ax.set_ylim(height + margin, -margin)\n    ax.set_xlim(-margin, width + margin)\n    ax.axis('off')\n    masked_image = image.astype(np.uint32).copy()\n    for i in range(N):\n        color = colors[i]\n        _mask = mask[i]\n        if blur:\n            _mask = cv2.blur(_mask,(10,10))\n        # Mask\n        masked_image = apply_mask(masked_image, _mask, color, alpha)\n        # Mask Polygon\n        # Pad to ensure proper polygons for masks that touch image edges.\n        if contour:\n            padded_mask = np.zeros((_mask.shape[0] + 2, _mask.shape[1] + 2))\n            padded_mask[1:-1, 1:-1] = _mask\n            contours = find_contours(padded_mask, 0.5)\n            for verts in contours:\n                # Subtract the padding and flip (y, x) to (x, y)\n                verts = np.fliplr(verts) - 1\n                p = Polygon(verts, facecolor=\"none\", edgecolor=color)\n                ax.add_patch(p)\n    ax.imshow(masked_image.astype(np.uint8), aspect='auto')\n    fig.savefig(fname)\n    print(f\"{fname} saved.\")\n    return\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser('Visualize Self-Attention maps')\n    parser.add_argument('--arch', default='vit_small', type=str,\n        choices=['vit_tiny', 'vit_small', 'vit_base'], help='Architecture (support only ViT atm).')\n    parser.add_argument('--patch_size', default=8, type=int, help='Patch resolution of the model.')\n    parser.add_argument('--pretrained_weights', default='', type=str,\n        help=\"Path to pretrained weights to load.\")\n    parser.add_argument(\"--checkpoint_key\", default=\"teacher\", type=str,\n        help='Key to use in the checkpoint (example: \"teacher\")')\n    parser.add_argument(\"--image_path\", default=None, type=str, help=\"Path of the image to load.\")\n    parser.add_argument(\"--image_size\", default=(480, 480), type=int, nargs=\"+\", help=\"Resize image.\")\n    parser.add_argument('--output_dir', default='.', help='Path where to save visualizations.')\n    parser.add_argument(\"--threshold\", type=float, default=None, help=\"\"\"We visualize masks\n        obtained by thresholding the self-attention maps to keep xx% of the mass.\"\"\")\n    args = parser.parse_args()\n\n    device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n    # build model\n    model = vits.__dict__[args.arch](patch_size=args.patch_size, num_classes=0)\n    for p in model.parameters():\n        p.requires_grad = False\n    model.eval()\n    model.to(device)\n    if os.path.isfile(args.pretrained_weights):\n        state_dict = torch.load(args.pretrained_weights, map_location=\"cpu\")\n        if args.checkpoint_key is not None and args.checkpoint_key in state_dict:\n            print(f\"Take key {args.checkpoint_key} in provided checkpoint dict\")\n            state_dict = state_dict[args.checkpoint_key]\n        # remove `module.` prefix\n        state_dict = {k.replace(\"module.\", \"\"): v for k, v in state_dict.items()}\n        # remove `backbone.` prefix induced by multicrop wrapper\n        state_dict = {k.replace(\"backbone.\", \"\"): v for k, v in state_dict.items()}\n        msg = model.load_state_dict(state_dict, strict=False)\n        print('Pretrained weights found at {} and loaded with msg: {}'.format(args.pretrained_weights, msg))\n    else:\n        print(\"Please use the `--pretrained_weights` argument to indicate the path of the checkpoint to evaluate.\")\n        url = None\n        if args.arch == \"vit_small\" and args.patch_size == 16:\n            url = \"dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth\"\n        elif args.arch == \"vit_small\" and args.patch_size == 8:\n            url = \"dino_deitsmall8_300ep_pretrain/dino_deitsmall8_300ep_pretrain.pth\"  # model used for visualizations in our paper\n        elif args.arch == \"vit_base\" and args.patch_size == 16:\n            url = \"dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth\"\n        elif args.arch == \"vit_base\" and args.patch_size == 8:\n            url = \"dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth\"\n        if url is not None:\n            print(\"Since no pretrained weights have been provided, we load the reference pretrained DINO weights.\")\n            state_dict = torch.hub.load_state_dict_from_url(url=\"https://dl.fbaipublicfiles.com/dino/\" + url)\n            model.load_state_dict(state_dict, strict=True)\n        else:\n            print(\"There is no reference weights available for this model => We use random weights.\")\n\n    # open image\n    if args.image_path is None:\n        # user has not specified any image - we use our own image\n        print(\"Please use the `--image_path` argument to indicate the path of the image you wish to visualize.\")\n        print(\"Since no image path have been provided, we take the first image in our paper.\")\n        response = requests.get(\"https://dl.fbaipublicfiles.com/dino/img.png\")\n        img = Image.open(BytesIO(response.content))\n        img = img.convert('RGB')\n    elif os.path.isfile(args.image_path):\n        with open(args.image_path, 'rb') as f:\n            img = Image.open(f)\n            img = img.convert('RGB')\n    else:\n        print(f\"Provided image path {args.image_path} is non valid.\")\n        sys.exit(1)\n    transform = pth_transforms.Compose([\n        pth_transforms.Resize(args.image_size),\n        pth_transforms.ToTensor(),\n        pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n    ])\n    img = transform(img)\n\n    # make the image divisible by the patch size\n    w, h = img.shape[1] - img.shape[1] % args.patch_size, img.shape[2] - img.shape[2] % args.patch_size\n    img = img[:, :w, :h].unsqueeze(0)\n\n    w_featmap = img.shape[-2] // args.patch_size\n    h_featmap = img.shape[-1] // args.patch_size\n\n    attentions = model.get_last_selfattention(img.to(device))\n\n    nh = attentions.shape[1] # number of head\n\n    # we keep only the output patch attention\n    attentions = attentions[0, :, 0, 1:].reshape(nh, -1)\n\n    if args.threshold is not None:\n        # we keep only a certain percentage of the mass\n        val, idx = torch.sort(attentions)\n        val /= torch.sum(val, dim=1, keepdim=True)\n        cumval = torch.cumsum(val, dim=1)\n        th_attn = cumval > (1 - args.threshold)\n        idx2 = torch.argsort(idx)\n        for head in range(nh):\n            th_attn[head] = th_attn[head][idx2[head]]\n        th_attn = th_attn.reshape(nh, w_featmap, h_featmap).float()\n        # interpolate\n        th_attn = nn.functional.interpolate(th_attn.unsqueeze(0), scale_factor=args.patch_size, mode=\"nearest\")[0].cpu().numpy()\n\n    attentions = attentions.reshape(nh, w_featmap, h_featmap)\n    attentions = nn.functional.interpolate(attentions.unsqueeze(0), scale_factor=args.patch_size, mode=\"nearest\")[0].cpu().numpy()\n\n    # save attentions heatmaps\n    os.makedirs(args.output_dir, exist_ok=True)\n    torchvision.utils.save_image(torchvision.utils.make_grid(img, normalize=True, scale_each=True), os.path.join(args.output_dir, \"img.png\"))\n    for j in range(nh):\n        fname = os.path.join(args.output_dir, \"attn-head\" + str(j) + \".png\")\n        plt.imsave(fname=fname, arr=attentions[j], format='png')\n        print(f\"{fname} saved.\")\n\n    if args.threshold is not None:\n        image = skimage.io.imread(os.path.join(args.output_dir, \"img.png\"))\n        for j in range(nh):\n            display_instances(image, th_attn[j], fname=os.path.join(args.output_dir, \"mask_th\" + str(args.threshold) + \"_head\" + str(j) +\".png\"), blur=False)\n"
  }
]