Repository: timmeinhardt/trackformer Branch: main Commit: e468bf156b02 Files: 91 Total size: 458.1 KB Directory structure: gitextract_f7imb6c9/ ├── .circleci/ │ └── config.yml ├── .github/ │ ├── CODE_OF_CONDUCT.md │ ├── CONTRIBUTING.md │ └── ISSUE_TEMPLATE/ │ ├── bugs.md │ ├── questions-help-support.md │ └── unexpected-problems-bugs.md ├── .gitignore ├── LICENSE ├── README.md ├── cfgs/ │ ├── submit.yaml │ ├── track.yaml │ ├── track_reid.yaml │ ├── train.yaml │ ├── train_coco_person_masks.yaml │ ├── train_crowdhuman.yaml │ ├── train_deformable.yaml │ ├── train_full_res.yaml │ ├── train_mot17.yaml │ ├── train_mot17_crowdhuman.yaml │ ├── train_mot20_crowdhuman.yaml │ ├── train_mot_coco_person.yaml │ ├── train_mots20.yaml │ ├── train_multi_frame.yaml │ └── train_tracking.yaml ├── data/ │ └── .gitignore ├── docs/ │ ├── INSTALL.md │ └── TRAIN.md ├── logs/ │ ├── .gitignore │ └── visdom/ │ └── .gitignore ├── models/ │ └── .gitignore ├── requirements.txt ├── setup.py └── src/ ├── combine_frames.py ├── compute_best_mean_epoch_from_splits.py ├── generate_coco_from_crowdhuman.py ├── generate_coco_from_mot.py ├── parse_mot_results_to_tex.py ├── run_with_submitit.py ├── track.py ├── track_param_search.py ├── trackformer/ │ ├── __init__.py │ ├── datasets/ │ │ ├── __init__.py │ │ ├── coco.py │ │ ├── coco_eval.py │ │ ├── coco_panoptic.py │ │ ├── crowdhuman.py │ │ ├── mot.py │ │ ├── panoptic_eval.py │ │ ├── tracking/ │ │ │ ├── __init__.py │ │ │ ├── demo_sequence.py │ │ │ ├── factory.py │ │ │ ├── mot17_sequence.py │ │ │ ├── mot20_sequence.py │ │ │ ├── mot_wrapper.py │ │ │ └── mots20_sequence.py │ │ └── transforms.py │ ├── engine.py │ ├── models/ │ │ ├── __init__.py │ │ ├── backbone.py │ │ ├── deformable_detr.py │ │ ├── deformable_transformer.py │ │ ├── detr.py │ │ ├── detr_segmentation.py │ │ ├── detr_tracking.py │ │ ├── matcher.py │ │ ├── ops/ │ │ │ ├── .gitignore │ │ │ ├── functions/ │ │ │ │ ├── __init__.py │ │ │ │ └── ms_deform_attn_func.py │ │ │ ├── make.sh │ │ │ ├── modules/ │ │ │ │ ├── __init__.py │ │ │ │ └── ms_deform_attn.py │ │ │ ├── setup.py │ │ │ ├── src/ │ │ │ │ ├── cpu/ │ │ │ │ │ ├── ms_deform_attn_cpu.cpp │ │ │ │ │ └── ms_deform_attn_cpu.h │ │ │ │ ├── cuda/ │ │ │ │ │ ├── ms_deform_attn_cuda.cu │ │ │ │ │ ├── ms_deform_attn_cuda.h │ │ │ │ │ └── ms_deform_im2col_cuda.cuh │ │ │ │ ├── ms_deform_attn.h │ │ │ │ └── vision.cpp │ │ │ ├── test.py │ │ │ └── test_double_precision.py │ │ ├── position_encoding.py │ │ ├── tracker.py │ │ └── transformer.py │ ├── util/ │ │ ├── __init__.py │ │ ├── box_ops.py │ │ ├── misc.py │ │ ├── plot_utils.py │ │ └── track_utils.py │ └── vis.py └── train.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .circleci/config.yml ================================================ version: 2.1 jobs: python_lint: docker: - image: circleci/python:3.7 steps: - checkout - run: command: | pip install --user --progress-bar off flake8 typing flake8 . test: docker: - image: circleci/python:3.7 steps: - checkout - run: command: | pip install --user --progress-bar off scipy pytest pip install --user --progress-bar off --pre torch torchvision -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html pytest . workflows: build: jobs: - python_lint - test ================================================ FILE: .github/CODE_OF_CONDUCT.md ================================================ # Code of Conduct Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the [full text](https://code.fb.com/codeofconduct/) so that you can understand what actions will and will not be tolerated. ================================================ FILE: .github/CONTRIBUTING.md ================================================ # Contributing to DETR We want to make contributing to this project as easy and transparent as possible. ## Our Development Process Minor changes and improvements will be released on an ongoing basis. Larger changes (e.g., changesets implementing a new paper) will be released on a more periodic basis. ## Pull Requests We actively welcome your pull requests. 1. Fork the repo and create your branch from `master`. 2. If you've added code that should be tested, add tests. 3. If you've changed APIs, update the documentation. 4. Ensure the test suite passes. 5. Make sure your code lints. 6. If you haven't already, complete the Contributor License Agreement ("CLA"). ## Contributor License Agreement ("CLA") In order to accept your pull request, we need you to submit a CLA. You only need to do this once to work on any of Facebook's open source projects. Complete your CLA here: ## Issues We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. In those cases, please go through the process outlined on that page and do not file a public issue. ## Coding Style * 4 spaces for indentation rather than tabs * 80 character line length * PEP8 formatting following [Black](https://black.readthedocs.io/en/stable/) ## License By contributing to DETR, you agree that your contributions will be licensed under the LICENSE file in the root directory of this source tree. ================================================ FILE: .github/ISSUE_TEMPLATE/bugs.md ================================================ --- name: "🐛 Bugs" about: Report bugs in DETR title: Please read & provide the following --- ## Instructions To Reproduce the 🐛 Bug: 1. what changes you made (`git diff`) or what code you wrote ``` ``` 2. what exact command you run: 3. what you observed (including __full logs__): ``` ``` 4. please simplify the steps as much as possible so they do not require additional resources to run, such as a private dataset. ## Expected behavior: If there are no obvious error in "what you observed" provided above, please tell us the expected behavior. ## Environment: Provide your environment information using the following command: ``` python -m torch.utils.collect_env ``` ================================================ FILE: .github/ISSUE_TEMPLATE/questions-help-support.md ================================================ --- name: "How to do something❓" about: How to do something using DETR? --- ## ❓ How to do something using DETR Describe what you want to do, including: 1. what inputs you will provide, if any: 2. what outputs you are expecting: NOTE: 1. Only general answers are provided. If you want to ask about "why X did not work", please use the [Unexpected behaviors](https://github.com/facebookresearch/detr/issues/new/choose) issue template. 2. About how to implement new models / new dataloader / new training logic, etc., check documentation first. 3. We do not answer general machine learning / computer vision questions that are not specific to DETR, such as how a model works, how to improve your training/make it converge, or what algorithm/methods can be used to achieve X. ================================================ FILE: .github/ISSUE_TEMPLATE/unexpected-problems-bugs.md ================================================ --- name: "Unexpected behaviors" about: Run into unexpected behaviors when using DETR title: Please read & provide the following --- If you do not know the root cause of the problem, and wish someone to help you, please post according to this template: ## Instructions To Reproduce the Issue: 1. what changes you made (`git diff`) or what code you wrote ``` ``` 2. what exact command you run: 3. what you observed (including __full logs__): ``` ``` 4. please simplify the steps as much as possible so they do not require additional resources to run, such as a private dataset. ## Expected behavior: If there are no obvious error in "what you observed" provided above, please tell us the expected behavior. If you expect the model to converge / work better, note that we do not give suggestions on how to train a new model. Only in one of the two conditions we will help with it: (1) You're unable to reproduce the results in DETR model zoo. (2) It indicates a DETR bug. ## Environment: Provide your environment information using the following command: ``` python -m torch.utils.collect_env ``` ================================================ FILE: .gitignore ================================================ .nfs* *.ipynb *.pyc .dumbo.json .DS_Store .*.swp *.pth **/__pycache__/** .ipynb_checkpoints/ datasets/data/ experiment-* *.tmp *.pkl **/.mypy_cache/* .mypy_cache/* not_tracked_dir/ .vscode .python-version *.sbatch *.egg-info src/trackformer/models/ops/build* src/trackformer/models/ops/dist* src/trackformer/models/ops/lib* src/trackformer/models/ops/temp* ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2020 - present, Facebook, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # TrackFormer: Multi-Object Tracking with Transformers This repository provides the official implementation of the [TrackFormer: Multi-Object Tracking with Transformers](https://arxiv.org/abs/2101.02702) paper by [Tim Meinhardt](https://dvl.in.tum.de/team/meinhardt/), [Alexander Kirillov](https://alexander-kirillov.github.io/), [Laura Leal-Taixe](https://dvl.in.tum.de/team/lealtaixe/) and [Christoph Feichtenhofer](https://feichtenhofer.github.io/). The codebase builds upon [DETR](https://github.com/facebookresearch/detr), [Deformable DETR](https://github.com/fundamentalvision/Deformable-DETR) and [Tracktor](https://github.com/phil-bergmann/tracking_wo_bnw).
MOT17-03-SDP MOTS20-07
## Abstract The challenging task of multi-object tracking (MOT) requires simultaneous reasoning about track initialization, identity, and spatiotemporal trajectories. We formulate this task as a frame-to-frame set prediction problem and introduce TrackFormer, an end-to-end MOT approach based on an encoder-decoder Transformer architecture. Our model achieves data association between frames via attention by evolving a set of track predictions through a video sequence. The Transformer decoder initializes new tracks from static object queries and autoregressively follows existing tracks in space and time with the new concept of identity preserving track queries. Both decoder query types benefit from self- and encoder-decoder attention on global frame-level features, thereby omitting any additional graph optimization and matching or modeling of motion and appearance. TrackFormer represents a new tracking-by-attention paradigm and yields state-of-the-art performance on the task of multi-object tracking (MOT17) and segmentation (MOTS20).
TrackFormer casts multi-object tracking as a set prediction problem performing joint detection and tracking-by-attention. The architecture consists of a CNN for image feature extraction, a Transformer encoder for image feature encoding and a Transformer decoder which applies self- and encoder-decoder attention to produce output embeddings with bounding box and class information.
## Installation We refer to our [docs/INSTALL.md](docs/INSTALL.md) for detailed installation instructions. ## Train TrackFormer We refer to our [docs/TRAIN.md](docs/TRAIN.md) for detailed training instructions. ## Evaluate TrackFormer In order to evaluate TrackFormer on a multi-object tracking dataset, we provide the `src/track.py` script which supports several datasets and splits interchangle via the `dataset_name` argument (See `src/datasets/tracking/factory.py` for an overview of all datasets.) The default tracking configuration is specified in `cfgs/track.yaml`. To facilitate the reproducibility of our results, we provide evaluation metrics for both the train and test set. ### MOT17 #### Private detections ``` python src/track.py with reid ```
| MOT17 | MOTA | IDF1 | MT | ML | FP | FN | ID SW. | | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | | **Train** | 74.2 | 71.7 | 849 | 177 | 7431 | 78057 | 1449 | | **Test** | 74.1 | 68.0 | 1113 | 246 | 34602 | 108777 | 2829 |
#### Public detections (DPM, FRCNN, SDP) ``` python src/track.py with \ reid \ tracker_cfg.public_detections=min_iou_0_5 \ obj_detect_checkpoint_file=models/mot17_deformable_multi_frame/checkpoint_epoch_50.pth ```
| MOT17 | MOTA | IDF1 | MT | ML | FP | FN | ID SW. | | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | | **Train** | 64.6 | 63.7 | 621 | 675 | 4827 | 111958 | 2556 | | **Test** | 62.3 | 57.6 | 688 | 638 | 16591 | 192123 | 4018 |
### MOT20 #### Private detections ``` python src/track.py with \ reid \ dataset_name=MOT20-ALL \ obj_detect_checkpoint_file=models/mot20_crowdhuman_deformable_multi_frame/checkpoint_epoch_50.pth ```
| MOT20 | MOTA | IDF1 | MT | ML | FP | FN | ID SW. | | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | | **Train** | 81.0 | 73.3 | 1540 | 124 | 20807 | 192665 | 1961 | | **Test** | 68.6 | 65.7 | 666 | 181 | 20348 | 140373 | 1532 |
### MOTS20 ``` python src/track.py with \ dataset_name=MOTS20-ALL \ obj_detect_checkpoint_file=models/mots20_train_masks/checkpoint.pth ``` Our tracking script only applies MOT17 metrics evaluation but outputs MOTS20 mask prediction files. To evaluate these download the official [MOTChallengeEvalKit](https://github.com/dendorferpatrick/MOTChallengeEvalKit).
| MOTS20 | sMOTSA | IDF1 | FP | FN | IDs | | :---: | :---: | :---: | :---: | :---: | :---: | | **Train** | -- | -- | -- | -- | -- | | **Test** | 54.9 | 63.6 | 2233 | 7195 | 278 |
### Demo To facilitate the application of TrackFormer, we provide a demo interface which allows for a quick processing of a given video sequence. ``` ffmpeg -i data/snakeboard/snakeboard.mp4 -vf fps=30 data/snakeboard/%06d.png python src/track.py with \ dataset_name=DEMO \ data_root_dir=data/snakeboard \ output_dir=data/snakeboard \ write_images=pretty ```
Snakeboard demo
## Publication If you use this software in your research, please cite our publication: ``` @InProceedings{meinhardt2021trackformer, title={TrackFormer: Multi-Object Tracking with Transformers}, author={Tim Meinhardt and Alexander Kirillov and Laura Leal-Taixe and Christoph Feichtenhofer}, year={2022}, month = {June}, booktitle = {The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, } ``` ================================================ FILE: cfgs/submit.yaml ================================================ # Number of gpus to request on each node num_gpus: 1 vram: 12GB # memory allocated per GPU in GB mem_per_gpu: 20 # Number of nodes to request nodes: 1 # Duration of the job timeout: 4320 # Job dir. Leave empty for automatic. job_dir: '' # Use to run jobs locally. ('debug', 'local', 'slurm') cluster: debug # Partition. Leave empty for automatic. slurm_partition: '' # Constraint. Leave empty for automatic. slurm_constraint: '' slurm_comment: '' slurm_gres: '' slurm_exclude: '' cpus_per_task: 2 ================================================ FILE: cfgs/track.yaml ================================================ output_dir: null verbose: false seed: 666 obj_detect_checkpoint_file: models/mot17_crowdhuman_deformable_multi_frame/checkpoint_epoch_40.pth interpolate: False # if available load tracking results and only evaluate load_results_dir: null # dataset (look into src/datasets/tracking/factory.py) dataset_name: MOT17-ALL-ALL data_root_dir: data # [False, 'debug', 'pretty'] # compile video with: `ffmpeg -f image2 -framerate 15 -i %06d.jpg -vcodec libx264 -y movie.mp4 -vf scale=320:-1` write_images: False # Maps are only visualized if write_images is True generate_attention_maps: False # track, evaluate and write images only for a range of frames (in float fraction) frame_range: start: 0.0 end: 1.0 tracker_cfg: # [False, 'center_distance', 'min_iou_0_5'] public_detections: False # score threshold for detections detection_obj_score_thresh: 0.4 # score threshold for keeping the track alive track_obj_score_thresh: 0.4 # NMS threshold for detection detection_nms_thresh: 0.9 # NMS theshold while tracking track_nms_thresh: 0.9 # number of consective steps a score has to be below track_obj_score_thresh for a track to be terminated steps_termination: 1 # distance of previous frame for multi-frame attention prev_frame_dist: 1 # How many timesteps inactive tracks are kept and cosidered for reid inactive_patience: -1 # How similar do image and old track need to be to be considered the same person reid_sim_threshold: 0.0 reid_sim_only: false reid_score_thresh: 0.4 reid_greedy_matching: false ================================================ FILE: cfgs/track_reid.yaml ================================================ tracker_cfg: inactive_patience: 5 ================================================ FILE: cfgs/train.yaml ================================================ lr: 0.0002 lr_backbone_names: ['backbone.0'] lr_backbone: 0.00002 lr_linear_proj_names: ['reference_points', 'sampling_offsets'] lr_linear_proj_mult: 0.1 lr_track: 0.0001 overwrite_lrs: false overwrite_lr_scheduler: false batch_size: 2 weight_decay: 0.0001 epochs: 50 lr_drop: 40 # gradient clipping max norm clip_max_norm: 0.1 # Deformable DETR deformable: false with_box_refine: false two_stage: false # Model parameters freeze_detr: false load_mask_head_from_model: null # Backbone # Name of the convolutional backbone to use. ('resnet50', 'resnet101') backbone: resnet50 # If true, we replace stride with dilation in the last convolutional block (DC5) dilation: false # Type of positional embedding to use on top of the image features. ('sine', 'learned') position_embedding: sine # Number of feature levels the encoder processes from the backbone num_feature_levels: 1 # Transformer # Number of encoding layers in the transformer enc_layers: 6 # Number of decoding layers in the transformer dec_layers: 6 # Intermediate size of the feedforward layers in the transformer blocks dim_feedforward: 2048 # Size of the embeddings (dimension of the transformer) hidden_dim: 256 # Dropout applied in the transformer dropout: 0.1 # Number of attention heads inside the transformer's attentions nheads: 8 # Number of object queries num_queries: 100 pre_norm: false dec_n_points: 4 enc_n_points: 4 # Tracking tracking: false # In addition to detection also run tracking evaluation with default configuration from `cfgs/track.yaml` tracking_eval: true # Range of possible random previous frames track_prev_frame_range: 0 track_prev_frame_rnd_augs: 0.01 track_prev_prev_frame: False track_backprop_prev_frame: False track_query_false_positive_prob: 0.1 track_query_false_negative_prob: 0.4 # only for vanilla DETR track_query_false_positive_eos_weight: true track_attention: false multi_frame_attention: false multi_frame_encoding: true multi_frame_attention_separate_encoder: true merge_frame_features: false overflow_boxes: false # Segmentation masks: false # Matcher # Class coefficient in the matching cost set_cost_class: 1.0 # L1 box coefficient in the matching cost set_cost_bbox: 5.0 # giou box coefficient in the matching cost set_cost_giou: 2.0 # Loss # Disables auxiliary decoding losses (loss at each layer) aux_loss: true mask_loss_coef: 1.0 dice_loss_coef: 1.0 cls_loss_coef: 1.0 bbox_loss_coef: 5.0 giou_loss_coef: 2 # Relative classification weight of the no-object class eos_coef: 0.1 focal_loss: false focal_alpha: 0.25 focal_gamma: 2 # Dataset dataset: coco train_split: train val_split: val coco_path: data/coco_2017 coco_panoptic_path: null mot_path_train: data/MOT17 mot_path_val: data/MOT17 crowdhuman_path: data/CrowdHuman # allows for joint training of mot and crowdhuman/coco_person with the `mot_crowdhuman`/`mot_coco_person` dataset crowdhuman_train_split: null coco_person_train_split: null coco_and_crowdhuman_prev_frame_rnd_augs: 0.2 coco_min_num_objects: 0 img_transform: max_size: 1333 val_width: 800 # Miscellaneous # path where to save, empty for no saving output_dir: '' # device to use for training / testing device: cuda seed: 42 # resume from checkpoint resume: '' resume_shift_neuron: False # resume optimization from checkpoint resume_optim: false # resume Visdom visualization resume_vis: false start_epoch: 1 eval_only: false eval_train: false num_workers: 2 val_interval: 5 debug: false # epoch interval for model saving. if 0 only save last and best models save_model_interval: 5 # distributed training parameters # number of distributed processes world_size: 1 # url used to set up distributed training dist_url: env:// # Visdom params # vis_server: http://localhost vis_server: '' vis_port: 8090 vis_and_log_interval: 50 no_vis: false ================================================ FILE: cfgs/train_coco_person_masks.yaml ================================================ dataset: coco_person load_mask_head_from_model: models/detr-r50-panoptic-00ce5173.pth freeze_detr: true masks: true lr: 0.0001 lr_drop: 50 epochs: 50 ================================================ FILE: cfgs/train_crowdhuman.yaml ================================================ dataset: mot_crowdhuman crowdhuman_train_split: train_val train_split: null val_split: mot17_train_cross_val_frame_0_5_to_1_0_coco epochs: 80 lr_drop: 50 ================================================ FILE: cfgs/train_deformable.yaml ================================================ deformable: true num_feature_levels: 4 num_queries: 300 dim_feedforward: 1024 focal_loss: true focal_alpha: 0.25 focal_gamma: 2 cls_loss_coef: 2.0 set_cost_class: 2.0 overflow_boxes: true with_box_refine: true ================================================ FILE: cfgs/train_full_res.yaml ================================================ img_transform: max_size: 1920 val_width: 1080 ================================================ FILE: cfgs/train_mot17.yaml ================================================ dataset: mot train_split: mot17_train_coco val_split: mot17_train_cross_val_frame_0_5_to_1_0_coco mot_path_train: data/MOT17 mot_path_val: data/MOT17 resume: models/r50_deformable_detr_plus_iterative_bbox_refinement-checkpoint_hidden_dim_288.pth epochs: 50 lr_drop: 10 ================================================ FILE: cfgs/train_mot17_crowdhuman.yaml ================================================ dataset: mot_crowdhuman crowdhuman_train_split: train_val train_split: mot17_train_coco val_split: mot17_train_cross_val_frame_0_5_to_1_0_coco mot_path_train: data/MOT17 mot_path_val: data/MOT17 resume: models/crowdhuman_deformable_trackformer/checkpoint_epoch_80.pth epochs: 40 lr_drop: 10 ================================================ FILE: cfgs/train_mot20_crowdhuman.yaml ================================================ dataset: mot_crowdhuman crowdhuman_train_split: train_val train_split: mot20_train_coco val_split: mot20_train_cross_val_frame_0_5_to_1_0_coco mot_path_train: data/MOT20 mot_path_val: data/MOT20 resume: models/crowdhuman_deformable_trackformer/checkpoint_epoch_80.pth epochs: 50 lr_drop: 10 ================================================ FILE: cfgs/train_mot_coco_person.yaml ================================================ dataset: mot_coco_person coco_person_train_split: train train_split: null val_split: mot17_train_cross_val_frame_0_5_to_1_0_coco ================================================ FILE: cfgs/train_mots20.yaml ================================================ dataset: mot mot_path: data/MOTS20 train_split: mots20_train_coco val_split: mots20_train_coco resume: models/mot17_train_pretrain_CH_deformable_with_coco_person_masks/checkpoint.pth masks: true lr: 0.00001 lr_backbone: 0.000001 epochs: 40 lr_drop: 40 ================================================ FILE: cfgs/train_multi_frame.yaml ================================================ num_queries: 500 hidden_dim: 288 multi_frame_attention: true multi_frame_encoding: true multi_frame_attention_separate_encoder: true ================================================ FILE: cfgs/train_tracking.yaml ================================================ tracking: true tracking_eval: true track_prev_frame_range: 5 track_query_false_positive_eos_weight: true ================================================ FILE: data/.gitignore ================================================ * !.gitignore !snakeboard ================================================ FILE: docs/INSTALL.md ================================================ # Installation 1. Clone and enter this repository: ``` git clone git@github.com:timmeinhardt/trackformer.git cd trackformer ``` 2. Install packages for Python 3.7: 1. `pip3 install -r requirements.txt` 2. Install PyTorch 1.5 and torchvision 0.6 from [here](https://pytorch.org/get-started/previous-versions/#v150). 3. Install pycocotools (with fixed ignore flag): `pip3 install -U 'git+https://github.com/timmeinhardt/cocoapi.git#subdirectory=PythonAPI'` 5. Install MultiScaleDeformableAttention package: `python src/trackformer/models/ops/setup.py build --build-base=src/trackformer/models/ops/ install` 3. Download and unpack datasets in the `data` directory: 1. [MOT17](https://motchallenge.net/data/MOT17/): ``` wget https://motchallenge.net/data/MOT17.zip unzip MOT17.zip python src/generate_coco_from_mot.py ``` 2. (Optional) [MOT20](https://motchallenge.net/data/MOT20/): ``` wget https://motchallenge.net/data/MOT20.zip unzip MOT20.zip python src/generate_coco_from_mot.py --mot20 ``` 3. (Optional) [MOTS20](https://motchallenge.net/data/MOTS/): ``` wget https://motchallenge.net/data/MOTS.zip unzip MOTS.zip python src/generate_coco_from_mot.py --mots ``` 4. (Optional) [CrowdHuman](https://www.crowdhuman.org/download.html): 1. Create a `CrowdHuman` and `CrowdHuman/annotations` directory. 2. Download and extract the `train` and `val` datasets including their corresponding `*.odgt` annotation file into the `CrowdHuman` directory. 3. Create a `CrowdHuman/train_val` directory and merge or symlink the `train` and `val` image folders. 4. Run `python src/generate_coco_from_crowdhuman.py` 5. The final folder structure should resemble this: ~~~ |-- data |-- CrowdHuman | |-- train | | |-- *.jpg | |-- val | | |-- *.jpg | |-- train_val | | |-- *.jpg | |-- annotations | | |-- annotation_train.odgt | | |-- annotation_val.odgt | | |-- train_val.json ~~~ 3. Download and unpack pretrained TrackFormer model files in the `models` directory: ``` wget https://vision.in.tum.de/webshare/u/meinhard/trackformer_models_v1.zip unzip trackformer_models_v1.zip ``` 4. (optional) The evaluation of MOTS20 metrics requires two steps: 1. Run Trackformer with `src/track.py` and output prediction files 2. Download the official MOTChallenge [devkit](https://github.com/dendorferpatrick/MOTChallengeEvalKit) and run the MOTS evaluation on the prediction files In order to configure, log and reproduce our computational experiments, we structure our code with the [Sacred](http://sacred.readthedocs.io/en/latest/index.html) framework. For a detailed explanation of the Sacred interface please read its documentation. ================================================ FILE: docs/TRAIN.md ================================================ # Train TrackFormer We provide the code as well as intermediate models of our entire training pipeline for multiple datasets. Monitoring of the training/evaluation progress is possible via command line as well as [Visdom](https://github.com/fossasia/visdom.git). For the latter, a Visdom server must be running at `vis_port` and `vis_server` (see `cfgs/train.yaml`). We set `vis_server=''` by default to deactivate Visdom logging. To deactivate Visdom logging with set parameters, you can run a training with the `no_vis=True` flag.
Snakeboard demo
The settings for each dataset are specified in the respective configuration files, e.g., `cfgs/train_crowdhuman.yaml`. The following train commands produced the pretrained model files mentioned in [docs/INSTALL.md](INSTALL.md). ## CrowdHuman pre-training ``` python src/train.py with \ crowdhuman \ deformable \ multi_frame \ tracking \ output_dir=models/crowdhuman_deformable_multi_frame \ ``` ## MOT17 #### Private detections ``` python src/train.py with \ mot17_crowdhuman \ deformable \ multi_frame \ tracking \ output_dir=models/mot17_crowdhuman_deformable_multi_frame \ ``` #### Public detections ``` python src/train.py with \ mot17 \ deformable \ multi_frame \ tracking \ output_dir=models/mot17_deformable_multi_frame \ ``` ## MOT20 #### Private detections ``` python src/train.py with \ mot20_crowdhuman \ deformable \ multi_frame \ tracking \ output_dir=models/mot20_crowdhuman_deformable_multi_frame \ ``` ## MOTS20 For our MOTS20 test set submission, we finetune a MOT17 private detection model without deformable attention, i.e., vanilla DETR, which was pre-trained on the CrowdHuman dataset. The finetuning itself conists of two training steps: (i) the original DETR panoptic segmentation head on the COCO person segmentation data and (ii) the entire TrackFormer model (including segmentation head) on the MOTS20 training set. At this point, we only provide the final model files in [docs/INSTALL.md](INSTALL.md). ## Custom Dataset TrackFormer can be trained on additional/new object detection or multi-object tracking datasets without changing our codebase. The `crowdhuman` or `mot` datasets merely require a [COCO style](https://www.immersivelimit.com/tutorials/create-coco-annotations-from-scratch) annotation file and the following folder structure: ~~~ |-- data |-- custom_dataset | |-- train | | |-- *.jpg | |-- val | | |-- *.jpg | |-- annotations | | |-- train.json | | |-- val.json ~~~ In the case of a multi-object tracking dataset, the original COCO annotations style must be extended with `seq_length`, `first_frame_image_id` and `track_id` fields. See the `src/generate_coco_from_mot.py` script for details. For example, the following command finetunes our `MOT17` private model for additional 20 epochs on a custom dataset: ``` python src/train.py with \ mot17 \ deformable \ multi_frame \ tracking \ resume=models/mot17_crowdhuman_deformable_trackformer/checkpoint_epoch_40.pth \ output_dir=models/custom_dataset_deformable \ mot_path_train=data/custom_dataset \ mot_path_val=data/custom_dataset \ train_split=train \ val_split=val \ epochs=20 \ ``` ## Run with multipe GPUs All reported results are obtained by training with a batch size of 2 and 7 GPUs, i.e., an effective batch size of 14. If you have less GPUs at your disposal, adjust the learning rates accordingly. To start the CrowdHuman pre-training with 7 GPUs execute: ``` python -m torch.distributed.launch --nproc_per_node=7 --use_env src/train.py with \ crowdhuman \ deformable \ multi_frame \ tracking \ output_dir=models/crowdhuman_deformable_multi_frame \ ``` ## Run SLURM jobs with Submitit Furthermore, we provide a script for starting Slurm jobs with [submitit](https://github.com/facebookincubator/submitit). This includes a convenient command line interface for Slurm options as well as preemption and resuming capabilities. The aforementioned CrowdHuman pre-training can be executed on 7 x 32 GB GPUs with the following command: ``` python src/run_with_submitit.py with \ num_gpus=7 \ vram=32GB \ cluster=slurm \ train.crowdhuman \ train.deformable \ train.trackformer \ train.tracking \ train.output_dir=models/crowdhuman_train_val_deformable \ ``` ================================================ FILE: logs/.gitignore ================================================ * !visdom !.gitignore ================================================ FILE: logs/visdom/.gitignore ================================================ * !.gitignore ================================================ FILE: models/.gitignore ================================================ * !.gitignore ================================================ FILE: requirements.txt ================================================ argon2-cffi==20.1.0 astroid==2.4.2 async-generator==1.10 attrs==19.3.0 backcall==0.2.0 bleach==3.2.3 certifi==2020.4.5.2 cffi==1.14.4 chardet==3.0.4 cloudpickle==1.6.0 colorama==0.4.3 cycler==0.10.0 Cython==0.29.20 decorator==4.4.2 defusedxml==0.6.0 docopt==0.6.2 entrypoints==0.3 filelock==3.0.12 flake8==3.8.3 flake8-import-order==0.18.1 future==0.18.2 gdown==3.12.2 gitdb==4.0.5 GitPython==3.1.3 idna==2.9 imageio==2.8.0 importlib-metadata==1.6.1 ipykernel==5.4.3 ipython==7.19.0 ipython-genutils==0.2.0 ipywidgets==7.6.3 isort==5.6.4 jedi==0.18.0 Jinja2==2.11.2 jsonpatch==1.25 jsonpickle==1.4.1 jsonpointer==2.0 jsonschema==3.2.0 jupyter==1.0.0 jupyter-client==6.1.11 jupyter-console==6.2.0 jupyter-core==4.7.0 jupyterlab-pygments==0.1.2 jupyterlab-widgets==1.0.0 kiwisolver==1.2.0 lap==0.4.0 lapsolver==1.1.0 lazy-object-proxy==1.4.3 MarkupSafe==1.1.1 matplotlib==3.2.1 mccabe==0.6.1 mistune==0.8.4 more-itertools==8.4.0 motmetrics==1.2.0 munch==2.5.0 nbclient==0.5.1 nbconvert==6.0.7 nbformat==5.1.2 nest-asyncio==1.5.1 networkx==2.4 ninja==1.10.0.post2 notebook==6.2.0 numpy==1.18.5 opencv-python==4.2.0.34 packaging==20.4 pandas==1.0.5 pandocfilters==1.4.3 parso==0.8.1 pexpect==4.8.0 pickleshare==0.7.5 Pillow==7.1.2 pluggy==0.13.1 prometheus-client==0.9.0 prompt-toolkit==3.0.14 ptyprocess==0.7.0 py==1.8.2 py-cpuinfo==6.0.0 pyaml==20.4.0 pycodestyle==2.6.0 pycparser==2.20 pyflakes==2.2.0 Pygments==2.7.4 pylint==2.6.0 pyparsing==2.4.7 pyrsistent==0.17.3 PySocks==1.7.1 pytest==5.4.3 pytest-benchmark==3.2.3 python-dateutil==2.8.1 pytz==2020.1 PyWavelets==1.1.1 PyYAML==5.3.1 pyzmq==19.0.1 qtconsole==5.0.2 QtPy==1.9.0 requests==2.23.0 sacred==0.8.1 scikit-image==0.17.2 scipy==1.4.1 seaborn==0.10.1 Send2Trash==1.5.0 six==1.15.0 smmap==3.0.4 submitit==1.1.5 terminado==0.9.2 testpath==0.4.4 tifffile==2020.6.3 toml==0.10.2 torchfile==0.1.0 tornado==6.1 tqdm==4.46.1 traitlets==5.0.5 typed-ast==1.4.1 typing-extensions==3.7.4.3 urllib3==1.25.9 visdom==0.1.8.9 wcwidth==0.2.5 webencodings==0.5.1 websocket-client==0.57.0 widgetsnbextension==3.5.1 wrapt==1.12.1 xmltodict==0.12.0 zipp==3.1.0 ================================================ FILE: setup.py ================================================ from setuptools import setup, find_packages setup(name='trackformer', packages=['trackformer'], package_dir={'':'src'}, version='0.0.1', install_requires=[],) ================================================ FILE: src/combine_frames.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Combine two sets of frames to one. """ import os import os.path as osp from PIL import Image OUTPUT_DIR = 'models/mot17_masks_track_rcnn_and_v3_combined' FRAME_DIR_1 = 'models/mot17_masks_track_rcnn/MOTS20-TEST' FRAME_DIR_2 = 'models/mot17_masks_v3/MOTS20-ALL' if __name__ == '__main__': seqs_1 = os.listdir(FRAME_DIR_1) seqs_2 = os.listdir(FRAME_DIR_2) if not osp.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) for seq in seqs_1: if seq in seqs_2: print(seq) seg_output_dir = osp.join(OUTPUT_DIR, seq) if not osp.exists(seg_output_dir): os.makedirs(seg_output_dir) frames = os.listdir(osp.join(FRAME_DIR_1, seq)) for frame in frames: img_1 = Image.open(osp.join(FRAME_DIR_1, seq, frame)) img_2 = Image.open(osp.join(FRAME_DIR_2, seq, frame)) width = img_1.size[0] height = img_2.size[1] combined_frame = Image.new('RGB', (width, height * 2)) combined_frame.paste(img_1, (0, 0)) combined_frame.paste(img_2, (0, height)) combined_frame.save(osp.join(seg_output_dir, f'{frame}')) ================================================ FILE: src/compute_best_mean_epoch_from_splits.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import json import numpy as np LOG_DIR = 'logs/visdom' METRICS = ['MOTA', 'IDF1', 'BBOX AP IoU=0.50:0.95', 'MASK AP IoU=0.50:0.95'] RUNS = [ 'mot17_train_1_deformable_full_res', 'mot17_train_2_deformable_full_res', 'mot17_train_3_deformable_full_res', 'mot17_train_4_deformable_full_res', 'mot17_train_5_deformable_full_res', 'mot17_train_6_deformable_full_res', 'mot17_train_7_deformable_full_res', ] RUNS = [ 'mot17_train_1_no_pretrain_deformable_tracking', 'mot17_train_2_no_pretrain_deformable_tracking', 'mot17_train_3_no_pretrain_deformable_tracking', 'mot17_train_4_no_pretrain_deformable_tracking', 'mot17_train_5_no_pretrain_deformable_tracking', 'mot17_train_6_no_pretrain_deformable_tracking', 'mot17_train_7_no_pretrain_deformable_tracking', ] RUNS = [ 'mot17_train_1_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_2_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_3_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_4_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_5_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_6_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_7_coco_pretrain_deformable_tracking_lr=0.00001', ] RUNS = [ 'mot17_train_1_crowdhuman_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_2_crowdhuman_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_3_crowdhuman_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_4_crowdhuman_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_5_crowdhuman_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_6_crowdhuman_coco_pretrain_deformable_tracking_lr=0.00001', 'mot17_train_7_crowdhuman_coco_pretrain_deformable_tracking_lr=0.00001', ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_eos_coef=0.2', # 'mot17_train_2_no_pretrain_deformable_tracking_eos_coef=0.2', # 'mot17_train_3_no_pretrain_deformable_tracking_eos_coef=0.2', # 'mot17_train_4_no_pretrain_deformable_tracking_eos_coef=0.2', # 'mot17_train_5_no_pretrain_deformable_tracking_eos_coef=0.2', # 'mot17_train_6_no_pretrain_deformable_tracking_eos_coef=0.2', # 'mot17_train_7_no_pretrain_deformable_tracking_eos_coef=0.2', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_lr_drop=50', # 'mot17_train_2_no_pretrain_deformable_tracking_lr_drop=50', # 'mot17_train_3_no_pretrain_deformable_tracking_lr_drop=50', # 'mot17_train_4_no_pretrain_deformable_tracking_lr_drop=50', # 'mot17_train_5_no_pretrain_deformable_tracking_lr_drop=50', # 'mot17_train_6_no_pretrain_deformable_tracking_lr_drop=50', # 'mot17_train_7_no_pretrain_deformable_tracking_lr_drop=50', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_2_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_3_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_4_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_5_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_6_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_7_no_pretrain_deformable_tracking_save_model_interval=1', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_2_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_3_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_4_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_5_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_6_no_pretrain_deformable_tracking_save_model_interval=1', # 'mot17_train_7_no_pretrain_deformable_tracking_save_model_interval=1', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_full_res', # 'mot17_train_2_no_pretrain_deformable_full_res', # 'mot17_train_3_no_pretrain_deformable_full_res', # 'mot17_train_4_no_pretrain_deformable_full_res', # 'mot17_train_5_no_pretrain_deformable_full_res', # 'mot17_train_6_no_pretrain_deformable_full_res', # 'mot17_train_7_no_pretrain_deformable_full_res', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_track_query_false_positive_eos_weight=False', # 'mot17_train_2_no_pretrain_deformable_tracking_track_query_false_positive_eos_weight=False', # 'mot17_train_3_no_pretrain_deformable_tracking_track_query_false_positive_eos_weight=False', # 'mot17_train_4_no_pretrain_deformable_tracking_track_query_false_positive_eos_weight=False', # 'mot17_train_5_no_pretrain_deformable_tracking_track_query_false_positive_eos_weight=False', # 'mot17_train_6_no_pretrain_deformable_tracking_track_query_false_positive_eos_weight=False', # 'mot17_train_7_no_pretrain_deformable_tracking_track_query_false_positive_eos_weight=False', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0', # 'mot17_train_2_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0', # 'mot17_train_3_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0', # 'mot17_train_4_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0', # 'mot17_train_5_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0', # 'mot17_train_6_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0', # 'mot17_train_7_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0', # 'mot17_train_2_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0', # 'mot17_train_3_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0', # 'mot17_train_4_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0', # 'mot17_train_5_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0', # 'mot17_train_6_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0', # 'mot17_train_7_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0_track_query_false_negative_prob=0_0', # 'mot17_train_2_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0_track_query_false_negative_prob=0_0', # 'mot17_train_3_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0_track_query_false_negative_prob=0_0', # 'mot17_train_4_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0_track_query_false_negative_prob=0_0', # 'mot17_train_5_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0_track_query_false_negative_prob=0_0', # 'mot17_train_6_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0_track_query_false_negative_prob=0_0', # 'mot17_train_7_no_pretrain_deformable_tracking_track_query_false_positive_prob=0_0_track_prev_frame_range=0_track_query_false_negative_prob=0_0', # ] # RUNS = [ # 'mot17_train_1_no_pretrain_deformable', # 'mot17_train_2_no_pretrain_deformable', # 'mot17_train_3_no_pretrain_deformable', # 'mot17_train_4_no_pretrain_deformable', # 'mot17_train_5_no_pretrain_deformable', # 'mot17_train_6_no_pretrain_deformable', # 'mot17_train_7_no_pretrain_deformable', # ] # # MOTS 4-fold split # # RUNS = [ # 'mots20_train_1_coco_tracking', # 'mots20_train_2_coco_tracking', # 'mots20_train_3_coco_tracking', # 'mots20_train_4_coco_tracking', # ] # RUNS = [ # 'mots20_train_1_coco_tracking_full_res_masks=False', # 'mots20_train_2_coco_tracking_full_res_masks=False', # 'mots20_train_3_coco_tracking_full_res_masks=False', # 'mots20_train_4_coco_tracking_full_res_masks=False', # ] # RUNS = [ # 'mots20_train_1_coco_full_res_pretrain_masks=False_lr_0_0001', # 'mots20_train_2_coco_full_res_pretrain_masks=False_lr_0_0001', # 'mots20_train_3_coco_full_res_pretrain_masks=False_lr_0_0001', # 'mots20_train_4_coco_full_res_pretrain_masks=False_lr_0_0001', # ] # RUNS = [ # 'mots20_train_1_coco_tracking_full_res_masks=False_pretrain', # 'mots20_train_2_coco_tracking_full_res_masks=False_pretrain', # 'mots20_train_3_coco_tracking_full_res_masks=False_pretrain', # 'mots20_train_4_coco_tracking_full_res_masks=False_pretrain', # ] # RUNS = [ # 'mot17det_train_1_mots_track_bbox_proposals_pretrain_train_1_mots_vis_save_model_interval_1', # 'mot17det_train_2_mots_track_bbox_proposals_pretrain_train_3_mots_vis_save_model_interval_1', # 'mot17det_train_3_mots_track_bbox_proposals_pretrain_train_4_mots_vis_save_model_interval_1', # 'mot17det_train_4_mots_track_bbox_proposals_pretrain_train_6_mots_vis_save_model_interval_1', # ] if __name__ == '__main__': results = {} for r in RUNS: print(r) log_file = os.path.join(LOG_DIR, f"{r}.json") with open(log_file) as json_file: data = json.load(json_file) window = [ window for window in data['jsons'].values() if window['title'] == 'VAL EVAL EPOCHS'][0] for m in METRICS: if m not in window['legend']: continue elif m not in results: results[m] = [] idxs = window['legend'].index(m) values = window['content']['data'][idxs]['y'] results[m].append(values) print(f'NUM EPOCHS: {len(values)}') min_length = min([len(l) for l in next(iter(results.values()))]) for metric in results.keys(): results[metric] = [l[:min_length] for l in results[metric]] mean_results = { metric: np.array(results[metric]).mean(axis=0) for metric in results.keys()} print("* METRIC INTERVAL = BEST EPOCHS") for metric in results.keys(): best_interval = mean_results[metric].argmax() print(mean_results[metric]) print( f'{metric}: {mean_results[metric].max():.2%} at {best_interval + 1}/{len(mean_results[metric])} ' f'{[(mmetric, f"{mean_results[mmetric][best_interval]:.2%}") for mmetric in results.keys() if not mmetric == metric]}') ================================================ FILE: src/generate_coco_from_crowdhuman.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Generates COCO data and annotation structure from CrowdHuman data. """ import json import os import cv2 from generate_coco_from_mot import check_coco_from_mot DATA_ROOT = 'data/CrowdHuman' VIS_THRESHOLD = 0.0 def generate_coco_from_crowdhuman(split_name='train_val', split='train_val'): """ Generate COCO data from CrowdHuman. """ annotations = {} annotations['type'] = 'instances' annotations['images'] = [] annotations['categories'] = [{"supercategory": "person", "name": "person", "id": 1}] annotations['annotations'] = [] annotation_file = os.path.join(DATA_ROOT, f'annotations/{split_name}.json') # IMAGES imgs_list_dir = os.listdir(os.path.join(DATA_ROOT, split)) for i, img in enumerate(sorted(imgs_list_dir)): im = cv2.imread(os.path.join(DATA_ROOT, split, img)) h, w, _ = im.shape annotations['images'].append({ "file_name": img, "height": h, "width": w, "id": i, }) # GT annotation_id = 0 img_file_name_to_id = { os.path.splitext(img_dict['file_name'])[0]: img_dict['id'] for img_dict in annotations['images']} for split in ['train', 'val']: if split not in split_name: continue odgt_annos_file = os.path.join(DATA_ROOT, f'annotations/annotation_{split}.odgt') with open(odgt_annos_file, 'r+') as anno_file: datalist = anno_file.readlines() ignores = 0 for data in datalist: json_data = json.loads(data) gtboxes = json_data['gtboxes'] for gtbox in gtboxes: if gtbox['tag'] == 'person': bbox = gtbox['fbox'] area = bbox[2] * bbox[3] ignore = False visibility = 1.0 # if 'occ' in gtbox['extra']: # visibility = 1.0 - gtbox['extra']['occ'] # if visibility <= VIS_THRESHOLD: # ignore = True if 'ignore' in gtbox['extra']: ignore = ignore or bool(gtbox['extra']['ignore']) ignores += int(ignore) annotation = { "id": annotation_id, "bbox": bbox, "image_id": img_file_name_to_id[json_data['ID']], "segmentation": [], "ignore": int(ignore), "visibility": visibility, "area": area, "iscrowd": 0, "category_id": annotations['categories'][0]['id'],} annotation_id += 1 annotations['annotations'].append(annotation) # max objs per image num_objs_per_image = {} for anno in annotations['annotations']: image_id = anno["image_id"] if image_id in num_objs_per_image: num_objs_per_image[image_id] += 1 else: num_objs_per_image[image_id] = 1 print(f'max objs per image: {max([n for n in num_objs_per_image.values()])}') print(f'ignore augs: {ignores}/{len(annotations["annotations"])}') print(len(annotations['images'])) # for img_id, num_objs in num_objs_per_image.items(): # if num_objs > 50 or num_objs < 2: # annotations['images'] = [ # img for img in annotations['images'] # if img_id != img['id']] # annotations['annotations'] = [ # anno for anno in annotations['annotations'] # if img_id != anno['image_id']] # print(len(annotations['images'])) with open(annotation_file, 'w') as anno_file: json.dump(annotations, anno_file, indent=4) if __name__ == '__main__': generate_coco_from_crowdhuman(split_name='train_val', split='train_val') # generate_coco_from_crowdhuman(split_name='train', split='train') # coco_dir = os.path.join('data/CrowdHuman', 'train_val') # annotation_file = os.path.join('data/CrowdHuman/annotations', 'train_val.json') # check_coco_from_mot(coco_dir, annotation_file, img_id=9012) ================================================ FILE: src/generate_coco_from_mot.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Generates COCO data and annotation structure from MOTChallenge data. """ import argparse import configparser import csv import json import os import shutil import numpy as np import pycocotools.mask as rletools import skimage.io as io import torch from matplotlib import pyplot as plt from pycocotools.coco import COCO from scipy.optimize import linear_sum_assignment from torchvision.ops.boxes import box_iou from trackformer.datasets.tracking.mots20_sequence import load_mots_gt MOTS_ROOT = 'data/MOTS20' VIS_THRESHOLD = 0.25 MOT_15_SEQS_INFO = { 'ETH-Bahnhof': {'img_width': 640, 'img_height': 480, 'seq_length': 1000}, 'ETH-Sunnyday': {'img_width': 640, 'img_height': 480, 'seq_length': 354}, 'KITTI-13': {'img_width': 1242, 'img_height': 375, 'seq_length': 340}, 'KITTI-17': {'img_width': 1224, 'img_height': 370, 'seq_length': 145}, 'PETS09-S2L1': {'img_width': 768, 'img_height': 576, 'seq_length': 795}, 'TUD-Campus': {'img_width': 640, 'img_height': 480, 'seq_length': 71}, 'TUD-Stadtmitte': {'img_width': 640, 'img_height': 480, 'seq_length': 179},} def generate_coco_from_mot(split_name='train', seqs_names=None, root_split='train', mots=False, mots_vis=False, frame_range=None, data_root='data/MOT17'): """ Generates COCO data from MOT. """ if frame_range is None: frame_range = {'start': 0.0, 'end': 1.0} if mots: data_root = MOTS_ROOT root_split_path = os.path.join(data_root, root_split) root_split_mots_path = os.path.join(MOTS_ROOT, root_split) coco_dir = os.path.join(data_root, split_name) if os.path.isdir(coco_dir): shutil.rmtree(coco_dir) os.mkdir(coco_dir) annotations = {} annotations['type'] = 'instances' annotations['images'] = [] annotations['categories'] = [{"supercategory": "person", "name": "person", "id": 1}] annotations['annotations'] = [] annotations_dir = os.path.join(os.path.join(data_root, 'annotations')) if not os.path.isdir(annotations_dir): os.mkdir(annotations_dir) annotation_file = os.path.join(annotations_dir, f'{split_name}.json') # IMAGE FILES img_id = 0 seqs = sorted(os.listdir(root_split_path)) if seqs_names is not None: seqs = [s for s in seqs if s in seqs_names] annotations['sequences'] = seqs annotations['frame_range'] = frame_range print(split_name, seqs) for seq in seqs: # CONFIG FILE config = configparser.ConfigParser() config_file = os.path.join(root_split_path, seq, 'seqinfo.ini') if os.path.isfile(config_file): config.read(config_file) img_width = int(config['Sequence']['imWidth']) img_height = int(config['Sequence']['imHeight']) seq_length = int(config['Sequence']['seqLength']) else: img_width = MOT_15_SEQS_INFO[seq]['img_width'] img_height = MOT_15_SEQS_INFO[seq]['img_height'] seq_length = MOT_15_SEQS_INFO[seq]['seq_length'] seg_list_dir = os.listdir(os.path.join(root_split_path, seq, 'img1')) start_frame = int(frame_range['start'] * seq_length) end_frame = int(frame_range['end'] * seq_length) seg_list_dir = seg_list_dir[start_frame: end_frame] print(f"{seq}: {len(seg_list_dir)}/{seq_length}") seq_length = len(seg_list_dir) for i, img in enumerate(sorted(seg_list_dir)): if i == 0: first_frame_image_id = img_id annotations['images'].append({"file_name": f"{seq}_{img}", "height": img_height, "width": img_width, "id": img_id, "frame_id": i, "seq_length": seq_length, "first_frame_image_id": first_frame_image_id}) img_id += 1 os.symlink(os.path.join(os.getcwd(), root_split_path, seq, 'img1', img), os.path.join(coco_dir, f"{seq}_{img}")) # GT annotation_id = 0 img_file_name_to_id = { img_dict['file_name']: img_dict['id'] for img_dict in annotations['images']} for seq in seqs: # GT FILE gt_file_path = os.path.join(root_split_path, seq, 'gt', 'gt.txt') if mots: gt_file_path = os.path.join( root_split_mots_path, seq.replace('MOT17', 'MOTS20'), 'gt', 'gt.txt') if not os.path.isfile(gt_file_path): continue seq_annotations = [] if mots: mask_objects_per_frame = load_mots_gt(gt_file_path) for frame_id, mask_objects in mask_objects_per_frame.items(): for mask_object in mask_objects: # class_id = 1 is car # class_id = 2 is person # class_id = 10 IGNORE if mask_object.class_id == 1: continue bbox = rletools.toBbox(mask_object.mask) bbox = [int(c) for c in bbox] area = bbox[2] * bbox[3] image_id = img_file_name_to_id.get(f"{seq}_{frame_id:06d}.jpg", None) if image_id is None: continue segmentation = { 'size': mask_object.mask['size'], 'counts': mask_object.mask['counts'].decode(encoding='UTF-8')} annotation = { "id": annotation_id, "bbox": bbox, "image_id": image_id, "segmentation": segmentation, "ignore": mask_object.class_id == 10, "visibility": 1.0, "area": area, "iscrowd": 0, "seq": seq, "category_id": annotations['categories'][0]['id'], "track_id": mask_object.track_id} seq_annotations.append(annotation) annotation_id += 1 annotations['annotations'].extend(seq_annotations) else: seq_annotations_per_frame = {} with open(gt_file_path, "r") as gt_file: reader = csv.reader(gt_file, delimiter=' ' if mots else ',') for row in reader: if int(row[6]) == 1 and (seq in MOT_15_SEQS_INFO or int(row[7]) == 1): bbox = [float(row[2]), float(row[3]), float(row[4]), float(row[5])] bbox = [int(c) for c in bbox] area = bbox[2] * bbox[3] visibility = float(row[8]) frame_id = int(row[0]) image_id = img_file_name_to_id.get(f"{seq}_{frame_id:06d}.jpg", None) if image_id is None: continue track_id = int(row[1]) annotation = { "id": annotation_id, "bbox": bbox, "image_id": image_id, "segmentation": [], "ignore": 0 if visibility > VIS_THRESHOLD else 1, "visibility": visibility, "area": area, "iscrowd": 0, "seq": seq, "category_id": annotations['categories'][0]['id'], "track_id": track_id} seq_annotations.append(annotation) if frame_id not in seq_annotations_per_frame: seq_annotations_per_frame[frame_id] = [] seq_annotations_per_frame[frame_id].append(annotation) annotation_id += 1 annotations['annotations'].extend(seq_annotations) #change ignore based on MOTS mask if mots_vis: gt_file_mots = os.path.join( root_split_mots_path, seq.replace('MOT17', 'MOTS20'), 'gt', 'gt.txt') if os.path.isfile(gt_file_mots): mask_objects_per_frame = load_mots_gt(gt_file_mots) for frame_id, frame_annotations in seq_annotations_per_frame.items(): mask_objects = mask_objects_per_frame[frame_id] mask_object_bboxes = [rletools.toBbox(obj.mask) for obj in mask_objects] mask_object_bboxes = torch.tensor(mask_object_bboxes).float() frame_boxes = [a['bbox'] for a in frame_annotations] frame_boxes = torch.tensor(frame_boxes).float() # x,y,w,h --> x,y,x,y frame_boxes[:, 2:] += frame_boxes[:, :2] mask_object_bboxes[:, 2:] += mask_object_bboxes[:, :2] mask_iou = box_iou(mask_object_bboxes, frame_boxes) mask_indices, frame_indices = linear_sum_assignment(-mask_iou) for m_i, f_i in zip(mask_indices, frame_indices): if mask_iou[m_i, f_i] < 0.5: continue if not frame_annotations[f_i]['visibility']: frame_annotations[f_i]['ignore'] = 0 # max objs per image num_objs_per_image = {} for anno in annotations['annotations']: image_id = anno["image_id"] if image_id in num_objs_per_image: num_objs_per_image[image_id] += 1 else: num_objs_per_image[image_id] = 1 print(f'max objs per image: {max(list(num_objs_per_image.values()))}') with open(annotation_file, 'w') as anno_file: json.dump(annotations, anno_file, indent=4) def check_coco_from_mot(coco_dir='data/MOT17/mot17_train_coco', annotation_file='data/MOT17/annotations/mot17_train_coco.json', img_id=None): """ Visualize generated COCO data. Only used for debugging. """ # coco_dir = os.path.join(data_root, split) # annotation_file = os.path.join(coco_dir, 'annotations.json') coco = COCO(annotation_file) cat_ids = coco.getCatIds(catNms=['person']) if img_id == None: img_ids = coco.getImgIds(catIds=cat_ids) index = np.random.randint(0, len(img_ids)) img_id = img_ids[index] img = coco.loadImgs(img_id)[0] i = io.imread(os.path.join(coco_dir, img['file_name'])) plt.imshow(i) plt.axis('off') ann_ids = coco.getAnnIds(imgIds=img['id'], catIds=cat_ids, iscrowd=None) anns = coco.loadAnns(ann_ids) coco.showAnns(anns, draw_bbox=True) plt.savefig('annotations.png') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate COCO from MOT.') parser.add_argument('--mots20', action='store_true') parser.add_argument('--mot20', action='store_true') args = parser.parse_args() mot15_seqs_names = list(MOT_15_SEQS_INFO.keys()) if args.mots20: # # MOTS20 # # TRAIN SET generate_coco_from_mot( 'mots20_train_coco', seqs_names=['MOTS20-02', 'MOTS20-05', 'MOTS20-09', 'MOTS20-11'], mots=True) # TRAIN SPLITS for i in range(4): train_seqs = ['MOTS20-02', 'MOTS20-05', 'MOTS20-09', 'MOTS20-11'] val_seqs = train_seqs.pop(i) generate_coco_from_mot( f'mots20_train_{i + 1}_coco', seqs_names=train_seqs, mots=True) generate_coco_from_mot( f'mots20_val_{i + 1}_coco', seqs_names=val_seqs, mots=True) elif args.mot20: data_root = 'data/MOT20' train_seqs = ['MOT20-01', 'MOT20-02', 'MOT20-03', 'MOT20-05',] # TRAIN SET generate_coco_from_mot( 'mot20_train_coco', seqs_names=train_seqs, data_root=data_root) for i in range(0, len(train_seqs)): train_seqs_copy = train_seqs.copy() val_seqs = train_seqs_copy.pop(i) generate_coco_from_mot( f'mot20_train_{i + 1}_coco', seqs_names=train_seqs_copy, data_root=data_root) generate_coco_from_mot( f'mot20_val_{i + 1}_coco', seqs_names=val_seqs, data_root=data_root) # CROSS VAL FRAME SPLIT generate_coco_from_mot( 'mot20_train_cross_val_frame_0_0_to_0_5_coco', seqs_names=train_seqs, frame_range={'start': 0, 'end': 0.5}, data_root=data_root) generate_coco_from_mot( 'mot20_train_cross_val_frame_0_5_to_1_0_coco', seqs_names=train_seqs, frame_range={'start': 0.5, 'end': 1.0}, data_root=data_root) else: # # MOT17 # # CROSS VAL SPLIT 1 generate_coco_from_mot( 'mot17_train_cross_val_1_coco', seqs_names=['MOT17-04-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-11-FRCNN']) generate_coco_from_mot( 'mot17_val_cross_val_1_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-10-FRCNN', 'MOT17-13-FRCNN']) # CROSS VAL SPLIT 2 generate_coco_from_mot( 'mot17_train_cross_val_2_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-10-FRCNN', 'MOT17-13-FRCNN']) generate_coco_from_mot( 'mot17_val_cross_val_2_coco', seqs_names=['MOT17-04-FRCNN', 'MOT17-11-FRCNN']) # CROSS VAL SPLIT 3 generate_coco_from_mot( 'mot17_train_cross_val_3_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-04-FRCNN', 'MOT17-10-FRCNN', 'MOT17-11-FRCNN', 'MOT17-13-FRCNN']) generate_coco_from_mot( 'mot17_val_cross_val_3_coco', seqs_names=['MOT17-05-FRCNN', 'MOT17-09-FRCNN']) # CROSS VAL FRAME SPLIT generate_coco_from_mot( 'mot17_train_cross_val_frame_0_0_to_0_25_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-04-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-10-FRCNN', 'MOT17-11-FRCNN', 'MOT17-13-FRCNN'], frame_range={'start': 0, 'end': 0.25}) generate_coco_from_mot( 'mot17_train_cross_val_frame_0_0_to_0_5_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-04-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-10-FRCNN', 'MOT17-11-FRCNN', 'MOT17-13-FRCNN'], frame_range={'start': 0, 'end': 0.5}) generate_coco_from_mot( 'mot17_train_cross_val_frame_0_5_to_1_0_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-04-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-10-FRCNN', 'MOT17-11-FRCNN', 'MOT17-13-FRCNN'], frame_range={'start': 0.5, 'end': 1.0}) generate_coco_from_mot( 'mot17_train_cross_val_frame_0_75_to_1_0_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-04-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-10-FRCNN', 'MOT17-11-FRCNN', 'MOT17-13-FRCNN'], frame_range={'start': 0.75, 'end': 1.0}) # TRAIN SET generate_coco_from_mot( 'mot17_train_coco', seqs_names=['MOT17-02-FRCNN', 'MOT17-04-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-10-FRCNN', 'MOT17-11-FRCNN', 'MOT17-13-FRCNN']) for i in range(0, 7): train_seqs = [ 'MOT17-02-FRCNN', 'MOT17-04-FRCNN', 'MOT17-05-FRCNN', 'MOT17-09-FRCNN', 'MOT17-10-FRCNN', 'MOT17-11-FRCNN', 'MOT17-13-FRCNN'] val_seqs = train_seqs.pop(i) generate_coco_from_mot( f'mot17_train_{i + 1}_coco', seqs_names=train_seqs) generate_coco_from_mot( f'mot17_val_{i + 1}_coco', seqs_names=val_seqs) ================================================ FILE: src/parse_mot_results_to_tex.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Parse MOT results and generate a LaTeX table. """ MOTS = False MOT20 = False # F_CONTENT = """ # MOTA IDF1 MOTP MT ML FP FN Recall Precision FAF IDSW Frag # MOT17-01-DPM 41.6 44.2 77.1 5 8 496 3252 49.6 86.6 1.1 22 58 # MOT17-01-FRCNN 41.0 42.1 77.1 6 9 571 3207 50.3 85.0 1.3 25 61 # MOT17-01-SDP 41.8 44.3 76.8 7 8 612 3112 51.8 84.5 1.4 27 65 # MOT17-03-DPM 79.3 71.6 79.1 94 8 1142 20297 80.6 98.7 0.8 191 525 # MOT17-03-FRCNN 79.6 72.7 79.1 93 7 1234 19945 80.9 98.6 0.8 180 508 # MOT17-03-SDP 80.0 72.0 79.0 93 8 1223 19530 81.3 98.6 0.8 181 526 # MOT17-06-DPM 54.8 42.0 79.5 54 63 314 4839 58.9 95.7 0.3 175 244 # MOT17-06-FRCNN 55.6 42.9 79.3 57 59 363 4676 60.3 95.1 0.3 190 264 # MOT17-06-SDP 55.5 43.8 79.3 56 61 354 4712 60.0 95.2 0.3 181 262 # MOT17-07-DPM 44.8 42.0 76.6 11 16 1322 7851 53.5 87.2 2.6 147 275 # MOT17-07-FRCNN 45.5 41.5 76.6 13 15 1263 7785 53.9 87.8 2.5 156 289 # MOT17-07-SDP 45.2 42.4 76.6 13 15 1332 7775 54.0 87.3 2.7 147 279 # MOT17-08-DPM 26.5 32.2 83.0 11 37 378 15066 28.7 94.1 0.6 88 146 # MOT17-08-FRCNN 26.5 31.9 83.1 11 36 332 15113 28.5 94.8 0.5 89 141 # MOT17-08-SDP 26.6 32.3 83.1 11 36 350 15067 28.7 94.5 0.6 91 147 # MOT17-12-DPM 46.1 53.1 82.7 16 45 207 4434 48.8 95.3 0.2 30 50 # MOT17-12-FRCNN 46.1 52.6 82.6 15 45 197 4443 48.7 95.5 0.2 30 48 # MOT17-12-SDP 46.0 53.0 82.6 16 45 221 4426 48.9 95.0 0.2 30 52 # MOT17-14-DPM 31.6 36.6 74.8 13 78 636 11812 36.1 91.3 0.8 196 331 # MOT17-14-FRCNN 31.6 37.6 74.6 13 77 780 11653 37.0 89.8 1.0 202 350 # MOT17-14-SDP 31.7 37.1 74.7 13 76 749 11677 36.8 90.1 1.0 205 344 # OVERALL 61.5 59.6 78.9 621 752 14076 200672 64.4 96.3 0.8 2583 4965 # """ F_CONTENT = """ MOTA MOTP IDF1 IDP IDR TP FP FN Rcll Prcn MTR PTR MLR MT PT ML IDSW FAR FM MOT17-01-DPM 49.92 79.58 42.97 58.18 34.06 3518 258 2932 54.54 93.17 20.83 45.83 33.33 5 11 8 40 0.57 50 MOT17-01-FRCNN 50.87 79.26 42.33 55.77 34.11 3637 308 2813 56.39 92.19 33.33 41.67 25.00 8 10 6 48 0.68 57 MOT17-01-SDP 53.66 78.16 45.33 54.31 38.90 4064 556 2386 63.01 87.97 41.67 37.50 20.83 10 9 5 47 1.24 72 MOT17-03-DPM 74.05 79.41 66.45 76.34 58.83 79279 1389 25396 75.74 98.28 57.43 30.41 12.16 85 45 18 374 0.93 420 MOT17-03-FRCNN 75.34 79.45 66.98 76.21 59.75 80635 1434 24040 77.03 98.25 56.76 32.43 10.81 84 48 16 335 0.96 409 MOT17-03-SDP 79.64 79.04 65.84 72.00 60.65 86043 2134 18632 82.20 97.58 64.19 27.03 8.78 95 40 13 545 1.42 522 MOT17-06-DPM 53.62 82.55 51.83 64.47 43.33 7209 711 4575 61.18 91.02 28.38 37.84 33.78 63 84 75 180 0.60 170 MOT17-06-FRCNN 57.21 81.73 54.75 63.67 48.02 7928 960 3856 67.28 89.20 32.88 45.50 21.62 73 101 48 226 0.80 223 MOT17-06-SDP 56.43 81.93 54.00 62.70 47.42 7895 1017 3889 67.00 88.59 36.94 37.39 25.68 82 83 57 228 0.85 222 MOT17-07-DPM 52.59 80.54 48.08 66.84 37.54 9230 258 7663 54.64 97.28 20.00 53.33 26.67 12 32 16 88 0.52 148 MOT17-07-FRCNN 52.39 80.11 47.88 64.56 38.05 9456 499 7437 55.98 94.99 20.00 61.67 18.33 12 37 11 106 1.00 174 MOT17-07-SDP 54.56 79.84 47.81 62.29 38.79 9928 590 6965 58.77 94.39 26.67 55.00 18.33 16 33 11 121 1.18 199 MOT17-08-DPM 32.52 83.93 31.85 60.34 21.63 7286 288 13838 34.49 96.20 13.16 44.74 42.11 10 34 32 128 0.46 154 MOT17-08-FRCNN 31.11 84.47 31.68 62.05 21.27 6958 285 14166 32.94 96.07 13.16 39.47 47.37 10 30 36 102 0.46 120 MOT17-08-SDP 34.96 83.31 33.05 58.02 23.11 7972 443 13152 37.74 94.74 15.79 48.68 35.53 12 37 27 144 0.71 175 MOT17-12-DPM 51.26 83.01 57.74 72.70 47.88 5102 606 3565 58.87 89.38 23.08 42.86 34.07 21 39 31 53 0.67 86 MOT17-12-FRCNN 47.71 83.16 56.73 72.39 46.64 4882 702 3785 56.33 87.43 20.88 43.96 35.16 19 40 32 45 0.78 72 MOT17-12-SDP 48.88 82.87 57.46 70.30 48.59 5140 850 3527 59.31 85.81 24.18 45.05 30.77 22 41 28 54 0.94 89 MOT17-14-DPM 38.07 77.47 42.03 66.15 30.80 7978 627 10505 43.16 92.71 9.15 52.44 38.41 15 86 63 314 0.84 296 MOT17-14-FRCNN 37.78 76.70 41.78 59.55 32.18 8688 1300 9795 47.01 86.98 10.37 55.49 34.15 17 91 56 406 1.73 382 MOT17-14-SDP 40.40 76.40 42.38 57.96 33.40 9277 1376 9206 50.19 87.08 10.37 59.76 29.88 17 98 49 434 1.83 437 OVERALL\t62.30\t79.77\t57.58\t70.58\t48.62\t372105\t16591 192123 65.95 95.73 29.21 43.69 27.09 688 1029 638 4018 0.93 4477 """ # MOTS = True # F_CONTENT = """ # sMOTSA MOTSA MOTSP IDF1 MT ML MTR PTR MLR GT TP FP FN Rcll Prcn FM FMR IDSW IDSWR # MOTS20-01 59.79 79.56 77.60 68.00 10 0 83.33 16.67 0.00 12 2742 255 364 88.28 91.49 37 41.91 16 18.1 # MOTS20-06 63.91 78.72 82.85 65.14 115 22 60.53 27.89 11.58 190 8479 595 1335 86.40 93.44 218 252.32 158 182.9 # MOTS20-07 43.17 58.52 76.59 53.60 15 17 25.86 44.83 29.31 58 8445 834 4433 65.58 91.01 177 269.91 75 114.4 # MOTS20-12 62.04 74.64 84.93 76.83 41 9 60.29 26.47 13.24 68 5408 549 1063 83.57 90.78 76 90.94 29 34.7 # OVERALL 54.86 69.92 80.62 63.58 181 48 55.18 30.18 14.63 328 25074 2233 7195 77.70 91.82 508 653.77 278 357.8 # """ MOT20 = True F_CONTENT = """ MOTA MOTP IDF1 IDP IDR HOTA DetA AssA DetRe DetPr AssRe AssPr LocA TP FP FN Rcll Prcn IDSW\tMT\tML MOT20-04 82.72 82.57 75.59 79.81 71.79 63.21 68.29 58.64 73.11 81.27 63.43 80.18 84.53 236919 9639 37165 86.44 96.09 566\t490\t28 MOT20-06 55.88 79.00 53.51 68.11 44.07 43.85 45.80 42.23 49.13 75.94 45.95 74.07 81.72 80317 5582 52440 60.50 93.50 545\t96\t72 MOT20-07 56.21 85.22 59.05 78.90 47.18 49.19 48.45 50.21 50.63 84.68 53.31 83.48 86.86 19245 547 13856 58.14 97.24 92\t41\t20 MOT20-08 46.03 77.71 48.34 65.65 38.26 38.89 38.46 39.70 41.87 71.85 43.36 71.76 81.08 40572 4580 36912 52.36 89.86 329\t39\t61 OVERALL\t68.64 81.42 65.70 75.63 58.08 54.67 56.68 52.97 60.84 79.22 57.39 78.50 83.69 377053 20348 140373 72.87 94.88 1532\t666\t181 """ if __name__ == '__main__': # remove empty lines at start and beginning of F_CONTENT F_CONTENT = F_CONTENT.strip() F_CONTENT = F_CONTENT.splitlines() start_ixs = range(1, len(F_CONTENT) - 1, 3) if MOTS or MOT20: start_ixs = range(1, len(F_CONTENT) - 1) metrics_res = {} for i in range(len(['DPM', 'FRCNN', 'SDP'])): for start in start_ixs: f_list = F_CONTENT[start + i].strip().split('\t') metrics_res[f_list[0]] = f_list[1:] if MOTS or MOT20: break metrics_names = F_CONTENT[0].replace('\n', '').split() print(metrics_names) metrics_res['ALL'] = F_CONTENT[-1].strip().split('\t')[1:] for full_seq_name, data in metrics_res.items(): seq_name = '-'.join(full_seq_name.split('-')[:2]) detection_name = full_seq_name.split('-')[-1] if MOTS: print(f"{seq_name} & " f"{float(data[metrics_names.index('sMOTSA')]):.1f} & " f"{float(data[metrics_names.index('IDF1')]):.1f} & " f"{float(data[metrics_names.index('MOTSA')]):.1f} & " f"{data[metrics_names.index('FP')]} & " f"{data[metrics_names.index('FN')]} & " f"{data[metrics_names.index('IDSW')]} \\\\") else: print(f"{seq_name} & {detection_name} & " f"{float(data[metrics_names.index('MOTA')]):.1f} & " f"{float(data[metrics_names.index('IDF1')]):.1f} & " f"{data[metrics_names.index('MT')]} & " f"{data[metrics_names.index('ML')]} & " f"{data[metrics_names.index('FP')]} & " f"{data[metrics_names.index('FN')]} & " f"{data[metrics_names.index('IDSW')]} \\\\") ================================================ FILE: src/run_with_submitit.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ A script to run multinode training with submitit. """ import os import sys import uuid from pathlib import Path from argparse import Namespace import sacred import submitit import train from trackformer.util.misc import nested_dict_to_namespace WORK_DIR = str(Path(__file__).parent.absolute()) ex = sacred.Experiment('submit', ingredients=[train.ex]) ex.add_config('cfgs/submit.yaml') def get_shared_folder() -> Path: user = os.getenv("USER") if Path("/storage/slurm").is_dir(): path = Path(f"/storage/slurm/{user}/runs") path.mkdir(exist_ok=True) return path raise RuntimeError("No shared folder available") def get_init_file() -> Path: # Init file must not exist, but it's parent dir must exist. os.makedirs(str(get_shared_folder()), exist_ok=True) init_file = get_shared_folder() / f"{uuid.uuid4().hex}_init" if init_file.exists(): os.remove(str(init_file)) return init_file class Trainer: def __init__(self, args: Namespace) -> None: self.args = args def __call__(self) -> None: sys.path.append(WORK_DIR) import train self._setup_gpu_args() train.train(self.args) def checkpoint(self) -> submitit.helpers.DelayedSubmission: import os import submitit self.args.dist_url = get_init_file().as_uri() checkpoint_file = os.path.join(self.args.output_dir, "checkpoint.pth") if os.path.exists(checkpoint_file): self.args.resume = checkpoint_file self.args.resume_optim = True self.args.resume_vis = True self.args.load_mask_head_from_model = None print("Requeuing ", self.args) empty_trainer = type(self)(self.args) return submitit.helpers.DelayedSubmission(empty_trainer) def _setup_gpu_args(self) -> None: from pathlib import Path import submitit job_env = submitit.JobEnvironment() self.args.output_dir = Path(str(self.args.output_dir).replace("%j", str(job_env.job_id))) print(self.args.output_dir) self.args.gpu = job_env.local_rank self.args.rank = job_env.global_rank self.args.world_size = job_env.num_tasks print(f"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}") def main(args: Namespace): # Note that the folder will depend on the job_id, to easily track experiments if args.job_dir == "": args.job_dir = get_shared_folder() / "%j" executor = submitit.AutoExecutor( folder=args.job_dir, cluster=args.cluster, slurm_max_num_timeout=30) # cluster setup is defined by environment variables num_gpus_per_node = args.num_gpus nodes = args.nodes timeout_min = args.timeout if args.slurm_gres: slurm_gres = args.slurm_gres else: slurm_gres = f'gpu:{num_gpus_per_node},VRAM:{args.vram}' # slurm_gres = f'gpu:rtx_8000:{num_gpus_per_node}' executor.update_parameters( mem_gb=args.mem_per_gpu * num_gpus_per_node, gpus_per_node=num_gpus_per_node, tasks_per_node=num_gpus_per_node, # one task per GPU cpus_per_task=args.cpus_per_task, nodes=nodes, timeout_min=timeout_min, # max is 60 * 72, slurm_partition=args.slurm_partition, slurm_constraint=args.slurm_constraint, slurm_comment=args.slurm_comment, slurm_exclude=args.slurm_exclude, slurm_gres=slurm_gres ) executor.update_parameters(name="fair_track") args.train.dist_url = get_init_file().as_uri() # args.output_dir = args.job_dir trainer = Trainer(args.train) job = executor.submit(trainer) print("Submitted job_id:", job.job_id) if args.cluster == 'debug': job.wait() @ex.main def load_config(_config, _run): """ We use sacred only for config loading from YAML files. """ sacred.commands.print_config(_run) if __name__ == '__main__': # TODO: hierachical Namespacing for nested dict config = ex.run_commandline().config args = nested_dict_to_namespace(config) # args.train = Namespace(**config['train']) main(args) ================================================ FILE: src/track.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import time from os import path as osp import motmetrics as mm import numpy as np import sacred import torch import tqdm import yaml from torch.utils.data import DataLoader from trackformer.datasets.tracking import TrackDatasetFactory from trackformer.models import build_model from trackformer.models.tracker import Tracker from trackformer.util.misc import nested_dict_to_namespace from trackformer.util.track_utils import (evaluate_mot_accums, get_mot_accum, interpolate_tracks, plot_sequence) mm.lap.default_solver = 'lap' ex = sacred.Experiment('track') ex.add_config('cfgs/track.yaml') ex.add_named_config('reid', 'cfgs/track_reid.yaml') @ex.automain def main(seed, dataset_name, obj_detect_checkpoint_file, tracker_cfg, write_images, output_dir, interpolate, verbose, load_results_dir, data_root_dir, generate_attention_maps, frame_range, _config, _log, _run, obj_detector_model=None): if write_images: assert output_dir is not None # obj_detector_model is only provided when run as evaluation during # training. in that case we omit verbose outputs. if obj_detector_model is None: sacred.commands.print_config(_run) # set all seeds if seed is not None: torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed) torch.backends.cudnn.deterministic = True if output_dir is not None: if not osp.exists(output_dir): os.makedirs(output_dir) yaml.dump( _config, open(osp.join(output_dir, 'track.yaml'), 'w'), default_flow_style=False) ########################## # Initialize the modules # ########################## # object detection if obj_detector_model is None: obj_detect_config_path = os.path.join( os.path.dirname(obj_detect_checkpoint_file), 'config.yaml') obj_detect_args = nested_dict_to_namespace(yaml.unsafe_load(open(obj_detect_config_path))) img_transform = obj_detect_args.img_transform obj_detector, _, obj_detector_post = build_model(obj_detect_args) obj_detect_checkpoint = torch.load( obj_detect_checkpoint_file, map_location=lambda storage, loc: storage) obj_detect_state_dict = obj_detect_checkpoint['model'] # obj_detect_state_dict = { # k: obj_detect_state_dict[k] if k in obj_detect_state_dict # else v # for k, v in obj_detector.state_dict().items()} obj_detect_state_dict = { k.replace('detr.', ''): v for k, v in obj_detect_state_dict.items() if 'track_encoding' not in k} obj_detector.load_state_dict(obj_detect_state_dict) if 'epoch' in obj_detect_checkpoint: _log.info(f"INIT object detector [EPOCH: {obj_detect_checkpoint['epoch']}]") obj_detector.cuda() else: obj_detector = obj_detector_model['model'] obj_detector_post = obj_detector_model['post'] img_transform = obj_detector_model['img_transform'] if hasattr(obj_detector, 'tracking'): obj_detector.tracking() track_logger = None if verbose: track_logger = _log.info tracker = Tracker( obj_detector, obj_detector_post, tracker_cfg, generate_attention_maps, track_logger, verbose) time_total = 0 num_frames = 0 mot_accums = [] dataset = TrackDatasetFactory( dataset_name, root_dir=data_root_dir, img_transform=img_transform) for seq in dataset: tracker.reset() _log.info(f"------------------") _log.info(f"TRACK SEQ: {seq}") start_frame = int(frame_range['start'] * len(seq)) end_frame = int(frame_range['end'] * len(seq)) seq_loader = DataLoader( torch.utils.data.Subset(seq, range(start_frame, end_frame))) num_frames += len(seq_loader) results = seq.load_results(load_results_dir) if not results: start = time.time() for frame_id, frame_data in enumerate(tqdm.tqdm(seq_loader, file=sys.stdout)): with torch.no_grad(): tracker.step(frame_data) results = tracker.get_results() time_total += time.time() - start _log.info(f"NUM TRACKS: {len(results)} ReIDs: {tracker.num_reids}") _log.info(f"RUNTIME: {time.time() - start :.2f} s") if interpolate: results = interpolate_tracks(results) if output_dir is not None: _log.info(f"WRITE RESULTS") seq.write_results(results, output_dir) else: _log.info("LOAD RESULTS") if seq.no_gt: _log.info("NO GT AVAILBLE") else: mot_accum = get_mot_accum(results, seq_loader) mot_accums.append(mot_accum) if verbose: mot_events = mot_accum.mot_events reid_events = mot_events[mot_events['Type'] == 'SWITCH'] match_events = mot_events[mot_events['Type'] == 'MATCH'] switch_gaps = [] for index, event in reid_events.iterrows(): frame_id, _ = index match_events_oid = match_events[match_events['OId'] == event['OId']] match_events_oid_earlier = match_events_oid[ match_events_oid.index.get_level_values('FrameId') < frame_id] if not match_events_oid_earlier.empty: match_events_oid_earlier_frame_ids = \ match_events_oid_earlier.index.get_level_values('FrameId') last_occurrence = match_events_oid_earlier_frame_ids.max() switch_gap = frame_id - last_occurrence switch_gaps.append(switch_gap) switch_gaps_hist = None if switch_gaps: switch_gaps_hist, _ = np.histogram( switch_gaps, bins=list(range(0, max(switch_gaps) + 10, 10))) switch_gaps_hist = switch_gaps_hist.tolist() _log.info(f'SWITCH_GAPS_HIST (bin_width=10): {switch_gaps_hist}') if output_dir is not None and write_images: _log.info("PLOT SEQ") plot_sequence( results, seq_loader, osp.join(output_dir, dataset_name, str(seq)), write_images, generate_attention_maps) if time_total: _log.info(f"RUNTIME ALL SEQS (w/o EVAL or IMG WRITE): " f"{time_total:.2f} s for {num_frames} frames " f"({num_frames / time_total:.2f} Hz)") if obj_detector_model is None: _log.info(f"EVAL:") summary, str_summary = evaluate_mot_accums( mot_accums, [str(s) for s in dataset if not s.no_gt]) _log.info(f'\n{str_summary}') return summary return mot_accums ================================================ FILE: src/track_param_search.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from itertools import product import numpy as np from track import ex if __name__ == "__main__": # configs = [ # {'dataset_name': ["MOT17-02-FRCNN", "MOT17-10-FRCNN", "MOT17-13-FRCNN"], # 'obj_detect_checkpoint_file': 'models/mot17det_train_cross_val_1_mots_vis_track_bbox_proposals_track_encoding_bbox_proposals_prev_frame_5/checkpoint_best_MOTA.pth'}, # {'dataset_name': ["MOT17-04-FRCNN", "MOT17-11-FRCNN"], # 'obj_detect_checkpoint_file': 'models/mot17det_train_cross_val_2_mots_vis_track_bbox_proposals_track_encoding_bbox_proposals_prev_frame_5/checkpoint_best_MOTA.pth'}, # {'dataset_name': ["MOT17-05-FRCNN", "MOT17-09-FRCNN"], # 'obj_detect_checkpoint_file': 'models/mot17det_train_cross_val_3_mots_vis_track_bbox_proposals_track_encoding_bbox_proposals_prev_frame_5/checkpoint_best_MOTA.pth'}, # ] # configs = [ # {'dataset_name': ["MOT17-02-FRCNN"], # 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot17_train_1_no_pretrain_deformable/checkpoint_best_BBOX_AP_IoU_0_50-0_95.pth'}, # {'dataset_name': ["MOT17-04-FRCNN"], # 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot17_train_2_no_pretrain_deformable/checkpoint_best_BBOX_AP_IoU_0_50-0_95.pth'}, # {'dataset_name': ["MOT17-05-FRCNN"], # 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot17_train_3_no_pretrain_deformable/checkpoint_best_BBOX_AP_IoU_0_50-0_95.pth'}, # {'dataset_name': ["MOT17-09-FRCNN"], # 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot17_train_4_no_pretrain_deformable/checkpoint_best_BBOX_AP_IoU_0_50-0_95.pth'}, # {'dataset_name': ["MOT17-10-FRCNN"], # 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot17_train_5_no_pretrain_deformable/checkpoint_best_BBOX_AP_IoU_0_50-0_95.pth'}, # {'dataset_name': ["MOT17-11-FRCNN"], # 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot17_train_6_no_pretrain_deformable/checkpoint_best_BBOX_AP_IoU_0_50-0_95.pth'}, # {'dataset_name': ["MOT17-13-FRCNN"], # 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot17_train_7_no_pretrain_deformable/checkpoint_best_BBOX_AP_IoU_0_50-0_95.pth'}, # ] # dataset_name = ["MOT17-02-FRCNN", "MOT17-04-FRCNN", "MOT17-05-FRCNN", "MOT17-09-FRCNN", "MOT17-10-FRCNN", "MOT17-11-FRCNN", "MOT17-13-FRCNN"] # general_tracker_cfg = {'public_detections': False, 'reid_sim_only': True, 'reid_greedy_matching': False} general_tracker_cfg = {'public_detections': 'min_iou_0_5'} # general_tracker_cfg = {'public_detections': False} # dataset_name = 'MOT17-TRAIN-FRCNN' dataset_name = 'MOT17-TRAIN-ALL' # dataset_name = 'MOT20-TRAIN' configs = [ {'dataset_name': dataset_name, 'frame_range': {'start': 0.5}, 'obj_detect_checkpoint_file': '/storage/user/meinhard/fair_track/models/mot_mot17_train_cross_val_frame_0_0_to_0_5_coco_pretrained_num_queries_500_batch_size=2_num_gpus_7_num_classes_20_AP_det_overflow_boxes_True_prev_frame_rnd_augs_0_2_uniform_false_negative_prob_multi_frame_hidden_dim_288_sep_encoders_batch_queries/checkpoint_epoch_50.pth'}, ] tracker_param_grids = { # 'detection_obj_score_thresh': [0.3, 0.4, 0.5, 0.6], # 'track_obj_score_thresh': [0.3, 0.4, 0.5, 0.6], 'detection_obj_score_thresh': [0.4], 'track_obj_score_thresh': [0.4], # 'detection_nms_thresh': [0.95, 0.9, 0.0], # 'track_nms_thresh': [0.95, 0.9, 0.0], # 'detection_nms_thresh': [0.9], # 'track_nms_thresh': [0.9], # 'reid_sim_threshold': [0.0, 0.5, 1.0, 10, 50, 100, 200], 'reid_score_thresh': [0.4], # 'inactive_patience': [-1, 5, 10, 20, 30, 40, 50] # 'reid_score_thresh': [0.8], # 'inactive_patience': [-1], # 'inactive_patience': [-1, 5, 10] } # compute all config combinations tracker_param_cfgs = [dict(zip(tracker_param_grids, v)) for v in product(*tracker_param_grids.values())] # add empty metric arrays metrics = ['mota', 'idf1'] tracker_param_cfgs = [ {'config': {**general_tracker_cfg, **tracker_cfg}} for tracker_cfg in tracker_param_cfgs] for m in metrics: for tracker_cfg in tracker_param_cfgs: tracker_cfg[m] = [] total_num_experiments = len(tracker_param_cfgs) * len(configs) print(f'NUM experiments: {total_num_experiments}') # run all tracker config combinations for all experiment configurations exp_counter = 1 for config in configs: for tracker_cfg in tracker_param_cfgs: print(f"EXPERIMENT: {exp_counter}/{total_num_experiments}") config['tracker_cfg'] = tracker_cfg['config'] run = ex.run(config_updates=config) eval_summary = run.result for m in metrics: tracker_cfg[m].append(eval_summary[m]['OVERALL']) exp_counter += 1 # compute mean for all metrices for m in metrics: for tracker_cfg in tracker_param_cfgs: tracker_cfg[m] = np.array(tracker_cfg[m]).mean() for cfg in tracker_param_cfgs: print([cfg[m] for m in metrics], cfg['config']) # compute and plot best metric config for m in metrics: best_metric_cfg_idx = np.array( [cfg[m] for cfg in tracker_param_cfgs]).argmax() print(f"BEST {m.upper()} CFG: {tracker_param_cfgs[best_metric_cfg_idx]['config']}") # TODO best_mota_plus_idf1_cfg_idx = np.array( [cfg['mota'] + cfg['idf1'] for cfg in tracker_param_cfgs]).argmax() print(f"BEST MOTA PLUS IDF1 CFG: {tracker_param_cfgs[best_mota_plus_idf1_cfg_idx]['config']}") ================================================ FILE: src/trackformer/__init__.py ================================================ ================================================ FILE: src/trackformer/datasets/__init__.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Submodule interface. """ from argparse import Namespace from pycocotools.coco import COCO from torch.utils.data import Dataset, Subset from torchvision.datasets import CocoDetection from .coco import build as build_coco from .crowdhuman import build_crowdhuman from .mot import build_mot, build_mot_crowdhuman, build_mot_coco_person def get_coco_api_from_dataset(dataset: Subset) -> COCO: """Return COCO class from PyTorch dataset for evaluation with COCO eval.""" for _ in range(10): # if isinstance(dataset, CocoDetection): # break if isinstance(dataset, Subset): dataset = dataset.dataset if not isinstance(dataset, CocoDetection): raise NotImplementedError return dataset.coco def build_dataset(split: str, args: Namespace) -> Dataset: """Helper function to build dataset for different splits ('train' or 'val').""" if args.dataset == 'coco': dataset = build_coco(split, args) elif args.dataset == 'coco_person': dataset = build_coco(split, args, 'person_keypoints') elif args.dataset == 'mot': dataset = build_mot(split, args) elif args.dataset == 'crowdhuman': dataset = build_crowdhuman(split, args) elif args.dataset == 'mot_crowdhuman': dataset = build_mot_crowdhuman(split, args) elif args.dataset == 'mot_coco_person': dataset = build_mot_coco_person(split, args) elif args.dataset == 'coco_panoptic': # to avoid making panopticapi required for coco from .coco_panoptic import build as build_coco_panoptic dataset = build_coco_panoptic(split, args) else: raise ValueError(f'dataset {args.dataset} not supported') return dataset ================================================ FILE: src/trackformer/datasets/coco.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ COCO dataset which returns image_id for evaluation. Mostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py """ import copy import random from pathlib import Path from collections import Counter import torch import torch.nn.functional as F import torch.utils.data import torchvision from pycocotools import mask as coco_mask from . import transforms as T class CocoDetection(torchvision.datasets.CocoDetection): fields = ["labels", "area", "iscrowd", "boxes", "track_ids", "masks"] def __init__(self, img_folder, ann_file, transforms, norm_transforms, return_masks=False, overflow_boxes=False, remove_no_obj_imgs=True, prev_frame=False, prev_frame_rnd_augs=0.0, prev_prev_frame=False, min_num_objects=0): super(CocoDetection, self).__init__(img_folder, ann_file) self._transforms = transforms self._norm_transforms = norm_transforms self.prepare = ConvertCocoPolysToMask(return_masks, overflow_boxes) annos_image_ids = [ ann['image_id'] for ann in self.coco.loadAnns(self.coco.getAnnIds())] if remove_no_obj_imgs: self.ids = sorted(list(set(annos_image_ids))) if min_num_objects: counter = Counter(annos_image_ids) self.ids = [i for i in self.ids if counter[i] >= min_num_objects] self._prev_frame = prev_frame self._prev_frame_rnd_augs = prev_frame_rnd_augs self._prev_prev_frame = prev_prev_frame def _getitem_from_id(self, image_id, random_state=None, random_jitter=True): # if random state is given we do the data augmentation with the state # and then apply the random jitter. this ensures that (simulated) adjacent # frames have independent jitter. if random_state is not None: curr_random_state = { 'random': random.getstate(), 'torch': torch.random.get_rng_state()} random.setstate(random_state['random']) torch.random.set_rng_state(random_state['torch']) img, target = super(CocoDetection, self).__getitem__(image_id) image_id = self.ids[image_id] target = {'image_id': image_id, 'annotations': target} img, target = self.prepare(img, target) if 'track_ids' not in target: target['track_ids'] = torch.arange(len(target['labels'])) if self._transforms is not None: img, target = self._transforms(img, target) # ignore ignore = target.pop("ignore").bool() for field in self.fields: if field in target: target[f"{field}_ignore"] = target[field][ignore] target[field] = target[field][~ignore] if random_state is not None: random.setstate(curr_random_state['random']) torch.random.set_rng_state(curr_random_state['torch']) if random_jitter: img, target = self._add_random_jitter(img, target) img, target = self._norm_transforms(img, target) return img, target # TODO: add to the transforms and merge norm_transforms into transforms def _add_random_jitter(self, img, target): if self._prev_frame_rnd_augs: orig_w, orig_h = img.size crop_width = random.randint( int((1.0 - self._prev_frame_rnd_augs) * orig_w), orig_w) crop_height = int(orig_h * crop_width / orig_w) transform = T.RandomCrop((crop_height, crop_width)) img, target = transform(img, target) img, target = T.resize(img, target, (orig_w, orig_h)) return img, target # def _add_random_jitter(self, img, target): # if self._prev_frame_rnd_augs: # and random.uniform(0, 1) < 0.5: # orig_w, orig_h = img.size # width, height = img.size # size = random.randint( # int((1.0 - self._prev_frame_rnd_augs) * min(width, height)), # int((1.0 + self._prev_frame_rnd_augs) * min(width, height))) # img, target = T.RandomResize([size])(img, target) # width, height = img.size # min_size = ( # int((1.0 - self._prev_frame_rnd_augs) * width), # int((1.0 - self._prev_frame_rnd_augs) * height)) # transform = T.RandomSizeCrop(min_size=min_size) # img, target = transform(img, target) # width, height = img.size # if orig_w < width: # img, target = T.RandomCrop((height, orig_w))(img, target) # else: # total_pad = orig_w - width # pad_left = random.randint(0, total_pad) # pad_right = total_pad - pad_left # padding = (pad_left, 0, pad_right, 0) # img, target = T.pad(img, target, padding) # width, height = img.size # if orig_h < height: # img, target = T.RandomCrop((orig_h, width))(img, target) # else: # total_pad = orig_h - height # pad_top = random.randint(0, total_pad) # pad_bottom = total_pad - pad_top # padding = (0, pad_top, 0, pad_bottom) # img, target = T.pad(img, target, padding) # return img, target def __getitem__(self, idx): random_state = { 'random': random.getstate(), 'torch': torch.random.get_rng_state()} img, target = self._getitem_from_id(idx, random_state, random_jitter=False) if self._prev_frame: # PREV prev_img, prev_target = self._getitem_from_id(idx, random_state) target[f'prev_image'] = prev_img target[f'prev_target'] = prev_target if self._prev_prev_frame: # PREV PREV prev_prev_img, prev_prev_target = self._getitem_from_id(idx, random_state) target[f'prev_prev_image'] = prev_prev_img target[f'prev_prev_target'] = prev_prev_target return img, target def write_result_files(self, *args): pass def convert_coco_poly_to_mask(segmentations, height, width): masks = [] for polygons in segmentations: if isinstance(polygons, dict): rles = {'size': polygons['size'], 'counts': polygons['counts'].encode(encoding='UTF-8')} else: rles = coco_mask.frPyObjects(polygons, height, width) mask = coco_mask.decode(rles) if len(mask.shape) < 3: mask = mask[..., None] mask = torch.as_tensor(mask, dtype=torch.uint8) mask = mask.any(dim=2) masks.append(mask) if masks: masks = torch.stack(masks, dim=0) else: masks = torch.zeros((0, height, width), dtype=torch.uint8) return masks class ConvertCocoPolysToMask(object): def __init__(self, return_masks=False, overflow_boxes=False): self.return_masks = return_masks self.overflow_boxes = overflow_boxes def __call__(self, image, target): w, h = image.size image_id = target["image_id"] image_id = torch.tensor([image_id]) anno = target["annotations"] anno = [obj for obj in anno if 'iscrowd' not in obj or obj['iscrowd'] == 0] boxes = [obj["bbox"] for obj in anno] # guard against no boxes via resizing boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4) # x,y,w,h --> x,y,x,y boxes[:, 2:] += boxes[:, :2] if not self.overflow_boxes: boxes[:, 0::2].clamp_(min=0, max=w) boxes[:, 1::2].clamp_(min=0, max=h) classes = [obj["category_id"] for obj in anno] classes = torch.tensor(classes, dtype=torch.int64) if self.return_masks: segmentations = [obj["segmentation"] for obj in anno] masks = convert_coco_poly_to_mask(segmentations, h, w) keypoints = None if anno and "keypoints" in anno[0]: keypoints = [obj["keypoints"] for obj in anno] keypoints = torch.as_tensor(keypoints, dtype=torch.float32) num_keypoints = keypoints.shape[0] if num_keypoints: keypoints = keypoints.view(num_keypoints, -1, 3) keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0]) boxes = boxes[keep] classes = classes[keep] if self.return_masks: masks = masks[keep] if keypoints is not None: keypoints = keypoints[keep] target = {} target["boxes"] = boxes target["labels"] = classes - 1 if self.return_masks: target["masks"] = masks target["image_id"] = image_id if keypoints is not None: target["keypoints"] = keypoints if anno and "track_id" in anno[0]: track_ids = torch.tensor([obj["track_id"] for obj in anno]) target["track_ids"] = track_ids[keep] elif not len(boxes): target["track_ids"] = torch.empty(0) # for conversion to coco api area = torch.tensor([obj["area"] for obj in anno]) iscrowd = torch.tensor([obj["iscrowd"] if "iscrowd" in obj else 0 for obj in anno]) ignore = torch.tensor([obj["ignore"] if "ignore" in obj else 0 for obj in anno]) target["area"] = area[keep] target["iscrowd"] = iscrowd[keep] target["ignore"] = ignore[keep] target["orig_size"] = torch.as_tensor([int(h), int(w)]) target["size"] = torch.as_tensor([int(h), int(w)]) return image, target def make_coco_transforms(image_set, img_transform=None, overflow_boxes=False): normalize = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # default max_size = 1333 val_width = 800 scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800] random_resizes = [400, 500, 600] random_size_crop = (384, 600) if img_transform is not None: scale = img_transform.max_size / max_size max_size = img_transform.max_size val_width = img_transform.val_width # scale all with respect to custom max_size scales = [int(scale * s) for s in scales] random_resizes = [int(scale * s) for s in random_resizes] random_size_crop = [int(scale * s) for s in random_size_crop] if image_set == 'train': transforms = [ T.RandomHorizontalFlip(), T.RandomSelect( T.RandomResize(scales, max_size=max_size), T.Compose([ T.RandomResize(random_resizes), T.RandomSizeCrop(*random_size_crop, overflow_boxes=overflow_boxes), T.RandomResize(scales, max_size=max_size), ]) ), ] elif image_set == 'val': transforms = [ T.RandomResize([val_width], max_size=max_size), ] else: ValueError(f'unknown {image_set}') # transforms.append(normalize) return T.Compose(transforms), normalize def build(image_set, args, mode='instances'): root = Path(args.coco_path) assert root.exists(), f'provided COCO path {root} does not exist' # image_set is 'train' or 'val' split = getattr(args, f"{image_set}_split") splits = { "train": (root / "train2017", root / "annotations" / f'{mode}_train2017.json'), "val": (root / "val2017", root / "annotations" / f'{mode}_val2017.json'), } if image_set == 'train': prev_frame_rnd_augs = args.coco_and_crowdhuman_prev_frame_rnd_augs elif image_set == 'val': prev_frame_rnd_augs = 0.0 transforms, norm_transforms = make_coco_transforms(image_set, args.img_transform, args.overflow_boxes) img_folder, ann_file = splits[split] dataset = CocoDetection( img_folder, ann_file, transforms, norm_transforms, return_masks=args.masks, prev_frame=args.tracking, prev_frame_rnd_augs=prev_frame_rnd_augs, prev_prev_frame=args.track_prev_prev_frame, min_num_objects=args.coco_min_num_objects) return dataset ================================================ FILE: src/trackformer/datasets/coco_eval.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ COCO evaluator that works in distributed mode. Mostly copy-paste from https://github.com/pytorch/vision/blob/edfd5a7/references/detection/coco_eval.py The difference is that there is less copy-pasting from pycocotools in the end of the file, as python3 can suppress prints with contextlib """ import os import contextlib import copy import numpy as np import torch from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from ..util.misc import all_gather class CocoEvaluator(object): def __init__(self, coco_gt, iou_types): assert isinstance(iou_types, (list, tuple)) coco_gt = copy.deepcopy(coco_gt) self.coco_gt = coco_gt self.iou_types = iou_types self.coco_eval = {} for iou_type in iou_types: self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type) self.img_ids = [] self.eval_imgs = {k: [] for k in iou_types} def update(self, predictions): img_ids = list(np.unique(list(predictions.keys()))) self.img_ids.extend(img_ids) for prediction in predictions.values(): prediction["labels"] += 1 for iou_type in self.iou_types: results = self.prepare(predictions, iou_type) # suppress pycocotools prints with open(os.devnull, 'w') as devnull: with contextlib.redirect_stdout(devnull): coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO() coco_eval = self.coco_eval[iou_type] coco_eval.cocoDt = coco_dt coco_eval.params.imgIds = list(img_ids) img_ids, eval_imgs = evaluate(coco_eval) self.eval_imgs[iou_type].append(eval_imgs) def synchronize_between_processes(self): for iou_type in self.iou_types: self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2) create_common_coco_eval( self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type]) def accumulate(self): for coco_eval in self.coco_eval.values(): coco_eval.accumulate() def summarize(self): for iou_type, coco_eval in self.coco_eval.items(): print(f"IoU metric: {iou_type}") coco_eval.summarize() def prepare(self, predictions, iou_type): if iou_type == "bbox": return self.prepare_for_coco_detection(predictions) elif iou_type == "segm": return self.prepare_for_coco_segmentation(predictions) elif iou_type == "keypoints": return self.prepare_for_coco_keypoint(predictions) else: raise ValueError("Unknown iou type {}".format(iou_type)) def prepare_for_coco_detection(self, predictions): coco_results = [] for original_id, prediction in predictions.items(): if len(prediction) == 0: continue boxes = prediction["boxes"] boxes = convert_to_xywh(boxes).tolist() scores = prediction["scores"].tolist() labels = prediction["labels"].tolist() coco_results.extend( [ { "image_id": original_id, "category_id": labels[k], "bbox": box, "score": scores[k], } for k, box in enumerate(boxes) ] ) return coco_results def prepare_for_coco_segmentation(self, predictions): coco_results = [] for original_id, prediction in predictions.items(): if len(prediction) == 0: continue scores = prediction["scores"] labels = prediction["labels"] masks = prediction["masks"] masks = masks > 0.5 scores = prediction["scores"].tolist() labels = prediction["labels"].tolist() rles = [ mask_util.encode(np.array(mask[0, :, :, np.newaxis], dtype=np.uint8, order="F"))[0] for mask in masks ] for rle in rles: rle["counts"] = rle["counts"].decode("utf-8") coco_results.extend( [ { "image_id": original_id, "category_id": labels[k], "segmentation": rle, "score": scores[k], } for k, rle in enumerate(rles) ] ) return coco_results def prepare_for_coco_keypoint(self, predictions): coco_results = [] for original_id, prediction in predictions.items(): if len(prediction) == 0: continue boxes = prediction["boxes"] boxes = convert_to_xywh(boxes).tolist() scores = prediction["scores"].tolist() labels = prediction["labels"].tolist() keypoints = prediction["keypoints"] keypoints = keypoints.flatten(start_dim=1).tolist() coco_results.extend( [ { "image_id": original_id, "category_id": labels[k], 'keypoints': keypoint, "score": scores[k], } for k, keypoint in enumerate(keypoints) ] ) return coco_results def convert_to_xywh(boxes): xmin, ymin, xmax, ymax = boxes.unbind(1) return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1) def merge(img_ids, eval_imgs): all_img_ids = all_gather(img_ids) all_eval_imgs = all_gather(eval_imgs) merged_img_ids = [] for p in all_img_ids: merged_img_ids.extend(p) merged_eval_imgs = [] for p in all_eval_imgs: merged_eval_imgs.append(p) merged_img_ids = np.array(merged_img_ids) merged_eval_imgs = np.concatenate(merged_eval_imgs, 2) # keep only unique (and in sorted order) images merged_img_ids, idx = np.unique(merged_img_ids, return_index=True) merged_eval_imgs = merged_eval_imgs[..., idx] return merged_img_ids, merged_eval_imgs def create_common_coco_eval(coco_eval, img_ids, eval_imgs): img_ids, eval_imgs = merge(img_ids, eval_imgs) img_ids = list(img_ids) eval_imgs = list(eval_imgs.flatten()) coco_eval.evalImgs = eval_imgs coco_eval.params.imgIds = img_ids coco_eval._paramsEval = copy.deepcopy(coco_eval.params) ################################################################# # From pycocotools, just removed the prints and fixed # a Python3 bug about unicode not defined ################################################################# def evaluate(self): ''' Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None ''' # tic = time.time() # print('Running per image evaluation...') p = self.params # add backward compatibility if useSegm is specified in params if p.useSegm is not None: p.iouType = 'segm' if p.useSegm == 1 else 'bbox' print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType)) # print('Evaluate annotation type *{}*'.format(p.iouType)) p.imgIds = list(np.unique(p.imgIds)) if p.useCats: p.catIds = list(np.unique(p.catIds)) p.maxDets = sorted(p.maxDets) self.params = p self._prepare() # loop through images, area range, max detection number catIds = p.catIds if p.useCats else [-1] if p.iouType == 'segm' or p.iouType == 'bbox': computeIoU = self.computeIoU elif p.iouType == 'keypoints': computeIoU = self.computeOks self.ious = { (imgId, catId): computeIoU(imgId, catId) for imgId in p.imgIds for catId in catIds} evaluateImg = self.evaluateImg maxDet = p.maxDets[-1] evalImgs = [ evaluateImg(imgId, catId, areaRng, maxDet) for catId in catIds for areaRng in p.areaRng for imgId in p.imgIds ] # this is NOT in the pycocotools code, but could be done outside evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds)) self._paramsEval = copy.deepcopy(self.params) # toc = time.time() # print('DONE (t={:0.2f}s).'.format(toc-tic)) return p.imgIds, evalImgs ################################################################# # end of straight copy from pycocotools, just removing the prints ################################################################# ================================================ FILE: src/trackformer/datasets/coco_panoptic.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import json from pathlib import Path import numpy as np import torch from PIL import Image from panopticapi.utils import rgb2id from util.box_ops import masks_to_boxes from .coco import make_coco_transforms class CocoPanoptic: def __init__(self, img_folder, ann_folder, ann_file, transforms=None, norm_transforms=None, return_masks=True): with open(ann_file, 'r') as f: self.coco = json.load(f) # sort 'images' field so that they are aligned with 'annotations' # i.e., in alphabetical order self.coco['images'] = sorted(self.coco['images'], key=lambda x: x['id']) # sanity check if "annotations" in self.coco: for img, ann in zip(self.coco['images'], self.coco['annotations']): assert img['file_name'][:-4] == ann['file_name'][:-4] self.img_folder = img_folder self.ann_folder = ann_folder self.ann_file = ann_file self.transforms = transforms self.norm_transforms = norm_transforms self.return_masks = return_masks def __getitem__(self, idx): ann_info = self.coco['annotations'][idx] if "annotations" in self.coco else self.coco['images'][idx] img_path = Path(self.img_folder) / ann_info['file_name'].replace('.png', '.jpg') ann_path = Path(self.ann_folder) / ann_info['file_name'] img = Image.open(img_path).convert('RGB') w, h = img.size if "segments_info" in ann_info: masks = np.asarray(Image.open(ann_path), dtype=np.uint32) masks = rgb2id(masks) ids = np.array([ann['id'] for ann in ann_info['segments_info']]) masks = masks == ids[:, None, None] masks = torch.as_tensor(masks, dtype=torch.uint8) labels = torch.tensor([ann['category_id'] for ann in ann_info['segments_info']], dtype=torch.int64) target = {} target['image_id'] = torch.tensor([ann_info['image_id'] if "image_id" in ann_info else ann_info["id"]]) if self.return_masks: target['masks'] = masks target['labels'] = labels target["boxes"] = masks_to_boxes(masks) target['size'] = torch.as_tensor([int(h), int(w)]) target['orig_size'] = torch.as_tensor([int(h), int(w)]) if "segments_info" in ann_info: for name in ['iscrowd', 'area']: target[name] = torch.tensor([ann[name] for ann in ann_info['segments_info']]) if self.transforms is not None: img, target = self.transforms(img, target) if self.norm_transforms is not None: img, target = self.norm_transforms(img, target) return img, target def __len__(self): return len(self.coco['images']) def get_height_and_width(self, idx): img_info = self.coco['images'][idx] height = img_info['height'] width = img_info['width'] return height, width def build(image_set, args): img_folder_root = Path(args.coco_path) ann_folder_root = Path(args.coco_panoptic_path) assert img_folder_root.exists(), f'provided COCO path {img_folder_root} does not exist' assert ann_folder_root.exists(), f'provided COCO path {ann_folder_root} does not exist' mode = 'panoptic' PATHS = { "train": ("train2017", Path("annotations") / f'{mode}_train2017.json'), "val": ("val2017", Path("annotations") / f'{mode}_val2017.json'), } img_folder, ann_file = PATHS[image_set] img_folder_path = img_folder_root / img_folder ann_folder = ann_folder_root / f'{mode}_{img_folder}' ann_file = ann_folder_root / ann_file transforms, norm_transforms = make_coco_transforms(image_set, args.img_transform, args.overflow_boxes) dataset = CocoPanoptic(img_folder_path, ann_folder, ann_file, transforms=transforms, norm_transforms=norm_transforms, return_masks=args.masks) return dataset ================================================ FILE: src/trackformer/datasets/crowdhuman.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ CrowdHuman dataset with tracking training augmentations. """ from pathlib import Path from .coco import CocoDetection, make_coco_transforms def build_crowdhuman(image_set, args): root = Path(args.crowdhuman_path) assert root.exists(), f'provided COCO path {root} does not exist' split = getattr(args, f"{image_set}_split") img_folder = root / split ann_file = root / f'annotations/{split}.json' if image_set == 'train': prev_frame_rnd_augs = args.coco_and_crowdhuman_prev_frame_rnd_augs elif image_set == 'val': prev_frame_rnd_augs = 0.0 transforms, norm_transforms = make_coco_transforms( image_set, args.img_transform, args.overflow_boxes) dataset = CocoDetection( img_folder, ann_file, transforms, norm_transforms, return_masks=args.masks, prev_frame=args.tracking, prev_frame_rnd_augs=prev_frame_rnd_augs) return dataset ================================================ FILE: src/trackformer/datasets/mot.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MOT dataset with tracking training augmentations. """ import bisect import copy import csv import os import random from pathlib import Path import torch from . import transforms as T from .coco import CocoDetection, make_coco_transforms from .coco import build as build_coco from .crowdhuman import build_crowdhuman class MOT(CocoDetection): def __init__(self, *args, prev_frame_range=1, **kwargs): super(MOT, self).__init__(*args, **kwargs) self._prev_frame_range = prev_frame_range @property def sequences(self): return self.coco.dataset['sequences'] @property def frame_range(self): if 'frame_range' in self.coco.dataset: return self.coco.dataset['frame_range'] else: return {'start': 0, 'end': 1.0} def seq_length(self, idx): return self.coco.imgs[idx]['seq_length'] def sample_weight(self, idx): return 1.0 / self.seq_length(idx) def __getitem__(self, idx): random_state = { 'random': random.getstate(), 'torch': torch.random.get_rng_state()} img, target = self._getitem_from_id(idx, random_state, random_jitter=False) if self._prev_frame: frame_id = self.coco.imgs[idx]['frame_id'] # PREV # first frame has no previous frame prev_frame_id = random.randint( max(0, frame_id - self._prev_frame_range), min(frame_id + self._prev_frame_range, self.seq_length(idx) - 1)) prev_image_id = self.coco.imgs[idx]['first_frame_image_id'] + prev_frame_id prev_img, prev_target = self._getitem_from_id(prev_image_id, random_state) target[f'prev_image'] = prev_img target[f'prev_target'] = prev_target if self._prev_prev_frame: # PREV PREV frame equidistant as prev_frame prev_prev_frame_id = min(max(0, prev_frame_id + prev_frame_id - frame_id), self.seq_length(idx) - 1) prev_prev_image_id = self.coco.imgs[idx]['first_frame_image_id'] + prev_prev_frame_id prev_prev_img, prev_prev_target = self._getitem_from_id(prev_prev_image_id, random_state) target[f'prev_prev_image'] = prev_prev_img target[f'prev_prev_target'] = prev_prev_target return img, target def write_result_files(self, results, output_dir): """Write the detections in the format for the MOT17Det sumbission Each file contains these lines: , , , , , , , , , """ files = {} for image_id, res in results.items(): img = self.coco.loadImgs(image_id)[0] file_name_without_ext = os.path.splitext(img['file_name'])[0] seq_name, frame = file_name_without_ext.split('_') frame = int(frame) outfile = os.path.join(output_dir, f"{seq_name}.txt") # check if out in keys and create empty list if not if outfile not in files.keys(): files[outfile] = [] for box, score in zip(res['boxes'], res['scores']): if score <= 0.7: continue x1 = box[0].item() y1 = box[1].item() x2 = box[2].item() y2 = box[3].item() files[outfile].append( [frame, -1, x1, y1, x2 - x1, y2 - y1, score.item(), -1, -1, -1]) for k, v in files.items(): with open(k, "w") as of: writer = csv.writer(of, delimiter=',') for d in v: writer.writerow(d) class WeightedConcatDataset(torch.utils.data.ConcatDataset): def sample_weight(self, idx): dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) if dataset_idx == 0: sample_idx = idx else: sample_idx = idx - self.cumulative_sizes[dataset_idx - 1] if hasattr(self.datasets[dataset_idx], 'sample_weight'): return self.datasets[dataset_idx].sample_weight(sample_idx) else: return 1 / len(self.datasets[dataset_idx]) def build_mot(image_set, args): if image_set == 'train': root = Path(args.mot_path_train) prev_frame_rnd_augs = args.track_prev_frame_rnd_augs prev_frame_range=args.track_prev_frame_range elif image_set == 'val': root = Path(args.mot_path_val) prev_frame_rnd_augs = 0.0 prev_frame_range = 1 else: ValueError(f'unknown {image_set}') assert root.exists(), f'provided MOT17Det path {root} does not exist' split = getattr(args, f"{image_set}_split") img_folder = root / split ann_file = root / f"annotations/{split}.json" transforms, norm_transforms = make_coco_transforms( image_set, args.img_transform, args.overflow_boxes) dataset = MOT( img_folder, ann_file, transforms, norm_transforms, prev_frame_range=prev_frame_range, return_masks=args.masks, overflow_boxes=args.overflow_boxes, remove_no_obj_imgs=False, prev_frame=args.tracking, prev_frame_rnd_augs=prev_frame_rnd_augs, prev_prev_frame=args.track_prev_prev_frame, ) return dataset def build_mot_crowdhuman(image_set, args): if image_set == 'train': args_crowdhuman = copy.deepcopy(args) args_crowdhuman.train_split = args.crowdhuman_train_split crowdhuman_dataset = build_crowdhuman('train', args_crowdhuman) if getattr(args, f"{image_set}_split") is None: return crowdhuman_dataset dataset = build_mot(image_set, args) if image_set == 'train': dataset = torch.utils.data.ConcatDataset( [dataset, crowdhuman_dataset]) return dataset def build_mot_coco_person(image_set, args): if image_set == 'train': args_coco_person = copy.deepcopy(args) args_coco_person.train_split = args.coco_person_train_split coco_person_dataset = build_coco('train', args_coco_person, 'person_keypoints') if getattr(args, f"{image_set}_split") is None: return coco_person_dataset dataset = build_mot(image_set, args) if image_set == 'train': dataset = torch.utils.data.ConcatDataset( [dataset, coco_person_dataset]) return dataset ================================================ FILE: src/trackformer/datasets/panoptic_eval.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import json import os from ..util import misc as utils try: from panopticapi.evaluation import pq_compute except ImportError: pass class PanopticEvaluator(object): def __init__(self, ann_file, ann_folder, output_dir="panoptic_eval"): self.gt_json = ann_file self.gt_folder = ann_folder if utils.is_main_process(): if not os.path.exists(output_dir): os.mkdir(output_dir) self.output_dir = output_dir self.predictions = [] def update(self, predictions): for p in predictions: with open(os.path.join(self.output_dir, p["file_name"]), "wb") as f: f.write(p.pop("png_string")) self.predictions += predictions def synchronize_between_processes(self): all_predictions = utils.all_gather(self.predictions) merged_predictions = [] for p in all_predictions: merged_predictions += p self.predictions = merged_predictions def summarize(self): if utils.is_main_process(): json_data = {"annotations": self.predictions} predictions_json = os.path.join(self.output_dir, "predictions.json") with open(predictions_json, "w") as f: f.write(json.dumps(json_data)) return pq_compute( self.gt_json, predictions_json, gt_folder=self.gt_folder, pred_folder=self.output_dir) return None ================================================ FILE: src/trackformer/datasets/tracking/__init__.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Submodule interface. """ from .factory import TrackDatasetFactory ================================================ FILE: src/trackformer/datasets/tracking/demo_sequence.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MOT17 sequence dataset. """ import configparser import csv import os from pathlib import Path import os.path as osp from argparse import Namespace from typing import Optional, Tuple, List import numpy as np import torch from PIL import Image from torch.utils.data import Dataset from ..coco import make_coco_transforms from ..transforms import Compose class DemoSequence(Dataset): """DemoSequence (MOT17) Dataset. """ def __init__(self, root_dir: str = 'data', img_transform: Namespace = None) -> None: """ Args: seq_name (string): Sequence to take vis_threshold (float): Threshold of visibility of persons above which they are selected """ super().__init__() self._data_dir = Path(root_dir) assert self._data_dir.is_dir(), f'data_root_dir:{root_dir} does not exist.' self.transforms = Compose(make_coco_transforms('val', img_transform, overflow_boxes=True)) self.data = self._sequence() self.no_gt = True def __len__(self) -> int: return len(self.data) def __str__(self) -> str: return self._data_dir.name def __getitem__(self, idx: int) -> dict: """Return the ith image converted to blob""" data = self.data[idx] img = Image.open(data['im_path']).convert("RGB") width_orig, height_orig = img.size img, _ = self.transforms(img) width, height = img.size(2), img.size(1) sample = {} sample['img'] = img sample['img_path'] = data['im_path'] sample['dets'] = torch.tensor([]) sample['orig_size'] = torch.as_tensor([int(height_orig), int(width_orig)]) sample['size'] = torch.as_tensor([int(height), int(width)]) return sample def _sequence(self) -> List[dict]: total = [] for filename in sorted(os.listdir(self._data_dir)): extension = os.path.splitext(filename)[1] if extension in ['.png', '.jpg']: total.append({'im_path': osp.join(self._data_dir, filename)}) return total def load_results(self, results_dir: str) -> dict: return {} def write_results(self, results: dict, output_dir: str) -> None: """Write the tracks in the format for MOT16/MOT17 sumbission results: dictionary with 1 dictionary for every track with {..., i:np.array([x1,y1,x2,y2]), ...} at key track_num Each file contains these lines: , , , , , , , , , """ # format_str = "{}, -1, {}, {}, {}, {}, {}, -1, -1, -1" if not os.path.exists(output_dir): os.makedirs(output_dir) result_file_path = osp.join(output_dir, self._data_dir.name) with open(result_file_path, "w") as r_file: writer = csv.writer(r_file, delimiter=',') for i, track in results.items(): for frame, data in track.items(): x1 = data['bbox'][0] y1 = data['bbox'][1] x2 = data['bbox'][2] y2 = data['bbox'][3] writer.writerow([ frame + 1, i + 1, x1 + 1, y1 + 1, x2 - x1 + 1, y2 - y1 + 1, -1, -1, -1, -1]) ================================================ FILE: src/trackformer/datasets/tracking/factory.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Factory of tracking datasets. """ from typing import Union from torch.utils.data import ConcatDataset from .demo_sequence import DemoSequence from .mot_wrapper import MOT17Wrapper, MOT20Wrapper, MOTS20Wrapper DATASETS = {} # Fill all available datasets, change here to modify / add new datasets. for split in ['TRAIN', 'TEST', 'ALL', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14']: for dets in ['DPM', 'FRCNN', 'SDP', 'ALL']: name = f'MOT17-{split}' if dets: name = f"{name}-{dets}" DATASETS[name] = ( lambda kwargs, split=split, dets=dets: MOT17Wrapper(split, dets, **kwargs)) for split in ['TRAIN', 'TEST', 'ALL', '01', '02', '03', '04', '05', '06', '07', '08']: name = f'MOT20-{split}' DATASETS[name] = ( lambda kwargs, split=split: MOT20Wrapper(split, **kwargs)) for split in ['TRAIN', 'TEST', 'ALL', '01', '02', '05', '06', '07', '09', '11', '12']: name = f'MOTS20-{split}' DATASETS[name] = ( lambda kwargs, split=split: MOTS20Wrapper(split, **kwargs)) DATASETS['DEMO'] = (lambda kwargs: [DemoSequence(**kwargs), ]) class TrackDatasetFactory: """A central class to manage the individual dataset loaders. This class contains the datasets. Once initialized the individual parts (e.g. sequences) can be accessed. """ def __init__(self, datasets: Union[str, list], **kwargs) -> None: """Initialize the corresponding dataloader. Keyword arguments: datasets -- the name of the dataset or list of dataset names kwargs -- arguments used to call the datasets """ if isinstance(datasets, str): datasets = [datasets] self._data = None for dataset in datasets: assert dataset in DATASETS, f"[!] Dataset not found: {dataset}" if self._data is None: self._data = DATASETS[dataset](kwargs) else: self._data = ConcatDataset([self._data, DATASETS[dataset](kwargs)]) def __len__(self) -> int: return len(self._data) def __getitem__(self, idx: int): return self._data[idx] ================================================ FILE: src/trackformer/datasets/tracking/mot17_sequence.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MOT17 sequence dataset. """ import configparser import csv import os import os.path as osp from argparse import Namespace from typing import Optional, Tuple, List import numpy as np import torch from PIL import Image from torch.utils.data import Dataset from ..coco import make_coco_transforms from ..transforms import Compose class MOT17Sequence(Dataset): """Multiple Object Tracking (MOT17) Dataset. This dataloader is designed so that it can handle only one sequence, if more have to be handled one should inherit from this class. """ data_folder = 'MOT17' def __init__(self, root_dir: str = 'data', seq_name: Optional[str] = None, dets: str = '', vis_threshold: float = 0.0, img_transform: Namespace = None) -> None: """ Args: seq_name (string): Sequence to take vis_threshold (float): Threshold of visibility of persons above which they are selected """ super().__init__() self._seq_name = seq_name self._dets = dets self._vis_threshold = vis_threshold self._data_dir = osp.join(root_dir, self.data_folder) self._train_folders = os.listdir(os.path.join(self._data_dir, 'train')) self._test_folders = os.listdir(os.path.join(self._data_dir, 'test')) self.transforms = Compose(make_coco_transforms('val', img_transform, overflow_boxes=True)) self.data = [] self.no_gt = True if seq_name is not None: full_seq_name = seq_name if self._dets is not None: full_seq_name = f"{seq_name}-{dets}" assert full_seq_name in self._train_folders or full_seq_name in self._test_folders, \ 'Image set does not exist: {}'.format(full_seq_name) self.data = self._sequence() self.no_gt = not osp.exists(self.get_gt_file_path()) def __len__(self) -> int: return len(self.data) def __getitem__(self, idx: int) -> dict: """Return the ith image converted to blob""" data = self.data[idx] img = Image.open(data['im_path']).convert("RGB") width_orig, height_orig = img.size img, _ = self.transforms(img) width, height = img.size(2), img.size(1) sample = {} sample['img'] = img sample['dets'] = torch.tensor([det[:4] for det in data['dets']]) sample['img_path'] = data['im_path'] sample['gt'] = data['gt'] sample['vis'] = data['vis'] sample['orig_size'] = torch.as_tensor([int(height_orig), int(width_orig)]) sample['size'] = torch.as_tensor([int(height), int(width)]) return sample def _sequence(self) -> List[dict]: # public detections dets = {i: [] for i in range(1, self.seq_length + 1)} det_file = self.get_det_file_path() if osp.exists(det_file): with open(det_file, "r") as inf: reader = csv.reader(inf, delimiter=',') for row in reader: x1 = float(row[2]) - 1 y1 = float(row[3]) - 1 # This -1 accounts for the width (width of 1 x1=x2) x2 = x1 + float(row[4]) - 1 y2 = y1 + float(row[5]) - 1 score = float(row[6]) bbox = np.array([x1, y1, x2, y2, score], dtype=np.float32) dets[int(float(row[0]))].append(bbox) # accumulate total img_dir = osp.join( self.get_seq_path(), self.config['Sequence']['imDir']) boxes, visibility = self.get_track_boxes_and_visbility() total = [ {'gt': boxes[i], 'im_path': osp.join(img_dir, f"{i:06d}.jpg"), 'vis': visibility[i], 'dets': dets[i]} for i in range(1, self.seq_length + 1)] return total def get_track_boxes_and_visbility(self) -> Tuple[dict, dict]: """ Load ground truth boxes and their visibility.""" boxes = {} visibility = {} for i in range(1, self.seq_length + 1): boxes[i] = {} visibility[i] = {} gt_file = self.get_gt_file_path() if not osp.exists(gt_file): return boxes, visibility with open(gt_file, "r") as inf: reader = csv.reader(inf, delimiter=',') for row in reader: # class person, certainity 1 if int(row[6]) == 1 and int(row[7]) == 1 and float(row[8]) >= self._vis_threshold: # Make pixel indexes 0-based, should already be 0-based (or not) x1 = int(row[2]) - 1 y1 = int(row[3]) - 1 # This -1 accounts for the width (width of 1 x1=x2) x2 = x1 + int(row[4]) - 1 y2 = y1 + int(row[5]) - 1 bbox = np.array([x1, y1, x2, y2], dtype=np.float32) frame_id = int(row[0]) track_id = int(row[1]) boxes[frame_id][track_id] = bbox visibility[frame_id][track_id] = float(row[8]) return boxes, visibility def get_seq_path(self) -> str: """ Return directory path of sequence. """ full_seq_name = self._seq_name if self._dets is not None: full_seq_name = f"{self._seq_name}-{self._dets}" if full_seq_name in self._train_folders: return osp.join(self._data_dir, 'train', full_seq_name) else: return osp.join(self._data_dir, 'test', full_seq_name) def get_config_file_path(self) -> str: """ Return config file of sequence. """ return osp.join(self.get_seq_path(), 'seqinfo.ini') def get_gt_file_path(self) -> str: """ Return ground truth file of sequence. """ return osp.join(self.get_seq_path(), 'gt', 'gt.txt') def get_det_file_path(self) -> str: """ Return public detections file of sequence. """ if self._dets is None: return "" return osp.join(self.get_seq_path(), 'det', 'det.txt') @property def config(self) -> dict: """ Return config of sequence. """ config_file = self.get_config_file_path() assert osp.exists(config_file), \ f'Config file does not exist: {config_file}' config = configparser.ConfigParser() config.read(config_file) return config @property def seq_length(self) -> int: """ Return sequence length, i.e, number of frames. """ return int(self.config['Sequence']['seqLength']) def __str__(self) -> str: return f"{self._seq_name}-{self._dets}" @property def results_file_name(self) -> str: """ Generate file name of results file. """ assert self._seq_name is not None, "[!] No seq_name, probably using combined database" if self._dets is None: return f"{self._seq_name}.txt" return f"{self}.txt" def write_results(self, results: dict, output_dir: str) -> None: """Write the tracks in the format for MOT16/MOT17 sumbission results: dictionary with 1 dictionary for every track with {..., i:np.array([x1,y1,x2,y2]), ...} at key track_num Each file contains these lines: , , , , , , , , , """ # format_str = "{}, -1, {}, {}, {}, {}, {}, -1, -1, -1" if not os.path.exists(output_dir): os.makedirs(output_dir) result_file_path = osp.join(output_dir, self.results_file_name) with open(result_file_path, "w") as r_file: writer = csv.writer(r_file, delimiter=',') for i, track in results.items(): for frame, data in track.items(): x1 = data['bbox'][0] y1 = data['bbox'][1] x2 = data['bbox'][2] y2 = data['bbox'][3] writer.writerow([ frame + 1, i + 1, x1 + 1, y1 + 1, x2 - x1 + 1, y2 - y1 + 1, -1, -1, -1, -1]) def load_results(self, results_dir: str) -> dict: results = {} if results_dir is None: return results file_path = osp.join(results_dir, self.results_file_name) if not os.path.isfile(file_path): return results with open(file_path, "r") as file: csv_reader = csv.reader(file, delimiter=',') for row in csv_reader: frame_id, track_id = int(row[0]) - 1, int(row[1]) - 1 if track_id not in results: results[track_id] = {} x1 = float(row[2]) - 1 y1 = float(row[3]) - 1 x2 = float(row[4]) - 1 + x1 y2 = float(row[5]) - 1 + y1 results[track_id][frame_id] = {} results[track_id][frame_id]['bbox'] = [x1, y1, x2, y2] results[track_id][frame_id]['score'] = 1.0 return results ================================================ FILE: src/trackformer/datasets/tracking/mot20_sequence.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MOT20 sequence dataset. """ from .mot17_sequence import MOT17Sequence class MOT20Sequence(MOT17Sequence): """Multiple Object Tracking (MOT20) Dataset. This dataloader is designed so that it can handle only one sequence, if more have to be handled one should inherit from this class. """ data_folder = 'MOT20' ================================================ FILE: src/trackformer/datasets/tracking/mot_wrapper.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MOT wrapper which combines sequences to a dataset. """ from torch.utils.data import Dataset from .mot17_sequence import MOT17Sequence from .mot20_sequence import MOT20Sequence from .mots20_sequence import MOTS20Sequence class MOT17Wrapper(Dataset): """A Wrapper for the MOT_Sequence class to return multiple sequences.""" def __init__(self, split: str, dets: str, **kwargs) -> None: """Initliazes all subset of the dataset. Keyword arguments: split -- the split of the dataset to use kwargs -- kwargs for the MOT17Sequence dataset """ train_sequences = [ 'MOT17-02', 'MOT17-04', 'MOT17-05', 'MOT17-09', 'MOT17-10', 'MOT17-11', 'MOT17-13'] test_sequences = [ 'MOT17-01', 'MOT17-03', 'MOT17-06', 'MOT17-07', 'MOT17-08', 'MOT17-12', 'MOT17-14'] if split == "TRAIN": sequences = train_sequences elif split == "TEST": sequences = test_sequences elif split == "ALL": sequences = train_sequences + test_sequences sequences = sorted(sequences) elif f"MOT17-{split}" in train_sequences + test_sequences: sequences = [f"MOT17-{split}"] else: raise NotImplementedError("MOT17 split not available.") self._data = [] for seq in sequences: if dets == 'ALL': self._data.append(MOT17Sequence(seq_name=seq, dets='DPM', **kwargs)) self._data.append(MOT17Sequence(seq_name=seq, dets='FRCNN', **kwargs)) self._data.append(MOT17Sequence(seq_name=seq, dets='SDP', **kwargs)) else: self._data.append(MOT17Sequence(seq_name=seq, dets=dets, **kwargs)) def __len__(self) -> int: return len(self._data) def __getitem__(self, idx: int): return self._data[idx] class MOT20Wrapper(Dataset): """A Wrapper for the MOT_Sequence class to return multiple sequences.""" def __init__(self, split: str, **kwargs) -> None: """Initliazes all subset of the dataset. Keyword arguments: split -- the split of the dataset to use kwargs -- kwargs for the MOT20Sequence dataset """ train_sequences = ['MOT20-01', 'MOT20-02', 'MOT20-03', 'MOT20-05',] test_sequences = ['MOT20-04', 'MOT20-06', 'MOT20-07', 'MOT20-08',] if split == "TRAIN": sequences = train_sequences elif split == "TEST": sequences = test_sequences elif split == "ALL": sequences = train_sequences + test_sequences sequences = sorted(sequences) elif f"MOT20-{split}" in train_sequences + test_sequences: sequences = [f"MOT20-{split}"] else: raise NotImplementedError("MOT20 split not available.") self._data = [] for seq in sequences: self._data.append(MOT20Sequence(seq_name=seq, dets=None, **kwargs)) def __len__(self) -> int: return len(self._data) def __getitem__(self, idx: int): return self._data[idx] class MOTS20Wrapper(MOT17Wrapper): """A Wrapper for the MOT_Sequence class to return multiple sequences.""" def __init__(self, split: str, **kwargs) -> None: """Initliazes all subset of the dataset. Keyword arguments: split -- the split of the dataset to use kwargs -- kwargs for the MOTS20Sequence dataset """ train_sequences = ['MOTS20-02', 'MOTS20-05', 'MOTS20-09', 'MOTS20-11'] test_sequences = ['MOTS20-01', 'MOTS20-06', 'MOTS20-07', 'MOTS20-12'] if split == "TRAIN": sequences = train_sequences elif split == "TEST": sequences = test_sequences elif split == "ALL": sequences = train_sequences + test_sequences sequences = sorted(sequences) elif f"MOTS20-{split}" in train_sequences + test_sequences: sequences = [f"MOTS20-{split}"] else: raise NotImplementedError("MOTS20 split not available.") self._data = [] for seq in sequences: self._data.append(MOTS20Sequence(seq_name=seq, **kwargs)) ================================================ FILE: src/trackformer/datasets/tracking/mots20_sequence.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MOTS20 sequence dataset. """ import csv import os import os.path as osp from argparse import Namespace from typing import Optional, Tuple import numpy as np import pycocotools.mask as rletools from .mot17_sequence import MOT17Sequence class MOTS20Sequence(MOT17Sequence): """Multiple Object and Segmentation Tracking (MOTS20) Dataset. This dataloader is designed so that it can handle only one sequence, if more have to be handled one should inherit from this class. """ data_folder = 'MOTS20' def __init__(self, root_dir: str = 'data', seq_name: Optional[str] = None, vis_threshold: float = 0.0, img_transform: Namespace = None) -> None: """ Args: seq_name (string): Sequence to take vis_threshold (float): Threshold of visibility of persons above which they are selected """ super().__init__(root_dir, seq_name, None, vis_threshold, img_transform) def get_track_boxes_and_visbility(self) -> Tuple[dict, dict]: boxes = {} visibility = {} for i in range(1, self.seq_length + 1): boxes[i] = {} visibility[i] = {} gt_file = self.get_gt_file_path() if not osp.exists(gt_file): return boxes, visibility mask_objects_per_frame = load_mots_gt(gt_file) for frame_id, mask_objects in mask_objects_per_frame.items(): for mask_object in mask_objects: # class_id = 1 is car # class_id = 2 is pedestrian # class_id = 10 IGNORE if mask_object.class_id in [1, 10]: continue bbox = rletools.toBbox(mask_object.mask) x1, y1, w, h = [int(c) for c in bbox] bbox = np.array([x1, y1, x1 + w, y1 + h], dtype=np.float32) # area = bbox[2] * bbox[3] # image_id = img_file_name_to_id[f"{seq}_{frame_id:06d}.jpg"] # segmentation = { # 'size': mask_object.mask['size'], # 'counts': mask_object.mask['counts'].decode(encoding='UTF-8')} boxes[frame_id][mask_object.track_id] = bbox visibility[frame_id][mask_object.track_id] = 1.0 return boxes, visibility def write_results(self, results: dict, output_dir: str) -> None: if not os.path.exists(output_dir): os.makedirs(output_dir) result_file_path = osp.join(output_dir, f"{self._seq_name}.txt") with open(result_file_path, "w") as res_file: writer = csv.writer(res_file, delimiter=' ') for i, track in results.items(): for frame, data in track.items(): mask = np.asfortranarray(data['mask']) rle_mask = rletools.encode(mask) writer.writerow([ frame + 1, i + 1, 2, # class pedestrian mask.shape[0], mask.shape[1], rle_mask['counts'].decode(encoding='UTF-8')]) def load_results(self, results_dir: str) -> dict: results = {} if results_dir is None: return results file_path = osp.join(results_dir, self.results_file_name) if not os.path.isfile(file_path): return results mask_objects_per_frame = load_mots_gt(file_path) for frame_id, mask_objects in mask_objects_per_frame.items(): for mask_object in mask_objects: # class_id = 1 is car # class_id = 2 is pedestrian # class_id = 10 IGNORE if mask_object.class_id in [1, 10]: continue bbox = rletools.toBbox(mask_object.mask) x1, y1, w, h = [int(c) for c in bbox] bbox = np.array([x1, y1, x1 + w, y1 + h], dtype=np.float32) # area = bbox[2] * bbox[3] # image_id = img_file_name_to_id[f"{seq}_{frame_id:06d}.jpg"] # segmentation = { # 'size': mask_object.mask['size'], # 'counts': mask_object.mask['counts'].decode(encoding='UTF-8')} track_id = mask_object.track_id - 1 if track_id not in results: results[track_id] = {} results[track_id][frame_id - 1] = {} results[track_id][frame_id - 1]['mask'] = rletools.decode(mask_object.mask) results[track_id][frame_id - 1]['bbox'] = bbox.tolist() results[track_id][frame_id - 1]['score'] = 1.0 return results def __str__(self) -> str: return self._seq_name class SegmentedObject: """ Helper class for segmentation objects. """ def __init__(self, mask: dict, class_id: int, track_id: int) -> None: self.mask = mask self.class_id = class_id self.track_id = track_id def load_mots_gt(path: str) -> dict: """Load MOTS ground truth from path.""" objects_per_frame = {} track_ids_per_frame = {} # Check that no frame contains two objects with same id combined_mask_per_frame = {} # Check that no frame contains overlapping masks with open(path, "r") as gt_file: for line in gt_file: line = line.strip() fields = line.split(" ") frame = int(fields[0]) if frame not in objects_per_frame: objects_per_frame[frame] = [] if frame not in track_ids_per_frame: track_ids_per_frame[frame] = set() if int(fields[1]) in track_ids_per_frame[frame]: assert False, f"Multiple objects with track id {fields[1]} in frame {fields[0]}" else: track_ids_per_frame[frame].add(int(fields[1])) class_id = int(fields[2]) if not(class_id == 1 or class_id == 2 or class_id == 10): assert False, "Unknown object class " + fields[2] mask = { 'size': [int(fields[3]), int(fields[4])], 'counts': fields[5].encode(encoding='UTF-8')} if frame not in combined_mask_per_frame: combined_mask_per_frame[frame] = mask elif rletools.area(rletools.merge([ combined_mask_per_frame[frame], mask], intersect=True)): assert False, "Objects with overlapping masks in frame " + fields[0] else: combined_mask_per_frame[frame] = rletools.merge( [combined_mask_per_frame[frame], mask], intersect=False) objects_per_frame[frame].append(SegmentedObject( mask, class_id, int(fields[1]) )) return objects_per_frame ================================================ FILE: src/trackformer/datasets/transforms.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Transforms and data augmentation for both image + bbox. """ import random from typing import Union import PIL import torch import torchvision.transforms as T import torchvision.transforms.functional as F from ..util.box_ops import box_xyxy_to_cxcywh from ..util.misc import interpolate def crop(image, target, region, overflow_boxes=False): i, j, h, w = region target = target.copy() if isinstance(image, torch.Tensor): cropped_image = image[:, j:j + w, i:i + h] else: cropped_image = F.crop(image, *region) # should we do something wrt the original size? target["size"] = torch.tensor([h, w]) fields = ["labels", "area", "iscrowd", "ignore", "track_ids"] orig_area = target["area"] if "boxes" in target: boxes = target["boxes"] max_size = torch.as_tensor([w, h], dtype=torch.float32) cropped_boxes = boxes - torch.as_tensor([j, i, j, i]) if overflow_boxes: for i, box in enumerate(cropped_boxes): l, t, r, b = box if l < 0 and r < 0: l = r = 0 if l > w and r > w: l = r = w if t < 0 and b < 0: t = b = 0 if t > h and b > h: t = b = h cropped_boxes[i] = torch.tensor([l, t, r, b], dtype=box.dtype) cropped_boxes = cropped_boxes.reshape(-1, 2, 2) else: cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size) cropped_boxes = cropped_boxes.clamp(min=0) area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1) target["boxes"] = cropped_boxes.reshape(-1, 4) target["area"] = area fields.append("boxes") if "masks" in target: # FIXME should we update the area here if there are no boxes? target['masks'] = target['masks'][:, i:i + h, j:j + w] fields.append("masks") # remove elements for which the boxes or masks that have zero area if "boxes" in target or "masks" in target: # favor boxes selection when defining which elements to keep # this is compatible with previous implementation if "boxes" in target: cropped_boxes = target['boxes'].reshape(-1, 2, 2) keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1) # new area must be at least % of orginal area # keep = target["area"] >= orig_area * 0.2 else: keep = target['masks'].flatten(1).any(1) for field in fields: if field in target: target[field] = target[field][keep] return cropped_image, target def hflip(image, target): if isinstance(image, torch.Tensor): flipped_image = image.flip(-1) _, width, _ = image.size() else: flipped_image = F.hflip(image) width, _ = image.size target = target.copy() if "boxes" in target: boxes = target["boxes"] boxes = boxes[:, [2, 1, 0, 3]] \ * torch.as_tensor([-1, 1, -1, 1]) \ + torch.as_tensor([width, 0, width, 0]) target["boxes"] = boxes if "boxes_ignore" in target: boxes = target["boxes_ignore"] boxes = boxes[:, [2, 1, 0, 3]] \ * torch.as_tensor([-1, 1, -1, 1]) \ + torch.as_tensor([width, 0, width, 0]) target["boxes_ignore"] = boxes if "masks" in target: target['masks'] = target['masks'].flip(-1) return flipped_image, target def resize(image, target, size, max_size=None): # size can be min_size (scalar) or (w, h) tuple def get_size_with_aspect_ratio(image_size, size, max_size=None): w, h = image_size if max_size is not None: min_original_size = float(min((w, h))) max_original_size = float(max((w, h))) if max_original_size / min_original_size * size > max_size: size = int(round(max_size * min_original_size / max_original_size)) if (w <= h and w == size) or (h <= w and h == size): return (h, w) if w < h: ow = size oh = int(size * h / w) else: oh = size ow = int(size * w / h) return (oh, ow) def get_size(image_size, size, max_size=None): if isinstance(size, (list, tuple)): return size[::-1] else: return get_size_with_aspect_ratio(image_size, size, max_size) size = get_size(image.size, size, max_size) rescaled_image = F.resize(image, size) if target is None: return rescaled_image, None ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size)) ratio_width, ratio_height = ratios target = target.copy() if "boxes" in target: boxes = target["boxes"] scaled_boxes = boxes \ * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height]) target["boxes"] = scaled_boxes if "area" in target: area = target["area"] scaled_area = area * (ratio_width * ratio_height) target["area"] = scaled_area h, w = size target["size"] = torch.tensor([h, w]) if "masks" in target: target['masks'] = interpolate( target['masks'][:, None].float(), size, mode="nearest")[:, 0] > 0.5 return rescaled_image, target def pad(image, target, padding): # pad_left, pad_top, pad_right, pad_bottom padded_image = F.pad(image, padding) if target is None: return padded_image, None target = target.copy() # should we do something wrt the original size? w, h = padded_image.size if "boxes" in target: # correct xyxy from left and right paddings target["boxes"] += torch.tensor( [padding[0], padding[1], padding[0], padding[1]]) target["size"] = torch.tensor([h, w]) if "masks" in target: # padding_left, padding_right, padding_top, padding_bottom target['masks'] = torch.nn.functional.pad( target['masks'], (padding[0], padding[2], padding[1], padding[3])) return padded_image, target class RandomCrop: def __init__(self, size, overflow_boxes=False): # in hxw self.size = size self.overflow_boxes = overflow_boxes def __call__(self, img, target): region = T.RandomCrop.get_params(img, self.size) return crop(img, target, region, self.overflow_boxes) class RandomSizeCrop: def __init__(self, min_size: Union[tuple, list, int], max_size: Union[tuple, list, int] = None, overflow_boxes: bool = False): if isinstance(min_size, int): min_size = (min_size, min_size) if isinstance(max_size, int): max_size = (max_size, max_size) self.min_size = min_size self.max_size = max_size self.overflow_boxes = overflow_boxes def __call__(self, img: PIL.Image.Image, target: dict): if self.max_size is None: w = random.randint(min(self.min_size[0], img.width), img.width) h = random.randint(min(self.min_size[1], img.height), img.height) else: w = random.randint( min(self.min_size[0], img.width), min(img.width, self.max_size[0])) h = random.randint( min(self.min_size[1], img.height), min(img.height, self.max_size[1])) region = T.RandomCrop.get_params(img, [h, w]) return crop(img, target, region, self.overflow_boxes) class CenterCrop: def __init__(self, size, overflow_boxes=False): self.size = size self.overflow_boxes = overflow_boxes def __call__(self, img, target): image_width, image_height = img.size crop_height, crop_width = self.size crop_top = int(round((image_height - crop_height) / 2.)) crop_left = int(round((image_width - crop_width) / 2.)) return crop(img, target, (crop_top, crop_left, crop_height, crop_width), self.overflow_boxes) class RandomHorizontalFlip: def __init__(self, p=0.5): self.p = p def __call__(self, img, target): if random.random() < self.p: return hflip(img, target) return img, target class RepeatUntilMaxObjects: def __init__(self, transforms, num_max_objects): self._num_max_objects = num_max_objects self._transforms = transforms def __call__(self, img, target): num_objects = None while num_objects is None or num_objects > self._num_max_objects: img_trans, target_trans = self._transforms(img, target) num_objects = len(target_trans['boxes']) return img_trans, target_trans class RandomResize: def __init__(self, sizes, max_size=None): assert isinstance(sizes, (list, tuple)) self.sizes = sizes self.max_size = max_size def __call__(self, img, target=None): size = random.choice(self.sizes) return resize(img, target, size, self.max_size) class RandomResizeTargets: def __init__(self, scale=0.5): self.scalce = scale def __call__(self, img, target=None): img = F.to_tensor(img) img_c, img_w, img_h = img.shape rescaled_boxes = [] rescaled_box_images = [] for box in target['boxes']: y1, x1, y2, x2 = box.int().tolist() w = x2 - x1 h = y2 - y1 box_img = img[:, x1:x2, y1:y2] random_scale = random.uniform(0.5, 2.0) scaled_width = int(random_scale * w) scaled_height = int(random_scale * h) box_img = F.to_pil_image(box_img) rescaled_box_image = F.resize( box_img, (scaled_width, scaled_height)) rescaled_box_images.append(F.to_tensor(rescaled_box_image)) rescaled_boxes.append([y1, x1, y1 + scaled_height, x1 + scaled_width]) for box in target['boxes']: y1, x1, y2, x2 = box.int().tolist() w = x2 - x1 h = y2 - y1 erase_value = torch.empty( [img_c, w, h], dtype=torch.float32).normal_() img = F.erase( img, x1, y1, w, h, erase_value, True) for box, rescaled_box_image in zip(target['boxes'], rescaled_box_images): y1, x1, y2, x2 = box.int().tolist() w = x2 - x1 h = y2 - y1 _, scaled_width, scaled_height = rescaled_box_image.shape rescaled_box_image = rescaled_box_image[ :, :scaled_width - max(x1 + scaled_width - img_w, 0), :scaled_height - max(y1 + scaled_height - img_h, 0)] img[:, x1:x1 + scaled_width, y1:y1 + scaled_height] = rescaled_box_image target['boxes'] = torch.tensor(rescaled_boxes).float() img = F.to_pil_image(img) return img, target class RandomPad: def __init__(self, max_size): if isinstance(max_size, int): max_size = (max_size, max_size) self.max_size = max_size def __call__(self, img, target): w, h = img.size pad_width = random.randint(0, max(self.max_size[0] - w, 0)) pad_height = random.randint(0, max(self.max_size[1] - h, 0)) pad_left = random.randint(0, pad_width) pad_right = pad_width - pad_left pad_top = random.randint(0, pad_height) pad_bottom = pad_height - pad_top padding = (pad_left, pad_top, pad_right, pad_bottom) return pad(img, target, padding) class RandomSelect: """ Randomly selects between transforms1 and transforms2, with probability p for transforms1 and (1 - p) for transforms2 """ def __init__(self, transforms1, transforms2, p=0.5): self.transforms1 = transforms1 self.transforms2 = transforms2 self.p = p def __call__(self, img, target): if random.random() < self.p: return self.transforms1(img, target) return self.transforms2(img, target) class ToTensor: def __call__(self, img, target=None): return F.to_tensor(img), target class RandomErasing: def __init__(self, p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), value=0, inplace=False): self.eraser = T.RandomErasing() self.p = p self.scale = scale self.ratio = ratio self.value = value self.inplace = inplace def __call__(self, img, target): if random.uniform(0, 1) < self.p: img = F.to_tensor(img) x, y, h, w, v = self.eraser.get_params( img, scale=self.scale, ratio=self.ratio, value=self.value) img = F.erase(img, x, y, h, w, v, self.inplace) img = F.to_pil_image(img) # target fields = ['boxes', "labels", "area", "iscrowd", "ignore", "track_ids"] if 'boxes' in target: erased_box = torch.tensor([[y, x, y + w, x + h]]).float() lt = torch.max(erased_box[:, None, :2], target['boxes'][:, :2]) # [N,M,2] rb = torch.min(erased_box[:, None, 2:], target['boxes'][:, 2:]) # [N,M,2] wh = (rb - lt).clamp(min=0) # [N,M,2] inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] keep = inter[0] <= 0.7 * target['area'] left = torch.logical_and( target['boxes'][:, 0] < erased_box[:, 0], target['boxes'][:, 2] > erased_box[:, 0]) left = torch.logical_and(left, inter[0].bool()) right = torch.logical_and( target['boxes'][:, 0] < erased_box[:, 2], target['boxes'][:, 2] > erased_box[:, 2]) right = torch.logical_and(right, inter[0].bool()) top = torch.logical_and( target['boxes'][:, 1] < erased_box[:, 1], target['boxes'][:, 3] > erased_box[:, 1]) top = torch.logical_and(top, inter[0].bool()) bottom = torch.logical_and( target['boxes'][:, 1] < erased_box[:, 3], target['boxes'][:, 3] > erased_box[:, 3]) bottom = torch.logical_and(bottom, inter[0].bool()) only_one_crop = (top.float() + bottom.float() + left.float() + right.float()) > 1 left[only_one_crop] = False right[only_one_crop] = False top[only_one_crop] = False bottom[only_one_crop] = False target['boxes'][:, 2][left] = erased_box[:, 0] target['boxes'][:, 0][right] = erased_box[:, 2] target['boxes'][:, 3][top] = erased_box[:, 1] target['boxes'][:, 1][bottom] = erased_box[:, 3] for field in fields: if field in target: target[field] = target[field][keep] return img, target class Normalize: def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, image, target=None): image = F.normalize(image, mean=self.mean, std=self.std) if target is None: return image, None target = target.copy() h, w = image.shape[-2:] if "boxes" in target: boxes = target["boxes"] boxes = box_xyxy_to_cxcywh(boxes) boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32) target["boxes"] = boxes return image, target class Compose: def __init__(self, transforms): self.transforms = transforms def __call__(self, image, target=None): for t in self.transforms: image, target = t(image, target) return image, target def __repr__(self): format_string = self.__class__.__name__ + "(" for t in self.transforms: format_string += "\n" format_string += " {0}".format(t) format_string += "\n)" return format_string ================================================ FILE: src/trackformer/engine.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Train and eval functions used in main.py """ import logging import math import os import sys from typing import Iterable import torch from track import ex from .datasets import get_coco_api_from_dataset from .datasets.coco_eval import CocoEvaluator from .datasets.panoptic_eval import PanopticEvaluator from .models.detr_segmentation import DETRSegm from .util import misc as utils from .util.box_ops import box_iou from .util.track_utils import evaluate_mot_accums from .vis import vis_results def make_results(outputs, targets, postprocessors, tracking, return_only_orig=True): target_sizes = torch.stack([t["size"] for t in targets], dim=0) orig_target_sizes = torch.stack([t["orig_size"] for t in targets], dim=0) # remove placeholder track queries # results_mask = None # if tracking: # results_mask = [~t['track_queries_placeholder_mask'] for t in targets] # for target, res_mask in zip(targets, results_mask): # target['track_queries_mask'] = target['track_queries_mask'][res_mask] # target['track_queries_fal_pos_mask'] = target['track_queries_fal_pos_mask'][res_mask] # results = None # if not return_only_orig: # results = postprocessors['bbox'](outputs, target_sizes, results_mask) # results_orig = postprocessors['bbox'](outputs, orig_target_sizes, results_mask) # if 'segm' in postprocessors: # results_orig = postprocessors['segm']( # results_orig, outputs, orig_target_sizes, target_sizes, results_mask) # if not return_only_orig: # results = postprocessors['segm']( # results, outputs, target_sizes, target_sizes, results_mask) results = None if not return_only_orig: results = postprocessors['bbox'](outputs, target_sizes) results_orig = postprocessors['bbox'](outputs, orig_target_sizes) if 'segm' in postprocessors: results_orig = postprocessors['segm']( results_orig, outputs, orig_target_sizes, target_sizes) if not return_only_orig: results = postprocessors['segm']( results, outputs, target_sizes, target_sizes) if results is None: return results_orig, results for i, result in enumerate(results): target = targets[i] target_size = target_sizes[i].unsqueeze(dim=0) result['target'] = {} result['boxes'] = result['boxes'].cpu() # revert boxes for visualization for key in ['boxes', 'track_query_boxes']: if key in target: target[key] = postprocessors['bbox'].process_boxes( target[key], target_size)[0].cpu() if tracking and 'prev_target' in target: if 'prev_prev_target' in target: target['prev_prev_target']['boxes'] = postprocessors['bbox'].process_boxes( target['prev_prev_target']['boxes'], target['prev_prev_target']['size'].unsqueeze(dim=0))[0].cpu() target['prev_target']['boxes'] = postprocessors['bbox'].process_boxes( target['prev_target']['boxes'], target['prev_target']['size'].unsqueeze(dim=0))[0].cpu() if 'track_query_match_ids' in target and len(target['track_query_match_ids']): track_queries_iou, _ = box_iou( target['boxes'][target['track_query_match_ids']], result['boxes']) box_ids = [box_id for box_id, (is_track_query, is_fals_pos_track_query) in enumerate(zip(target['track_queries_mask'], target['track_queries_fal_pos_mask'])) if is_track_query and not is_fals_pos_track_query] result['track_queries_with_id_iou'] = torch.diagonal(track_queries_iou[:, box_ids]) return results_orig, results def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, postprocessors, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, visualizers: dict, args): vis_iter_metrics = None if visualizers: vis_iter_metrics = visualizers['iter_metrics'] model.train() criterion.train() metric_logger = utils.MetricLogger( args.vis_and_log_interval, delimiter=" ", vis=vis_iter_metrics, debug=args.debug) metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) for i, (samples, targets) in enumerate(metric_logger.log_every(data_loader, epoch)): samples = samples.to(device) targets = [utils.nested_dict_to_device(t, device) for t in targets] # in order to be able to modify targets inside the forward call we need # to pass it through as torch.nn.parallel.DistributedDataParallel only # passes copies outputs, targets, *_ = model(samples, targets) loss_dict = criterion(outputs, targets) weight_dict = criterion.weight_dict losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) # reduce losses over all GPUs for logging purposes loss_dict_reduced = utils.reduce_dict(loss_dict) loss_dict_reduced_unscaled = { f'{k}_unscaled': v for k, v in loss_dict_reduced.items()} loss_dict_reduced_scaled = { k: v * weight_dict[k] for k, v in loss_dict_reduced.items() if k in weight_dict} losses_reduced_scaled = sum(loss_dict_reduced_scaled.values()) loss_value = losses_reduced_scaled.item() if not math.isfinite(loss_value): print(f"Loss is {loss_value}, stopping training") print(loss_dict_reduced) sys.exit(1) optimizer.zero_grad() losses.backward() if args.clip_max_norm > 0: torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_max_norm) optimizer.step() metric_logger.update(loss=loss_value, **loss_dict_reduced_scaled, **loss_dict_reduced_unscaled) metric_logger.update(class_error=loss_dict_reduced['class_error']) metric_logger.update(lr=optimizer.param_groups[0]["lr"], lr_backbone=optimizer.param_groups[1]["lr"]) if visualizers and (i == 0 or not i % args.vis_and_log_interval): _, results = make_results( outputs, targets, postprocessors, args.tracking, return_only_orig=False) vis_results( visualizers['example_results'], samples.unmasked_tensor(0), results[0], targets[0], args.tracking) # gather the stats from all processes metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) return {k: meter.global_avg for k, meter in metric_logger.meters.items()} @torch.no_grad() def evaluate(model, criterion, postprocessors, data_loader, device, output_dir: str, visualizers: dict, args, epoch: int = None): model.eval() criterion.eval() metric_logger = utils.MetricLogger( args.vis_and_log_interval, delimiter=" ", debug=args.debug) metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) base_ds = get_coco_api_from_dataset(data_loader.dataset) iou_types = tuple(k for k in ('bbox', 'segm') if k in postprocessors.keys()) coco_evaluator = CocoEvaluator(base_ds, iou_types) # coco_evaluator.coco_eval[iou_types[0]].params.iouThrs = [0, 0.1, 0.5, 0.75] panoptic_evaluator = None if 'panoptic' in postprocessors.keys(): panoptic_evaluator = PanopticEvaluator( data_loader.dataset.ann_file, data_loader.dataset.ann_folder, output_dir=os.path.join(output_dir, "panoptic_eval"), ) for i, (samples, targets) in enumerate(metric_logger.log_every(data_loader, 'Test:')): samples = samples.to(device) targets = [utils.nested_dict_to_device(t, device) for t in targets] outputs, targets, *_ = model(samples, targets) loss_dict = criterion(outputs, targets) weight_dict = criterion.weight_dict # reduce losses over all GPUs for logging purposes loss_dict_reduced = utils.reduce_dict(loss_dict) loss_dict_reduced_scaled = {k: v * weight_dict[k] for k, v in loss_dict_reduced.items() if k in weight_dict} loss_dict_reduced_unscaled = {f'{k}_unscaled': v for k, v in loss_dict_reduced.items()} metric_logger.update(loss=sum(loss_dict_reduced_scaled.values()), **loss_dict_reduced_scaled, **loss_dict_reduced_unscaled) metric_logger.update(class_error=loss_dict_reduced['class_error']) if visualizers and (i == 0 or not i % args.vis_and_log_interval): results_orig, results = make_results( outputs, targets, postprocessors, args.tracking, return_only_orig=False) vis_results( visualizers['example_results'], samples.unmasked_tensor(0), results[0], targets[0], args.tracking) else: results_orig, _ = make_results(outputs, targets, postprocessors, args.tracking) # TODO. remove cocoDts from coco eval and change example results output if coco_evaluator is not None: results_orig = { target['image_id'].item(): output for target, output in zip(targets, results_orig)} coco_evaluator.update(results_orig) if panoptic_evaluator is not None: target_sizes = torch.stack([t["size"] for t in targets], dim=0) orig_target_sizes = torch.stack([t["orig_size"] for t in targets], dim=0) res_pano = postprocessors["panoptic"](outputs, target_sizes, orig_target_sizes) for j, target in enumerate(targets): image_id = target["image_id"].item() file_name = f"{image_id:012d}.png" res_pano[j]["image_id"] = image_id res_pano[j]["file_name"] = file_name panoptic_evaluator.update(res_pano) # gather the stats from all processes metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) if coco_evaluator is not None: coco_evaluator.synchronize_between_processes() if panoptic_evaluator is not None: panoptic_evaluator.synchronize_between_processes() # accumulate predictions from all images if coco_evaluator is not None: coco_evaluator.accumulate() coco_evaluator.summarize() panoptic_res = None if panoptic_evaluator is not None: panoptic_res = panoptic_evaluator.summarize() stats = {k: meter.global_avg for k, meter in metric_logger.meters.items()} if coco_evaluator is not None: if 'bbox' in coco_evaluator.coco_eval: stats['coco_eval_bbox'] = coco_evaluator.coco_eval['bbox'].stats.tolist() if 'segm' in coco_evaluator.coco_eval: stats['coco_eval_masks'] = coco_evaluator.coco_eval['segm'].stats.tolist() if panoptic_res is not None: stats['PQ_all'] = panoptic_res["All"] stats['PQ_th'] = panoptic_res["Things"] stats['PQ_st'] = panoptic_res["Stuff"] # TRACK EVAL if args.tracking and args.tracking_eval: stats['track_bbox'] = [] ex.logger = logging.getLogger("submitit") # distribute evaluation of seqs to processes seqs = data_loader.dataset.sequences seqs_per_rank = {i: [] for i in range(utils.get_world_size())} for i, seq in enumerate(seqs): rank = i % utils.get_world_size() seqs_per_rank[rank].append(seq) # only evaluate one seq in debug mode if args.debug: seqs_per_rank = {k: v[:1] for k, v in seqs_per_rank.items()} seqs = [s for ss in seqs_per_rank.values() for s in ss] dataset_name = seqs_per_rank[utils.get_rank()] if not dataset_name: dataset_name = seqs_per_rank[0] model_without_ddp = model if args.distributed: model_without_ddp = model.module # mask prediction is too slow and consumes a lot of memory to # run it during tracking training. if isinstance(model, DETRSegm): model_without_ddp = model_without_ddp.detr obj_detector_model = { 'model': model_without_ddp, 'post': postprocessors, 'img_transform': args.img_transform} config_updates = { 'seed': None, 'dataset_name': dataset_name, 'frame_range': data_loader.dataset.frame_range, 'obj_detector_model': obj_detector_model} run = ex.run(config_updates=config_updates) mot_accums = utils.all_gather(run.result)[:len(seqs)] mot_accums = [item for sublist in mot_accums for item in sublist] # we compute seqs results on muliple nodes but evaluate the accumulated # results due to seqs being weighted differently (seg length) eval_summary, eval_summary_str = evaluate_mot_accums( mot_accums, seqs) print(eval_summary_str) for metric in ['mota', 'idf1']: eval_m = eval_summary[metric]['OVERALL'] stats['track_bbox'].append(eval_m) eval_stats = stats['coco_eval_bbox'][:3] if 'coco_eval_masks' in stats: eval_stats.extend(stats['coco_eval_masks'][:3]) if 'track_bbox' in stats: eval_stats.extend(stats['track_bbox']) # VIS if visualizers: vis_epoch = visualizers['epoch_metrics'] y_data = [stats[legend_name] for legend_name in vis_epoch.viz_opts['legend']] vis_epoch.plot(y_data, epoch) visualizers['epoch_eval'].plot(eval_stats, epoch) if args.debug: exit() return eval_stats, coco_evaluator ================================================ FILE: src/trackformer/models/__init__.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from .backbone import build_backbone from .deformable_detr import DeformableDETR, DeformablePostProcess from .deformable_transformer import build_deforamble_transformer from .detr import DETR, PostProcess, SetCriterion from .detr_segmentation import (DeformableDETRSegm, DeformableDETRSegmTracking, DETRSegm, DETRSegmTracking, PostProcessPanoptic, PostProcessSegm) from .detr_tracking import DeformableDETRTracking, DETRTracking from .matcher import build_matcher from .transformer import build_transformer def build_model(args): if args.dataset == 'coco': num_classes = 91 elif args.dataset == 'coco_panoptic': num_classes = 250 elif args.dataset in ['coco_person', 'mot', 'mot_crowdhuman', 'crowdhuman', 'mot_coco_person']: # num_classes = 91 num_classes = 20 # num_classes = 1 else: raise NotImplementedError device = torch.device(args.device) backbone = build_backbone(args) matcher = build_matcher(args) detr_kwargs = { 'backbone': backbone, 'num_classes': num_classes - 1 if args.focal_loss else num_classes, 'num_queries': args.num_queries, 'aux_loss': args.aux_loss, 'overflow_boxes': args.overflow_boxes} tracking_kwargs = { 'track_query_false_positive_prob': args.track_query_false_positive_prob, 'track_query_false_negative_prob': args.track_query_false_negative_prob, 'matcher': matcher, 'backprop_prev_frame': args.track_backprop_prev_frame,} mask_kwargs = { 'freeze_detr': args.freeze_detr} if args.deformable: transformer = build_deforamble_transformer(args) detr_kwargs['transformer'] = transformer detr_kwargs['num_feature_levels'] = args.num_feature_levels detr_kwargs['with_box_refine'] = args.with_box_refine detr_kwargs['two_stage'] = args.two_stage detr_kwargs['multi_frame_attention'] = args.multi_frame_attention detr_kwargs['multi_frame_encoding'] = args.multi_frame_encoding detr_kwargs['merge_frame_features'] = args.merge_frame_features if args.tracking: if args.masks: model = DeformableDETRSegmTracking(mask_kwargs, tracking_kwargs, detr_kwargs) else: model = DeformableDETRTracking(tracking_kwargs, detr_kwargs) else: if args.masks: model = DeformableDETRSegm(mask_kwargs, detr_kwargs) else: model = DeformableDETR(**detr_kwargs) else: transformer = build_transformer(args) detr_kwargs['transformer'] = transformer if args.tracking: if args.masks: model = DETRSegmTracking(mask_kwargs, tracking_kwargs, detr_kwargs) else: model = DETRTracking(tracking_kwargs, detr_kwargs) else: if args.masks: model = DETRSegm(mask_kwargs, detr_kwargs) else: model = DETR(**detr_kwargs) weight_dict = {'loss_ce': args.cls_loss_coef, 'loss_bbox': args.bbox_loss_coef, 'loss_giou': args.giou_loss_coef,} if args.masks: weight_dict["loss_mask"] = args.mask_loss_coef weight_dict["loss_dice"] = args.dice_loss_coef # TODO this is a hack if args.aux_loss: aux_weight_dict = {} for i in range(args.dec_layers - 1): aux_weight_dict.update({k + f'_{i}': v for k, v in weight_dict.items()}) if args.two_stage: aux_weight_dict.update({k + f'_enc': v for k, v in weight_dict.items()}) weight_dict.update(aux_weight_dict) losses = ['labels', 'boxes', 'cardinality'] if args.masks: losses.append('masks') criterion = SetCriterion( num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=args.eos_coef, losses=losses, focal_loss=args.focal_loss, focal_alpha=args.focal_alpha, focal_gamma=args.focal_gamma, tracking=args.tracking, track_query_false_positive_eos_weight=args.track_query_false_positive_eos_weight,) criterion.to(device) if args.focal_loss: postprocessors = {'bbox': DeformablePostProcess()} else: postprocessors = {'bbox': PostProcess()} if args.masks: postprocessors['segm'] = PostProcessSegm() if args.dataset == "coco_panoptic": is_thing_map = {i: i <= 90 for i in range(201)} postprocessors["panoptic"] = PostProcessPanoptic(is_thing_map, threshold=0.85) return model, criterion, postprocessors ================================================ FILE: src/trackformer/models/backbone.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Backbone modules. """ from typing import Dict, List import torch import torch.nn.functional as F import torchvision from torch import nn from torchvision.models._utils import IntermediateLayerGetter from torchvision.ops.feature_pyramid_network import (FeaturePyramidNetwork, LastLevelMaxPool) from ..util.misc import NestedTensor, is_main_process from .position_encoding import build_position_encoding class FrozenBatchNorm2d(torch.nn.Module): """ BatchNorm2d where the batch statistics and the affine parameters are fixed. Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than torchvision.models.resnet[18,34,50,101] produce nans. """ def __init__(self, n): super(FrozenBatchNorm2d, self).__init__() self.register_buffer("weight", torch.ones(n)) self.register_buffer("bias", torch.zeros(n)) self.register_buffer("running_mean", torch.zeros(n)) self.register_buffer("running_var", torch.ones(n)) def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): num_batches_tracked_key = prefix + 'num_batches_tracked' if num_batches_tracked_key in state_dict: del state_dict[num_batches_tracked_key] super(FrozenBatchNorm2d, self)._load_from_state_dict( state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) def forward(self, x): # move reshapes to the beginning # to make it fuser-friendly w = self.weight.reshape(1, -1, 1, 1) b = self.bias.reshape(1, -1, 1, 1) rv = self.running_var.reshape(1, -1, 1, 1) rm = self.running_mean.reshape(1, -1, 1, 1) eps = 1e-5 scale = w * (rv + eps).rsqrt() bias = b - rm * scale return x * scale + bias class BackboneBase(nn.Module): def __init__(self, backbone: nn.Module, train_backbone: bool, return_interm_layers: bool): super().__init__() for name, parameter in backbone.named_parameters(): if (not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name): parameter.requires_grad_(False) if return_interm_layers: return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"} # return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"} self.strides = [4, 8, 16, 32] self.num_channels = [256, 512, 1024, 2048] else: return_layers = {'layer4': "0"} self.strides = [32] self.num_channels = [2048] self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) def forward(self, tensor_list: NestedTensor): xs = self.body(tensor_list.tensors) out: Dict[str, NestedTensor] = {} for name, x in xs.items(): m = tensor_list.mask assert m is not None mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0] out[name] = NestedTensor(x, mask) return out class Backbone(BackboneBase): """ResNet backbone with frozen BatchNorm.""" def __init__(self, name: str, train_backbone: bool, return_interm_layers: bool, dilation: bool): norm_layer = FrozenBatchNorm2d backbone = getattr(torchvision.models, name)( replace_stride_with_dilation=[False, False, dilation], pretrained=is_main_process(), norm_layer=norm_layer) super().__init__(backbone, train_backbone, return_interm_layers) if dilation: self.strides[-1] = self.strides[-1] // 2 class Joiner(nn.Sequential): def __init__(self, backbone, position_embedding): super().__init__(backbone, position_embedding) self.strides = backbone.strides self.num_channels = backbone.num_channels def forward(self, tensor_list: NestedTensor): xs = self[0](tensor_list) out: List[NestedTensor] = [] pos = [] for x in xs.values(): out.append(x) # position encoding pos.append(self[1](x).to(x.tensors.dtype)) return out, pos def build_backbone(args): position_embedding = build_position_encoding(args) train_backbone = args.lr_backbone > 0 return_interm_layers = args.masks or (args.num_feature_levels > 1) backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation) model = Joiner(backbone, position_embedding) return model ================================================ FILE: src/trackformer/models/deformable_detr.py ================================================ # ------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # ------------------------------------------------------------------------ """ Deformable DETR model and criterion classes. """ import copy import math import torch import torch.nn.functional as F from torch import nn from ..util import box_ops from ..util.misc import NestedTensor, inverse_sigmoid, nested_tensor_from_tensor_list from .detr import DETR, PostProcess, SetCriterion def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) class DeformableDETR(DETR): """ This is the Deformable DETR module that performs object detection """ def __init__(self, backbone, transformer, num_classes, num_queries, num_feature_levels, aux_loss=True, with_box_refine=False, two_stage=False, overflow_boxes=False, multi_frame_attention=False, multi_frame_encoding=False, merge_frame_features=False): """ Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_classes: number of object classes num_queries: number of object queries, ie detection slot. This is the maximal number of objects DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. with_box_refine: iterative bounding box refinement two_stage: two-stage Deformable DETR """ super().__init__(backbone, transformer, num_classes, num_queries, aux_loss) self.merge_frame_features = merge_frame_features self.multi_frame_attention = multi_frame_attention self.multi_frame_encoding = multi_frame_encoding self.overflow_boxes = overflow_boxes self.num_feature_levels = num_feature_levels if not two_stage: self.query_embed = nn.Embedding(num_queries, self.hidden_dim * 2) num_channels = backbone.num_channels[-3:] if num_feature_levels > 1: # return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"} num_backbone_outs = len(backbone.strides) - 1 input_proj_list = [] for i in range(num_backbone_outs): in_channels = num_channels[i] input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, self.hidden_dim, kernel_size=1), nn.GroupNorm(32, self.hidden_dim), )) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, self.hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, self.hidden_dim), )) in_channels = self.hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: self.input_proj = nn.ModuleList([ nn.Sequential( nn.Conv2d(num_channels[0], self.hidden_dim, kernel_size=1), nn.GroupNorm(32, self.hidden_dim), )]) self.with_box_refine = with_box_refine self.two_stage = two_stage prior_prob = 0.01 bias_value = -math.log((1 - prior_prob) / prior_prob) self.class_embed.bias.data = torch.ones_like(self.class_embed.bias) * bias_value nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0) nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0) for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) # if two-stage, the last class_embed and bbox_embed is for # region proposal generation num_pred = transformer.decoder.num_layers if two_stage: num_pred += 1 if with_box_refine: self.class_embed = _get_clones(self.class_embed, num_pred) self.bbox_embed = _get_clones(self.bbox_embed, num_pred) nn.init.constant_(self.bbox_embed[0].layers[-1].bias.data[2:], -2.0) # hack implementation for iterative bounding box refinement self.transformer.decoder.bbox_embed = self.bbox_embed else: nn.init.constant_(self.bbox_embed.layers[-1].bias.data[2:], -2.0) self.class_embed = nn.ModuleList([self.class_embed for _ in range(num_pred)]) self.bbox_embed = nn.ModuleList([self.bbox_embed for _ in range(num_pred)]) self.transformer.decoder.bbox_embed = None if two_stage: # hack implementation for two-stage self.transformer.decoder.class_embed = self.class_embed for box_embed in self.bbox_embed: nn.init.constant_(box_embed.layers[-1].bias.data[2:], 0.0) if self.merge_frame_features: self.merge_features = nn.Conv2d(self.hidden_dim * 2, self.hidden_dim, kernel_size=1) self.merge_features = _get_clones(self.merge_features, num_feature_levels) # def fpn_channels(self): # """ Returns FPN channels. """ # num_backbone_outs = len(self.backbone.strides) # return [self.hidden_dim, ] * num_backbone_outs def forward(self, samples: NestedTensor, targets: list = None, prev_features=None): """ The forward expects a NestedTensor, which consists of: - samples.tensors: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x (num_classes + 1)] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, height, width). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if not isinstance(samples, NestedTensor): samples = nested_tensor_from_tensor_list(samples) features, pos = self.backbone(samples) features_all = features # pos_all = pos # return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"} features = features[-3:] # pos = pos[-3:] if prev_features is None: prev_features = features else: prev_features = prev_features[-3:] # srcs = [] # masks = [] src_list = [] mask_list = [] pos_list = [] # for l, (feat, prev_feat) in enumerate(zip(features, prev_features)): frame_features = [prev_features, features] if not self.multi_frame_attention: frame_features = [features] for frame, frame_feat in enumerate(frame_features): if self.multi_frame_attention and self.multi_frame_encoding: pos_list.extend([p[:, frame] for p in pos[-3:]]) else: pos_list.extend(pos[-3:]) # src, mask = feat.decompose() # prev_src, _ = prev_feat.decompose() for l, feat in enumerate(frame_feat): src, mask = feat.decompose() if self.merge_frame_features: prev_src, _ = prev_features[l].decompose() src_list.append(self.merge_features[l](torch.cat([self.input_proj[l](src), self.input_proj[l](prev_src)], dim=1))) else: src_list.append(self.input_proj[l](src)) mask_list.append(mask) # if hasattr(self, 'merge_features'): # srcs.append(self.merge_features[l](torch.cat([self.input_proj[l](src), self.input_proj[l](prev_src)], dim=1))) # else: # srcs.append(self.input_proj[l](src)) # masks.append(mask) assert mask is not None if self.num_feature_levels > len(frame_feat): _len_srcs = len(frame_feat) for l in range(_len_srcs, self.num_feature_levels): if l == _len_srcs: # src = self.input_proj[l](frame_feat[-1].tensors) # if hasattr(self, 'merge_features'): # src = self.merge_features[l](torch.cat([self.input_proj[l](features[-1].tensors), self.input_proj[l](prev_features[-1].tensors)], dim=1)) # else: # src = self.input_proj[l](features[-1].tensors) if self.merge_frame_features: src = self.merge_features[l](torch.cat([self.input_proj[l](frame_feat[-1].tensors), self.input_proj[l](prev_features[-1].tensors)], dim=1)) else: src = self.input_proj[l](frame_feat[-1].tensors) else: src = self.input_proj[l](src_list[-1]) # src = self.input_proj[l](srcs[-1]) # m = samples.mask _, m = frame_feat[0].decompose() mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0] pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype) src_list.append(src) mask_list.append(mask) if self.multi_frame_attention and self.multi_frame_encoding: pos_list.append(pos_l[:, frame]) else: pos_list.append(pos_l) query_embeds = None if not self.two_stage: query_embeds = self.query_embed.weight hs, memory, init_reference, inter_references, enc_outputs_class, enc_outputs_coord_unact = \ self.transformer(src_list, mask_list, pos_list, query_embeds, targets) outputs_classes = [] outputs_coords = [] for lvl in range(hs.shape[0]): if lvl == 0: reference = init_reference else: reference = inter_references[lvl - 1] reference = inverse_sigmoid(reference) outputs_class = self.class_embed[lvl](hs[lvl]) tmp = self.bbox_embed[lvl](hs[lvl]) if reference.shape[-1] == 4: tmp += reference else: assert reference.shape[-1] == 2 tmp[..., :2] += reference outputs_coord = tmp.sigmoid() outputs_classes.append(outputs_class) outputs_coords.append(outputs_coord) outputs_class = torch.stack(outputs_classes) outputs_coord = torch.stack(outputs_coords) out = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1], 'hs_embed': hs[-1]} if self.aux_loss: out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord) if self.two_stage: enc_outputs_coord = enc_outputs_coord_unact.sigmoid() out['enc_outputs'] = {'pred_logits': enc_outputs_class, 'pred_boxes': enc_outputs_coord} offset = 0 memory_slices = [] batch_size, _, channels = memory.shape for src in src_list: _, _, height, width = src.shape memory_slice = memory[:, offset:offset + height * width].permute(0, 2, 1).view( batch_size, channels, height, width) memory_slices.append(memory_slice) offset += height * width memory = memory_slices # memory = memory_slices[-1] # features = [NestedTensor(memory_slide) for memory_slide in memory_slices] return out, targets, features_all, memory, hs @torch.jit.unused def _set_aux_loss(self, outputs_class, outputs_coord): # this is a workaround to make torchscript happy, as torchscript # doesn't support dictionary with non-homogeneous values, such # as a dict having both a Tensor and a list. return [{'pred_logits': a, 'pred_boxes': b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])] class DeformablePostProcess(PostProcess): """ This module converts the model's output into the format expected by the coco api""" @torch.no_grad() def forward(self, outputs, target_sizes, results_mask=None): """ Perform the computation Parameters: outputs: raw outputs of the model target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch For evaluation, this must be the original image size (before any data augmentation) For visualization, this should be the image size after data augment, but before padding """ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes'] assert len(out_logits) == len(target_sizes) assert target_sizes.shape[1] == 2 prob = out_logits.sigmoid() ### # topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 100, dim=1) # scores = topk_values # topk_boxes = topk_indexes // out_logits.shape[2] # labels = topk_indexes % out_logits.shape[2] # boxes = box_ops.box_cxcywh_to_xyxy(out_bbox) # boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1,1,4)) ### scores, labels = prob.max(-1) # scores, labels = prob[..., 0:1].max(-1) boxes = box_ops.box_cxcywh_to_xyxy(out_bbox) # and from relative [0, 1] to absolute [0, height] coordinates img_h, img_w = target_sizes.unbind(1) scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1) boxes = boxes * scale_fct[:, None, :] results = [ {'scores': s, 'scores_no_object': 1 - s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)] if results_mask is not None: for i, mask in enumerate(results_mask): for k, v in results[i].items(): results[i][k] = v[mask] return results ================================================ FILE: src/trackformer/models/deformable_transformer.py ================================================ # ------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # ------------------------------------------------------------------------ import math import torch from torch import nn from torch.nn.init import constant_, normal_, xavier_uniform_ from ..util.misc import inverse_sigmoid from .ops.modules import MSDeformAttn from .transformer import _get_clones, _get_activation_fn class DeformableTransformer(nn.Module): def __init__(self, d_model=256, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=1024, dropout=0.1, activation="relu", return_intermediate_dec=False, num_feature_levels=4, dec_n_points=4, enc_n_points=4, two_stage=False, two_stage_num_proposals=300, multi_frame_attention_separate_encoder=False): super().__init__() self.d_model = d_model self.nhead = nhead self.two_stage = two_stage self.two_stage_num_proposals = two_stage_num_proposals self.num_feature_levels = num_feature_levels self.multi_frame_attention_separate_encoder = multi_frame_attention_separate_encoder enc_num_feature_levels = num_feature_levels if multi_frame_attention_separate_encoder: enc_num_feature_levels = enc_num_feature_levels // 2 encoder_layer = DeformableTransformerEncoderLayer(d_model, dim_feedforward, dropout, activation, enc_num_feature_levels, nhead, enc_n_points) self.encoder = DeformableTransformerEncoder(encoder_layer, num_encoder_layers) decoder_layer = DeformableTransformerDecoderLayer(d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, dec_n_points) self.decoder = DeformableTransformerDecoder(decoder_layer, num_decoder_layers, return_intermediate_dec) self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model)) if two_stage: self.enc_output = nn.Linear(d_model, d_model) self.enc_output_norm = nn.LayerNorm(d_model) self.pos_trans = nn.Linear(d_model * 2, d_model * 2) self.pos_trans_norm = nn.LayerNorm(d_model * 2) else: self.reference_points = nn.Linear(d_model, 2) # self.hs_embed_to_query_embed = nn.Linear(d_model, d_model) # self.hs_embed_to_tgt = nn.Linear(d_model, d_model) # self.track_query_embed = nn.Embedding(1, d_model) self._reset_parameters() def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules(): if isinstance(m, MSDeformAttn): m._reset_parameters() if not self.two_stage: xavier_uniform_(self.reference_points.weight.data, gain=1.0) constant_(self.reference_points.bias.data, 0.) normal_(self.level_embed) def get_proposal_pos_embed(self, proposals): num_pos_feats = 128 temperature = 10000 scale = 2 * math.pi dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=proposals.device) dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats) # N, L, 4 proposals = proposals.sigmoid() * scale # N, L, 4, 128 pos = proposals[:, :, :, None] / dim_t # N, L, 4, 64, 2 pos = torch.stack((pos[:, :, :, 0::2].sin(), pos[:, :, :, 1::2].cos()), dim=4).flatten(2) return pos def gen_encoder_output_proposals(self, memory, memory_padding_mask, spatial_shapes): N_, S_, C_ = memory.shape base_scale = 4.0 proposals = [] _cur = 0 for lvl, (H_, W_) in enumerate(spatial_shapes): mask_flatten_ = memory_padding_mask[:, _cur:(_cur + H_ * W_)].view(N_, H_, W_, 1) valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1) valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1) grid_y, grid_x = torch.meshgrid(torch.linspace(0, H_ - 1, H_, dtype=torch.float32, device=memory.device), torch.linspace(0, W_ - 1, W_, dtype=torch.float32, device=memory.device)) grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1) scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N_, 1, 1, 2) grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale wh = torch.ones_like(grid) * 0.05 * (2.0 ** lvl) proposal = torch.cat((grid, wh), -1).view(N_, -1, 4) proposals.append(proposal) _cur += (H_ * W_) output_proposals = torch.cat(proposals, 1) output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(-1, keepdim=True) output_proposals = torch.log(output_proposals / (1 - output_proposals)) output_proposals = output_proposals.masked_fill(memory_padding_mask.unsqueeze(-1), float('inf')) output_proposals = output_proposals.masked_fill(~output_proposals_valid, float('inf')) output_memory = memory output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0)) output_memory = output_memory.masked_fill(~output_proposals_valid, float(0)) output_memory = self.enc_output_norm(self.enc_output(output_memory)) return output_memory, output_proposals def get_valid_ratio(self, mask): _, H, W = mask.shape valid_H = torch.sum(~mask[:, :, 0], 1) valid_W = torch.sum(~mask[:, 0, :], 1) valid_ratio_h = valid_H.float() / H valid_ratio_w = valid_W.float() / W valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1) return valid_ratio def forward(self, srcs, masks, pos_embeds, query_embed=None, targets=None): assert self.two_stage or query_embed is not None # prepare input for encoder src_flatten = [] mask_flatten = [] lvl_pos_embed_flatten = [] spatial_shapes = [] for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)): bs, c, h, w = src.shape spatial_shape = (h, w) spatial_shapes.append(spatial_shape) src = src.flatten(2).transpose(1, 2) mask = mask.flatten(1) pos_embed = pos_embed.flatten(2).transpose(1, 2) lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) # lvl_pos_embed = pos_embed + self.level_embed[lvl % self.num_feature_levels].view(1, 1, -1) lvl_pos_embed_flatten.append(lvl_pos_embed) src_flatten.append(src) mask_flatten.append(mask) src_flatten = torch.cat(src_flatten, 1) mask_flatten = torch.cat(mask_flatten, 1) lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) spatial_shapes = torch.as_tensor(spatial_shapes, dtype=torch.long, device=src_flatten.device) valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1) # encoder if self.multi_frame_attention_separate_encoder: prev_memory = self.encoder( src_flatten[:, :src_flatten.shape[1] // 2], spatial_shapes[:self.num_feature_levels // 2], valid_ratios[:, :self.num_feature_levels // 2], lvl_pos_embed_flatten[:, :src_flatten.shape[1] // 2], mask_flatten[:, :src_flatten.shape[1] // 2]) memory = self.encoder( src_flatten[:, src_flatten.shape[1] // 2:], spatial_shapes[self.num_feature_levels // 2:], valid_ratios[:, self.num_feature_levels // 2:], lvl_pos_embed_flatten[:, src_flatten.shape[1] // 2:], mask_flatten[:, src_flatten.shape[1] // 2:]) memory = torch.cat([memory, prev_memory], 1) else: memory = self.encoder(src_flatten, spatial_shapes, valid_ratios, lvl_pos_embed_flatten, mask_flatten) # prepare input for decoder bs, _, c = memory.shape query_attn_mask = None if self.two_stage: output_memory, output_proposals = self.gen_encoder_output_proposals(memory, mask_flatten, spatial_shapes) # hack implementation for two-stage Deformable DETR enc_outputs_class = self.decoder.class_embed[self.decoder.num_layers](output_memory) enc_outputs_coord_unact = self.decoder.bbox_embed[self.decoder.num_layers](output_memory) + output_proposals topk = self.two_stage_num_proposals topk_proposals = torch.topk(enc_outputs_class[..., 0], topk, dim=1)[1] topk_coords_unact = torch.gather(enc_outputs_coord_unact, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)) topk_coords_unact = topk_coords_unact.detach() reference_points = topk_coords_unact.sigmoid() init_reference_out = reference_points pos_trans_out = self.pos_trans_norm(self.pos_trans(self.get_proposal_pos_embed(topk_coords_unact))) query_embed, tgt = torch.split(pos_trans_out, c, dim=2) else: query_embed, tgt = torch.split(query_embed, c, dim=1) query_embed = query_embed.unsqueeze(0).expand(bs, -1, -1) tgt = tgt.unsqueeze(0).expand(bs, -1, -1) reference_points = self.reference_points(query_embed).sigmoid() if targets is not None and 'track_query_hs_embeds' in targets[0]: # print([t['track_query_hs_embeds'].shape for t in targets]) # prev_hs_embed = torch.nn.utils.rnn.pad_sequence([t['track_query_hs_embeds'] for t in targets], batch_first=True, padding_value=float('nan')) # prev_boxes = torch.nn.utils.rnn.pad_sequence([t['track_query_boxes'] for t in targets], batch_first=True, padding_value=float('nan')) # print(prev_hs_embed.shape) # query_mask = torch.isnan(prev_hs_embed) # print(query_mask) prev_hs_embed = torch.stack([t['track_query_hs_embeds'] for t in targets]) prev_boxes = torch.stack([t['track_query_boxes'] for t in targets]) prev_query_embed = torch.zeros_like(prev_hs_embed) # prev_query_embed = self.track_query_embed.weight.expand_as(prev_hs_embed) # prev_query_embed = self.hs_embed_to_query_embed(prev_hs_embed) # prev_query_embed = None prev_tgt = prev_hs_embed # prev_tgt = self.hs_embed_to_tgt(prev_hs_embed) query_embed = torch.cat([prev_query_embed, query_embed], dim=1) tgt = torch.cat([prev_tgt, tgt], dim=1) reference_points = torch.cat([prev_boxes[..., :2], reference_points], dim=1) # if 'track_queries_placeholder_mask' in targets[0]: # query_attn_mask = torch.stack([t['track_queries_placeholder_mask'] for t in targets]) init_reference_out = reference_points # decoder # query_embed = None hs, inter_references = self.decoder( tgt, reference_points, memory, spatial_shapes, valid_ratios, query_embed, mask_flatten, query_attn_mask) inter_references_out = inter_references # offset = 0 # memory_slices = [] # for src in srcs: # _, _, height, width = src.shape # memory_slice = memory[:, offset:offset +h * w].permute(0, 2, 1).view( # bs, c, height, width) # memory_slices.append(memory_slice) # offset += h * w # # memory = memory_slices[-1] # print([m.shape for m in memory_slices]) if self.two_stage: return (hs, memory, init_reference_out, inter_references_out, enc_outputs_class, enc_outputs_coord_unact) return hs, memory, init_reference_out, inter_references_out, None, None class DeformableTransformerEncoderLayer(nn.Module): def __init__(self, d_model=256, d_ffn=1024, dropout=0.1, activation="relu", n_levels=4, n_heads=8, n_points=4): super().__init__() # self attention self.self_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points) self.dropout1 = nn.Dropout(dropout) self.norm1 = nn.LayerNorm(d_model) # ffn self.linear1 = nn.Linear(d_model, d_ffn) self.activation = _get_activation_fn(activation) self.dropout2 = nn.Dropout(dropout) self.linear2 = nn.Linear(d_ffn, d_model) self.dropout3 = nn.Dropout(dropout) self.norm2 = nn.LayerNorm(d_model) @staticmethod def with_pos_embed(tensor, pos): return tensor if pos is None else tensor + pos def forward_ffn(self, src): src2 = self.linear2(self.dropout2(self.activation(self.linear1(src)))) src = src + self.dropout3(src2) src = self.norm2(src) return src def forward(self, src, pos, reference_points, spatial_shapes, padding_mask=None): # self attention src2 = self.self_attn(self.with_pos_embed(src, pos), reference_points, src, spatial_shapes, padding_mask) src = src + self.dropout1(src2) src = self.norm1(src) # ffn src = self.forward_ffn(src) return src class DeformableTransformerEncoder(nn.Module): def __init__(self, encoder_layer, num_layers): super().__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers @staticmethod def get_reference_points(spatial_shapes, valid_ratios, device): reference_points_list = [] for lvl, (H_, W_) in enumerate(spatial_shapes): ref_y, ref_x = torch.meshgrid(torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device), torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device)) ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_) ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_) ref = torch.stack((ref_x, ref_y), -1) reference_points_list.append(ref) reference_points = torch.cat(reference_points_list, 1) reference_points = reference_points[:, :, None] * valid_ratios[:, None] return reference_points def forward(self, src, spatial_shapes, valid_ratios, pos=None, padding_mask=None): output = src reference_points = self.get_reference_points(spatial_shapes, valid_ratios, device=src.device) for _, layer in enumerate(self.layers): output = layer(output, pos, reference_points, spatial_shapes, padding_mask) return output class DeformableTransformerDecoderLayer(nn.Module): def __init__(self, d_model=256, d_ffn=1024, dropout=0.1, activation="relu", n_levels=4, n_heads=8, n_points=4): super().__init__() # cross attention self.cross_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points) self.dropout1 = nn.Dropout(dropout) self.norm1 = nn.LayerNorm(d_model) # self attention self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) self.dropout2 = nn.Dropout(dropout) self.norm2 = nn.LayerNorm(d_model) # ffn self.linear1 = nn.Linear(d_model, d_ffn) self.activation = _get_activation_fn(activation) self.dropout3 = nn.Dropout(dropout) self.linear2 = nn.Linear(d_ffn, d_model) self.dropout4 = nn.Dropout(dropout) self.norm3 = nn.LayerNorm(d_model) @staticmethod def with_pos_embed(tensor, pos): return tensor if pos is None else tensor + pos def forward_ffn(self, tgt): tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout4(tgt2) tgt = self.norm3(tgt) return tgt def forward(self, tgt, query_pos, reference_points, src, src_spatial_shapes, src_padding_mask=None, query_attn_mask=None): # self attention q = k = self.with_pos_embed(tgt, query_pos) tgt2 = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), tgt.transpose(0, 1), key_padding_mask=query_attn_mask)[0].transpose(0, 1) tgt = tgt + self.dropout2(tgt2) tgt = self.norm2(tgt) # cross attention tgt2 = self.cross_attn(self.with_pos_embed(tgt, query_pos), reference_points, src, src_spatial_shapes, src_padding_mask, query_attn_mask) tgt = tgt + self.dropout1(tgt2) tgt = self.norm1(tgt) # ffn tgt = self.forward_ffn(tgt) return tgt class DeformableTransformerDecoder(nn.Module): def __init__(self, decoder_layer, num_layers, return_intermediate=False): super().__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.return_intermediate = return_intermediate # hack implementation for iterative bounding box refinement and two-stage Deformable DETR self.bbox_embed = None self.class_embed = None def forward(self, tgt, reference_points, src, src_spatial_shapes, src_valid_ratios, query_pos=None, src_padding_mask=None, query_attn_mask=None): output = tgt intermediate = [] intermediate_reference_points = [] for lid, layer in enumerate(self.layers): if reference_points.shape[-1] == 4: reference_points_input = reference_points[:, :, None] \ * torch.cat([src_valid_ratios, src_valid_ratios], -1)[:, None] else: assert reference_points.shape[-1] == 2 reference_points_input = reference_points[:, :, None] * src_valid_ratios[:, None] output = layer(output, query_pos, reference_points_input, src, src_spatial_shapes, src_padding_mask, query_attn_mask) # hack implementation for iterative bounding box refinement if self.bbox_embed is not None: tmp = self.bbox_embed[lid](output) if reference_points.shape[-1] == 4: new_reference_points = tmp + inverse_sigmoid(reference_points) new_reference_points = new_reference_points.sigmoid() else: assert reference_points.shape[-1] == 2 new_reference_points = tmp new_reference_points[..., :2] = tmp[..., :2] + inverse_sigmoid(reference_points) new_reference_points = new_reference_points.sigmoid() reference_points = new_reference_points.detach() if self.return_intermediate: intermediate.append(output) intermediate_reference_points.append(reference_points) if self.return_intermediate: return torch.stack(intermediate), torch.stack(intermediate_reference_points) return output, reference_points def build_deforamble_transformer(args): num_feature_levels = args.num_feature_levels if args.multi_frame_attention: num_feature_levels *= 2 return DeformableTransformer( d_model=args.hidden_dim, nhead=args.nheads, num_encoder_layers=args.enc_layers, num_decoder_layers=args.dec_layers, dim_feedforward=args.dim_feedforward, dropout=args.dropout, activation="relu", return_intermediate_dec=True, num_feature_levels=num_feature_levels, dec_n_points=args.dec_n_points, enc_n_points=args.enc_n_points, two_stage=args.two_stage, two_stage_num_proposals=args.num_queries, multi_frame_attention_separate_encoder=args.multi_frame_attention and args.multi_frame_attention_separate_encoder) ================================================ FILE: src/trackformer/models/detr.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ DETR model and criterion classes. """ import copy import torch import torch.nn.functional as F from torch import nn from ..util import box_ops from ..util.misc import (NestedTensor, accuracy, dice_loss, get_world_size, interpolate, is_dist_avail_and_initialized, nested_tensor_from_tensor_list, sigmoid_focal_loss) class DETR(nn.Module): """ This is the DETR module that performs object detection. """ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False, overflow_boxes=False): """ Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_classes: number of object classes num_queries: number of object queries, ie detection slot. This is the maximal number of objects DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.overflow_boxes = overflow_boxes self.class_embed = nn.Linear(self.hidden_dim, num_classes + 1) self.bbox_embed = MLP(self.hidden_dim, self.hidden_dim, 4, 3) self.query_embed = nn.Embedding(num_queries, self.hidden_dim) # match interface with deformable DETR self.input_proj = nn.Conv2d(backbone.num_channels[-1], self.hidden_dim, kernel_size=1) # self.input_proj = nn.ModuleList([ # nn.Sequential( # nn.Conv2d(backbone.num_channels[-1], self.hidden_dim, kernel_size=1) # )]) self.backbone = backbone self.aux_loss = aux_loss @property def hidden_dim(self): """ Returns the hidden feature dimension size. """ return self.transformer.d_model @property def fpn_channels(self): """ Returns FPN channels. """ return self.backbone.num_channels[:3][::-1] # return [1024, 512, 256] def forward(self, samples: NestedTensor, targets: list = None): """ The forward expects a NestedTensor, which consists of: - samples.tensor: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x (num_classes + 1)] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, height, width). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if not isinstance(samples, NestedTensor): samples = nested_tensor_from_tensor_list(samples) features, pos = self.backbone(samples) src, mask = features[-1].decompose() # src = self.input_proj[-1](src) src = self.input_proj(src) pos = pos[-1] batch_size, _, _, _ = src.shape query_embed = self.query_embed.weight query_embed = query_embed.unsqueeze(1).repeat(1, batch_size, 1) tgt = None if targets is not None and 'track_query_hs_embeds' in targets[0]: # [BATCH_SIZE, NUM_PROBS, 4] track_query_hs_embeds = torch.stack([t['track_query_hs_embeds'] for t in targets]) num_track_queries = track_query_hs_embeds.shape[1] track_query_embed = torch.zeros( num_track_queries, batch_size, self.hidden_dim).to(query_embed.device) query_embed = torch.cat([ track_query_embed, query_embed], dim=0) tgt = torch.zeros_like(query_embed) tgt[:num_track_queries] = track_query_hs_embeds.transpose(0, 1) for i, target in enumerate(targets): target['track_query_hs_embeds'] = tgt[:, i] assert mask is not None hs, hs_without_norm, memory = self.transformer( src, mask, query_embed, pos, tgt) outputs_class = self.class_embed(hs) outputs_coord = self.bbox_embed(hs).sigmoid() out = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1], 'hs_embed': hs_without_norm[-1]} if self.aux_loss: out['aux_outputs'] = self._set_aux_loss( outputs_class, outputs_coord) return out, targets, features, memory, hs @torch.jit.unused def _set_aux_loss(self, outputs_class, outputs_coord): # this is a workaround to make torchscript happy, as torchscript # doesn't support dictionary with non-homogeneous values, such # as a dict having both a Tensor and a list. return [{'pred_logits': a, 'pred_boxes': b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])] class SetCriterion(nn.Module): """ This class computes the loss for DETR. The process happens in two steps: 1) we compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and box) """ def __init__(self, num_classes, matcher, weight_dict, eos_coef, losses, focal_loss, focal_alpha, focal_gamma, tracking, track_query_false_positive_eos_weight): """ Create the criterion. Parameters: num_classes: number of object categories, omitting the special no-object category matcher: module able to compute a matching between targets and proposals weight_dict: dict containing as key the names of the losses and as values their relative weight. eos_coef: relative classification weight applied to the no-object category losses: list of all the losses to be applied. See get_loss for list of available losses. """ super().__init__() self.num_classes = num_classes self.matcher = matcher self.weight_dict = weight_dict self.eos_coef = eos_coef self.losses = losses empty_weight = torch.ones(self.num_classes + 1) empty_weight[-1] = self.eos_coef self.register_buffer('empty_weight', empty_weight) self.focal_loss = focal_loss self.focal_alpha = focal_alpha self.focal_gamma = focal_gamma self.tracking = tracking self.track_query_false_positive_eos_weight = track_query_false_positive_eos_weight def loss_labels(self, outputs, targets, indices, _, log=True): """Classification loss (NLL) targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes] """ assert 'pred_logits' in outputs src_logits = outputs['pred_logits'] idx = self._get_src_permutation_idx(indices) target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)]) target_classes = torch.full(src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device) target_classes[idx] = target_classes_o loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, weight=self.empty_weight, reduction='none') if self.tracking and self.track_query_false_positive_eos_weight: for i, target in enumerate(targets): if 'track_query_boxes' in target: # remove no-object weighting for false track_queries loss_ce[i, target['track_queries_fal_pos_mask']] *= 1 / self.eos_coef # assign false track_queries to some object class for the final weighting target_classes = target_classes.clone() target_classes[i, target['track_queries_fal_pos_mask']] = 0 # weight = None # if self.tracking: # weight = torch.stack([~t['track_queries_placeholder_mask'] for t in targets]).float() # loss_ce *= weight loss_ce = loss_ce.sum() / self.empty_weight[target_classes].sum() losses = {'loss_ce': loss_ce} if log: # TODO this should probably be a separate loss, not hacked in this one here losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0] return losses def loss_labels_focal(self, outputs, targets, indices, num_boxes, log=True): """Classification loss (NLL) targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes] """ assert 'pred_logits' in outputs src_logits = outputs['pred_logits'] idx = self._get_src_permutation_idx(indices) target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)]) target_classes = torch.full(src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device) target_classes[idx] = target_classes_o target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2] + 1], dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device) target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1) target_classes_onehot = target_classes_onehot[:,:,:-1] # query_mask = None # if self.tracking: # query_mask = torch.stack([~t['track_queries_placeholder_mask'] for t in targets])[..., None] # query_mask = query_mask.repeat(1, 1, self.num_classes) loss_ce = sigmoid_focal_loss( src_logits, target_classes_onehot, num_boxes, alpha=self.focal_alpha, gamma=self.focal_gamma) # , query_mask=query_mask) # if self.tracking: # mean_num_queries = torch.tensor([len(m.nonzero()) for m in query_mask]).float().mean() # loss_ce *= mean_num_queries # else: # loss_ce *= src_logits.shape[1] loss_ce *= src_logits.shape[1] losses = {'loss_ce': loss_ce} if log: # TODO this should probably be a separate loss, not hacked in this one here losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0] # compute seperate track and object query losses # loss_ce = sigmoid_focal_loss( # src_logits, target_classes_onehot, num_boxes, # alpha=self.focal_alpha, gamma=self.focal_gamma, query_mask=query_mask, reduction=False) # loss_ce *= src_logits.shape[1] # track_query_target_masks = [] # for t, ind in zip(targets, indices): # track_query_target_mask = torch.zeros_like(ind[1]).bool() # for i in t['track_query_match_ids']: # track_query_target_mask[ind[1].eq(i).nonzero()[0]] = True # track_query_target_masks.append(track_query_target_mask) # track_query_target_masks = torch.cat(track_query_target_masks) # losses['loss_ce_track_queries'] = loss_ce[idx][track_query_target_masks].mean(1).sum() / num_boxes # losses['loss_ce_object_queries'] = loss_ce[idx][~track_query_target_masks].mean(1).sum() / num_boxes return losses @torch.no_grad() def loss_cardinality(self, outputs, targets, indices, num_boxes): """ Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes. This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients """ pred_logits = outputs['pred_logits'] device = pred_logits.device tgt_lengths = torch.as_tensor([len(v["labels"]) for v in targets], device=device) # Count the number of predictions that are NOT "no-object" (which is the last class) card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1) card_err = F.l1_loss(card_pred.float(), tgt_lengths.float()) losses = {'cardinality_error': card_err} return losses def loss_boxes(self, outputs, targets, indices, num_boxes): """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]. The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size. """ assert 'pred_boxes' in outputs idx = self._get_src_permutation_idx(indices) src_boxes = outputs['pred_boxes'][idx] target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0) loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none') losses = {} losses['loss_bbox'] = loss_bbox.sum() / num_boxes loss_giou = 1 - torch.diag(box_ops.generalized_box_iou( box_ops.box_cxcywh_to_xyxy(src_boxes), box_ops.box_cxcywh_to_xyxy(target_boxes))) losses['loss_giou'] = loss_giou.sum() / num_boxes # compute seperate track and object query losses # track_query_target_masks = [] # for t, ind in zip(targets, indices): # track_query_target_mask = torch.zeros_like(ind[1]).bool() # for i in t['track_query_match_ids']: # track_query_target_mask[ind[1].eq(i).nonzero()[0]] = True # track_query_target_masks.append(track_query_target_mask) # track_query_target_masks = torch.cat(track_query_target_masks) # losses['loss_bbox_track_queries'] = loss_bbox[track_query_target_masks].sum() / num_boxes # losses['loss_bbox_object_queries'] = loss_bbox[~track_query_target_masks].sum() / num_boxes # losses['loss_giou_track_queries'] = loss_giou[track_query_target_masks].sum() / num_boxes # losses['loss_giou_object_queries'] = loss_giou[~track_query_target_masks].sum() / num_boxes return losses def loss_masks(self, outputs, targets, indices, num_boxes): """Compute the losses related to the masks: the focal loss and the dice loss. targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w] """ assert "pred_masks" in outputs src_idx = self._get_src_permutation_idx(indices) tgt_idx = self._get_tgt_permutation_idx(indices) src_masks = outputs["pred_masks"] # TODO use valid to mask invalid areas due to padding in loss target_masks, _ = nested_tensor_from_tensor_list([t["masks"] for t in targets]).decompose() target_masks = target_masks.to(src_masks) src_masks = src_masks[src_idx] # upsample predictions to the target size src_masks = interpolate(src_masks[:, None], size=target_masks.shape[-2:], mode="bilinear", align_corners=False) src_masks = src_masks[:, 0].flatten(1) target_masks = target_masks[tgt_idx].flatten(1) losses = { "loss_mask": sigmoid_focal_loss(src_masks, target_masks, num_boxes), "loss_dice": dice_loss(src_masks, target_masks, num_boxes), } return losses def _get_src_permutation_idx(self, indices): # permute predictions following indices batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)]) src_idx = torch.cat([src for (src, _) in indices]) return batch_idx, src_idx def _get_tgt_permutation_idx(self, indices): # permute targets following indices batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)]) tgt_idx = torch.cat([tgt for (_, tgt) in indices]) return batch_idx, tgt_idx def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs): loss_map = { 'labels': self.loss_labels_focal if self.focal_loss else self.loss_labels, 'cardinality': self.loss_cardinality, 'boxes': self.loss_boxes, 'masks': self.loss_masks, } assert loss in loss_map, f'do you really want to compute {loss} loss?' return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs) def forward(self, outputs, targets): """ This performs the loss computation. Parameters: outputs: dict of tensors, see the output specification of the model for the format targets: list of dicts, such that len(targets) == batch_size. The expected keys in each dict depends on the losses applied, see each loss' doc """ outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'} # Retrieve the matching between the outputs of the last layer and the targets indices = self.matcher(outputs_without_aux, targets) # Compute the average number of target boxes accross all nodes, for normalization purposes num_boxes = sum(len(t["labels"]) for t in targets) num_boxes = torch.as_tensor( [num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device) if is_dist_avail_and_initialized(): torch.distributed.all_reduce(num_boxes) num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item() # Compute all the requested losses losses = {} for loss in self.losses: losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes)) # In case of auxiliary losses, we repeat this process with the # output of each intermediate layer. if 'aux_outputs' in outputs: for i, aux_outputs in enumerate(outputs['aux_outputs']): indices = self.matcher(aux_outputs, targets) for loss in self.losses: if loss == 'masks': # Intermediate masks losses are too costly to compute, we ignore them. continue kwargs = {} if loss == 'labels': # Logging is enabled only for the last layer kwargs = {'log': False} l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs) l_dict = {k + f'_{i}': v for k, v in l_dict.items()} losses.update(l_dict) if 'enc_outputs' in outputs: enc_outputs = outputs['enc_outputs'] bin_targets = copy.deepcopy(targets) for bt in bin_targets: bt['labels'] = torch.zeros_like(bt['labels']) indices = self.matcher(enc_outputs, bin_targets) for loss in self.losses: if loss == 'masks': # Intermediate masks losses are too costly to compute, we ignore them. continue kwargs = {} if loss == 'labels': # Logging is enabled only for the last layer kwargs['log'] = False l_dict = self.get_loss(loss, enc_outputs, bin_targets, indices, num_boxes, **kwargs) l_dict = {k + f'_enc': v for k, v in l_dict.items()} losses.update(l_dict) return losses class PostProcess(nn.Module): """ This module converts the model's output into the format expected by the coco api""" def process_boxes(self, boxes, target_sizes): # convert to [x0, y0, x1, y1] format boxes = box_ops.box_cxcywh_to_xyxy(boxes) # and from relative [0, 1] to absolute [0, height] coordinates img_h, img_w = target_sizes.unbind(1) scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1) boxes = boxes * scale_fct[:, None, :] return boxes @torch.no_grad() def forward(self, outputs, target_sizes, results_mask=None): """ Perform the computation Parameters: outputs: raw outputs of the model target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch For evaluation, this must be the original image size (before any data augmentation) For visualization, this should be the image size after data augment, but before padding """ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes'] assert len(out_logits) == len(target_sizes) assert target_sizes.shape[1] == 2 prob = F.softmax(out_logits, -1) scores, labels = prob[..., :-1].max(-1) boxes = self.process_boxes(out_bbox, target_sizes) results = [ {'scores': s, 'labels': l, 'boxes': b, 'scores_no_object': s_n_o} for s, l, b, s_n_o in zip(scores, labels, boxes, prob[..., -1])] if results_mask is not None: for i, mask in enumerate(results_mask): for k, v in results[i].items(): results[i][k] = v[mask] return results class MLP(nn.Module): """ Very simple multi-layer perceptron (also called FFN)""" def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList( nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])) def forward(self, x): for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) return x ================================================ FILE: src/trackformer/models/detr_segmentation.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ This file provides the definition of the convolutional heads used to predict masks, as well as the losses. """ import io from collections import defaultdict from typing import List, Optional import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch import Tensor from ..util import box_ops from ..util.misc import NestedTensor, interpolate try: from panopticapi.utils import id2rgb, rgb2id except ImportError: pass from .deformable_detr import DeformableDETR from .detr import DETR from .detr_tracking import DETRTrackingBase class DETRSegmBase(nn.Module): def __init__(self, freeze_detr=False): if freeze_detr: for param in self.parameters(): param.requires_grad_(False) nheads = self.transformer.nhead self.bbox_attention = MHAttentionMap(self.hidden_dim, self.hidden_dim, nheads, dropout=0.0) self.mask_head = MaskHeadSmallConv( self.hidden_dim + nheads, self.fpn_channels, self.hidden_dim) def forward(self, samples: NestedTensor, targets: list = None): out, targets, features, memory, hs = super().forward(samples, targets) if isinstance(memory, list): src, mask = features[-2].decompose() batch_size = src.shape[0] src = self.input_proj[-3](src) mask = F.interpolate(mask[None].float(), size=src.shape[-2:]).to(torch.bool)[0] # fpns = [memory[2], memory[1], memory[0]] fpns = [features[-2].tensors, features[-3].tensors, features[-4].tensors] memory = memory[-3] else: src, mask = features[-1].decompose() batch_size = src.shape[0] src = self.input_proj(src) fpns = [features[2].tensors, features[1].tensors, features[0].tensors] # FIXME h_boxes takes the last one computed, keep this in mind bbox_mask = self.bbox_attention(hs[-1], memory, mask=mask) seg_masks = self.mask_head(src, bbox_mask, fpns) outputs_seg_masks = seg_masks.view( batch_size, hs.shape[2], seg_masks.shape[-2], seg_masks.shape[-1]) out["pred_masks"] = outputs_seg_masks return out, targets, features, memory, hs # TODO: with meta classes class DETRSegm(DETRSegmBase, DETR): def __init__(self, mask_kwargs, detr_kwargs): DETR.__init__(self, **detr_kwargs) DETRSegmBase.__init__(self, **mask_kwargs) class DeformableDETRSegm(DETRSegmBase, DeformableDETR): def __init__(self, mask_kwargs, detr_kwargs): DeformableDETR.__init__(self, **detr_kwargs) DETRSegmBase.__init__(self, **mask_kwargs) class DETRSegmTracking(DETRSegmBase, DETRTrackingBase, DETR): def __init__(self, mask_kwargs, tracking_kwargs, detr_kwargs): DETR.__init__(self, **detr_kwargs) DETRTrackingBase.__init__(self, **tracking_kwargs) DETRSegmBase.__init__(self, **mask_kwargs) class DeformableDETRSegmTracking(DETRSegmBase, DETRTrackingBase, DeformableDETR): def __init__(self, mask_kwargs, tracking_kwargs, detr_kwargs): DeformableDETR.__init__(self, **detr_kwargs) DETRTrackingBase.__init__(self, **tracking_kwargs) DETRSegmBase.__init__(self, **mask_kwargs) def _expand(tensor, length: int): return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1) class MaskHeadSmallConv(nn.Module): """ Simple convolutional head, using group norm. Upsampling is done using a FPN approach """ def __init__(self, dim, fpn_dims, context_dim): super().__init__() inter_dims = [ dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64] self.lay1 = torch.nn.Conv2d(dim, dim, 3, padding=1) self.gn1 = torch.nn.GroupNorm(8, dim) self.lay2 = torch.nn.Conv2d(dim, inter_dims[1], 3, padding=1) self.gn2 = torch.nn.GroupNorm(8, inter_dims[1]) self.lay3 = torch.nn.Conv2d(inter_dims[1], inter_dims[2], 3, padding=1) self.gn3 = torch.nn.GroupNorm(8, inter_dims[2]) self.lay4 = torch.nn.Conv2d(inter_dims[2], inter_dims[3], 3, padding=1) self.gn4 = torch.nn.GroupNorm(8, inter_dims[3]) self.lay5 = torch.nn.Conv2d(inter_dims[3], inter_dims[4], 3, padding=1) self.gn5 = torch.nn.GroupNorm(8, inter_dims[4]) self.out_lay = torch.nn.Conv2d(inter_dims[4], 1, 3, padding=1) self.dim = dim self.adapter1 = torch.nn.Conv2d(fpn_dims[0], inter_dims[1], 1) self.adapter2 = torch.nn.Conv2d(fpn_dims[1], inter_dims[2], 1) self.adapter3 = torch.nn.Conv2d(fpn_dims[2], inter_dims[3], 1) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_uniform_(m.weight, a=1) nn.init.constant_(m.bias, 0) def forward(self, x: Tensor, bbox_mask: Tensor, fpns: List[Tensor]): x = torch.cat([_expand(x, bbox_mask.shape[1]), bbox_mask.flatten(0, 1)], 1) x = self.lay1(x) x = self.gn1(x) x = F.relu(x) x = self.lay2(x) x = self.gn2(x) x = F.relu(x) cur_fpn = self.adapter1(fpns[0]) if cur_fpn.size(0) != x.size(0): cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0)) x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest") x = self.lay3(x) x = self.gn3(x) x = F.relu(x) cur_fpn = self.adapter2(fpns[1]) if cur_fpn.size(0) != x.size(0): cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0)) x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest") x = self.lay4(x) x = self.gn4(x) x = F.relu(x) cur_fpn = self.adapter3(fpns[2]) if cur_fpn.size(0) != x.size(0): cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0)) x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest") x = self.lay5(x) x = self.gn5(x) x = F.relu(x) x = self.out_lay(x) return x class MHAttentionMap(nn.Module): """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)""" def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True): super().__init__() self.num_heads = num_heads self.hidden_dim = hidden_dim self.dropout = nn.Dropout(dropout) self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias) self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias) nn.init.zeros_(self.k_linear.bias) nn.init.zeros_(self.q_linear.bias) nn.init.xavier_uniform_(self.k_linear.weight) nn.init.xavier_uniform_(self.q_linear.weight) self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5 def forward(self, q, k, mask: Optional[Tensor] = None): q = self.q_linear(q) k = F.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias) qh = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads) kh = k.view( k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1]) weights = torch.einsum("bqnc,bnchw->bqnhw", qh * self.normalize_fact, kh) if mask is not None: weights.masked_fill_(mask.unsqueeze(1).unsqueeze(1), float("-inf")) weights = F.softmax(weights.flatten(2), dim=-1).view_as(weights) weights = self.dropout(weights) return weights class PostProcessSegm(nn.Module): def __init__(self, threshold=0.5): super().__init__() self.threshold = threshold @torch.no_grad() def forward(self, results, outputs, orig_target_sizes, max_target_sizes, return_probs=False, results_mask=None): assert len(orig_target_sizes) == len(max_target_sizes) max_h, max_w = max_target_sizes.max(0)[0].tolist() outputs_masks = outputs["pred_masks"].squeeze(2) outputs_masks = F.interpolate( outputs_masks, size=(max_h, max_w), mode="bilinear", align_corners=False) outputs_masks = outputs_masks.sigmoid().cpu() if not return_probs: outputs_masks = outputs_masks > self.threshold zip_iter = zip(outputs_masks, max_target_sizes, orig_target_sizes) for i, (cur_mask, t, tt) in enumerate(zip_iter): img_h, img_w = t[0], t[1] masks = cur_mask[:, :img_h, :img_w].unsqueeze(1) masks = F.interpolate(masks.float(), size=tuple(tt.tolist()), mode="nearest") if not return_probs: masks = masks.byte() if results_mask is not None: masks = masks[results_mask[i]] results[i]["masks"] = masks return results class PostProcessPanoptic(nn.Module): """This class converts the output of the model to the final panoptic result, in the format expected by the coco panoptic API """ def __init__(self, is_thing_map, threshold=0.85): """ Parameters: is_thing_map: This is a whose keys are the class ids, and the values a boolean indicating whether the class is a thing (True) or a stuff (False) class threshold: confidence threshold: segments with confidence lower than this will be deleted """ super().__init__() self.threshold = threshold self.is_thing_map = is_thing_map def forward(self, outputs, processed_sizes, target_sizes=None): """ This function computes the panoptic prediction from the model's predictions. Parameters: outputs: This is a dict coming directly from the model. See the model doc for the content. processed_sizes: This is a list of tuples (or torch tensors) of sizes of the images that were passed to the model, ie the size after data augmentation but before batching. target_sizes: This is a list of tuples (or torch tensors) corresponding to the requested final size of each prediction. If left to None, it will default to the processed_sizes """ if target_sizes is None: target_sizes = processed_sizes assert len(processed_sizes) == len(target_sizes) out_logits, raw_masks, raw_boxes = \ outputs["pred_logits"], outputs["pred_masks"], outputs["pred_boxes"] assert len(out_logits) == len(raw_masks) == len(target_sizes) preds = [] def to_tuple(tup): if isinstance(tup, tuple): return tup return tuple(tup.cpu().tolist()) for cur_logits, cur_masks, cur_boxes, size, target_size in zip( out_logits, raw_masks, raw_boxes, processed_sizes, target_sizes ): # we filter empty queries and detection below threshold scores, labels = cur_logits.softmax(-1).max(-1) keep = labels.ne(outputs["pred_logits"].shape[-1] - 1) & (scores > self.threshold) cur_scores, cur_classes = cur_logits.softmax(-1).max(-1) cur_scores = cur_scores[keep] cur_classes = cur_classes[keep] cur_masks = cur_masks[keep] cur_masks = interpolate(cur_masks[None], to_tuple(size), mode="bilinear").squeeze(0) cur_boxes = box_ops.box_cxcywh_to_xyxy(cur_boxes[keep]) h, w = cur_masks.shape[-2:] assert len(cur_boxes) == len(cur_classes) # It may be that we have several predicted masks for the same stuff class. # In the following, we track the list of masks ids for each stuff class # (they are merged later on) cur_masks = cur_masks.flatten(1) stuff_equiv_classes = defaultdict(lambda: []) for k, label in enumerate(cur_classes): if not self.is_thing_map[label.item()]: stuff_equiv_classes[label.item()].append(k) def get_ids_area(masks, scores, dedup=False): # This helper function creates the final panoptic segmentation image # It also returns the area of the masks that appears on the image m_id = masks.transpose(0, 1).softmax(-1) if m_id.shape[-1] == 0: # We didn't detect any mask :( m_id = torch.zeros((h, w), dtype=torch.long, device=m_id.device) else: m_id = m_id.argmax(-1).view(h, w) if dedup: # Merge the masks corresponding to the same stuff class for equiv in stuff_equiv_classes.values(): if len(equiv) > 1: for eq_id in equiv: m_id.masked_fill_(m_id.eq(eq_id), equiv[0]) final_h, final_w = to_tuple(target_size) seg_img = Image.fromarray(id2rgb(m_id.view(h, w).cpu().numpy())) seg_img = seg_img.resize(size=(final_w, final_h), resample=Image.NEAREST) np_seg_img = (torch.ByteTensor( torch.ByteStorage.from_buffer(seg_img.tobytes())).view(final_h, final_w, 3).numpy()) m_id = torch.from_numpy(rgb2id(np_seg_img)) area = [] for i in range(len(scores)): area.append(m_id.eq(i).sum().item()) return area, seg_img area, seg_img = get_ids_area(cur_masks, cur_scores, dedup=True) if cur_classes.numel() > 0: # We know filter empty masks as long as we find some while True: filtered_small = torch.as_tensor([ area[i] <= 4 for i, c in enumerate(cur_classes)], dtype=torch.bool, device=keep.device) if filtered_small.any().item(): cur_scores = cur_scores[~filtered_small] cur_classes = cur_classes[~filtered_small] cur_masks = cur_masks[~filtered_small] area, seg_img = get_ids_area(cur_masks, cur_scores) else: break else: cur_classes = torch.ones(1, dtype=torch.long, device=cur_classes.device) segments_info = [] for i, a in enumerate(area): cat = cur_classes[i].item() segments_info.append({ "id": i, "isthing": self.is_thing_map[cat], "category_id": cat, "area": a}) del cur_classes with io.BytesIO() as out: seg_img.save(out, format="PNG") predictions = {"png_string": out.getvalue(), "segments_info": segments_info} preds.append(predictions) return preds ================================================ FILE: src/trackformer/models/detr_tracking.py ================================================ import math import random from contextlib import nullcontext import torch import torch.nn as nn from ..util import box_ops from ..util.misc import NestedTensor, get_rank from .deformable_detr import DeformableDETR from .detr import DETR from .matcher import HungarianMatcher class DETRTrackingBase(nn.Module): def __init__(self, track_query_false_positive_prob: float = 0.0, track_query_false_negative_prob: float = 0.0, matcher: HungarianMatcher = None, backprop_prev_frame=False): self._matcher = matcher self._track_query_false_positive_prob = track_query_false_positive_prob self._track_query_false_negative_prob = track_query_false_negative_prob self._backprop_prev_frame = backprop_prev_frame self._tracking = False def train(self, mode: bool = True): """Sets the module in train mode.""" self._tracking = False return super().train(mode) def tracking(self): """Sets the module in tracking mode.""" self.eval() self._tracking = True def add_track_queries_to_targets(self, targets, prev_indices, prev_out, add_false_pos=True): device = prev_out['pred_boxes'].device # for i, (target, prev_ind) in enumerate(zip(targets, prev_indices)): min_prev_target_ind = min([len(prev_ind[1]) for prev_ind in prev_indices]) num_prev_target_ind = 0 if min_prev_target_ind: num_prev_target_ind = torch.randint(0, min_prev_target_ind + 1, (1,)).item() num_prev_target_ind_for_fps = 0 if num_prev_target_ind: num_prev_target_ind_for_fps = \ torch.randint(int(math.ceil(self._track_query_false_positive_prob * num_prev_target_ind)) + 1, (1,)).item() for i, (target, prev_ind) in enumerate(zip(targets, prev_indices)): prev_out_ind, prev_target_ind = prev_ind # random subset if self._track_query_false_negative_prob: # and len(prev_target_ind): # random_subset_mask = torch.empty(len(prev_target_ind)).uniform_() # random_subset_mask = random_subset_mask.ge( # self._track_query_false_negative_prob) # random_subset_mask = torch.randperm(len(prev_target_ind))[:torch.randint(0, len(prev_target_ind) + 1, (1,))] random_subset_mask = torch.randperm(len(prev_target_ind))[:num_prev_target_ind] # if not len(random_subset_mask): # target['track_query_hs_embeds'] = torch.zeros(0, self.hidden_dim).float().to(device) # target['track_queries_placeholder_mask'] = torch.zeros(self.num_queries).bool().to(device) # target['track_queries_mask'] = torch.zeros(self.num_queries).bool().to(device) # target['track_queries_fal_pos_mask'] = torch.zeros(self.num_queries).bool().to(device) # target['track_query_boxes'] = torch.zeros(0, 4).to(device) # target['track_query_match_ids'] = torch.tensor([]).long().to(device) # continue prev_out_ind = prev_out_ind[random_subset_mask] prev_target_ind = prev_target_ind[random_subset_mask] # detected prev frame tracks prev_track_ids = target['prev_target']['track_ids'][prev_target_ind] # match track ids between frames target_ind_match_matrix = prev_track_ids.unsqueeze(dim=1).eq(target['track_ids']) target_ind_matching = target_ind_match_matrix.any(dim=1) target_ind_matched_idx = target_ind_match_matrix.nonzero()[:, 1] # current frame track ids detected in the prev frame # track_ids = target['track_ids'][target_ind_matched_idx] # index of prev frame detection in current frame box list target['track_query_match_ids'] = target_ind_matched_idx # random false positives if add_false_pos: prev_boxes_matched = prev_out['pred_boxes'][i, prev_out_ind[target_ind_matching]] not_prev_out_ind = torch.arange(prev_out['pred_boxes'].shape[1]) not_prev_out_ind = [ ind.item() for ind in not_prev_out_ind if ind not in prev_out_ind] random_false_out_ind = [] prev_target_ind_for_fps = torch.randperm(num_prev_target_ind)[:num_prev_target_ind_for_fps] # for j, prev_box_matched in enumerate(prev_boxes_matched): # if j not in prev_target_ind_for_fps: # continue for j in prev_target_ind_for_fps: # if random.uniform(0, 1) < self._track_query_false_positive_prob: prev_boxes_unmatched = prev_out['pred_boxes'][i, not_prev_out_ind] # only cxcy # box_dists = prev_box_matched[:2].sub(prev_boxes_unmatched[:, :2]).abs() # box_dists = box_dists.pow(2).sum(dim=-1).sqrt() # box_weights = 1.0 / box_dists.add(1e-8) # prev_box_ious, _ = box_ops.box_iou( # box_ops.box_cxcywh_to_xyxy(prev_box_matched.unsqueeze(dim=0)), # box_ops.box_cxcywh_to_xyxy(prev_boxes_unmatched)) # box_weights = prev_box_ious[0] # dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 ) if len(prev_boxes_matched) > j: prev_box_matched = prev_boxes_matched[j] box_weights = \ prev_box_matched.unsqueeze(dim=0)[:, :2] - \ prev_boxes_unmatched[:, :2] box_weights = box_weights[:, 0] ** 2 + box_weights[:, 0] ** 2 box_weights = torch.sqrt(box_weights) # if box_weights.gt(0.0).any(): # if box_weights.gt(0.0).any(): random_false_out_idx = not_prev_out_ind.pop( torch.multinomial(box_weights.cpu(), 1).item()) else: random_false_out_idx = not_prev_out_ind.pop(torch.randperm(len(not_prev_out_ind))[0]) random_false_out_ind.append(random_false_out_idx) prev_out_ind = torch.tensor(prev_out_ind.tolist() + random_false_out_ind).long() target_ind_matching = torch.cat([ target_ind_matching, torch.tensor([False, ] * len(random_false_out_ind)).bool().to(device) ]) # MSDeformAttn can not deal with empty inputs therefore we # add single false pos to have at least one track query per sample # not_prev_out_ind = torch.tensor([ # ind # for ind in torch.arange(prev_out['pred_boxes'].shape[1]) # if ind not in prev_out_ind]) # false_samples_inds = torch.randperm(not_prev_out_ind.size(0))[:1] # false_samples = not_prev_out_ind[false_samples_inds] # prev_out_ind = torch.cat([prev_out_ind, false_samples]) # target_ind_matching = torch.tensor( # target_ind_matching.tolist() + [False, ]).bool().to(target_ind_matching.device) # track query masks track_queries_mask = torch.ones_like(target_ind_matching).bool() track_queries_fal_pos_mask = torch.zeros_like(target_ind_matching).bool() track_queries_fal_pos_mask[~target_ind_matching] = True # track_queries_match_mask = torch.ones_like(target_ind_matching).float() # matches indices with 1.0 and not matched -1.0 # track_queries_mask[~target_ind_matching] = -1.0 # set prev frame info target['track_query_hs_embeds'] = prev_out['hs_embed'][i, prev_out_ind] target['track_query_boxes'] = prev_out['pred_boxes'][i, prev_out_ind].detach() target['track_queries_mask'] = torch.cat([ track_queries_mask, torch.tensor([False, ] * self.num_queries).to(device) ]).bool() target['track_queries_fal_pos_mask'] = torch.cat([ track_queries_fal_pos_mask, torch.tensor([False, ] * self.num_queries).to(device) ]).bool() # add placeholder track queries to allow for batch sizes > 1 # max_track_query_hs_embeds = max([len(t['track_query_hs_embeds']) for t in targets]) # for i, target in enumerate(targets): # num_add = max_track_query_hs_embeds - len(target['track_query_hs_embeds']) # if not num_add: # target['track_queries_placeholder_mask'] = torch.zeros_like(target['track_queries_mask']).bool() # continue # raise NotImplementedError # target['track_query_hs_embeds'] = torch.cat( # [torch.zeros(num_add, self.hidden_dim).to(device), # target['track_query_hs_embeds'] # ]) # target['track_query_boxes'] = torch.cat( # [torch.zeros(num_add, 4).to(device), # target['track_query_boxes'] # ]) # target['track_queries_mask'] = torch.cat([ # torch.tensor([True, ] * num_add).to(device), # target['track_queries_mask'] # ]).bool() # target['track_queries_fal_pos_mask'] = torch.cat([ # torch.tensor([False, ] * num_add).to(device), # target['track_queries_fal_pos_mask'] # ]).bool() # target['track_queries_placeholder_mask'] = torch.zeros_like(target['track_queries_mask']).bool() # target['track_queries_placeholder_mask'][:num_add] = True def forward(self, samples: NestedTensor, targets: list = None, prev_features=None): if targets is not None and not self._tracking: prev_targets = [target['prev_target'] for target in targets] # if self.training and random.uniform(0, 1) < 0.5: if self.training: # if True: backprop_context = torch.no_grad if self._backprop_prev_frame: backprop_context = nullcontext with backprop_context(): if 'prev_prev_image' in targets[0]: for target, prev_target in zip(targets, prev_targets): prev_target['prev_target'] = target['prev_prev_target'] prev_prev_targets = [target['prev_prev_target'] for target in targets] # PREV PREV prev_prev_out, _, prev_prev_features, _, _ = super().forward([t['prev_prev_image'] for t in targets]) prev_prev_outputs_without_aux = { k: v for k, v in prev_prev_out.items() if 'aux_outputs' not in k} prev_prev_indices = self._matcher(prev_prev_outputs_without_aux, prev_prev_targets) self.add_track_queries_to_targets( prev_targets, prev_prev_indices, prev_prev_out, add_false_pos=False) # PREV prev_out, _, prev_features, _, _ = super().forward( [t['prev_image'] for t in targets], prev_targets, prev_prev_features) else: prev_out, _, prev_features, _, _ = super().forward([t['prev_image'] for t in targets]) # prev_out = {k: v.detach() for k, v in prev_out.items() if torch.is_tensor(v)} prev_outputs_without_aux = { k: v for k, v in prev_out.items() if 'aux_outputs' not in k} prev_indices = self._matcher(prev_outputs_without_aux, prev_targets) self.add_track_queries_to_targets(targets, prev_indices, prev_out) else: # if not training we do not add track queries and evaluate detection performance only. # tracking performance is evaluated by the actual tracking evaluation. for target in targets: device = target['boxes'].device target['track_query_hs_embeds'] = torch.zeros(0, self.hidden_dim).float().to(device) # target['track_queries_placeholder_mask'] = torch.zeros(self.num_queries).bool().to(device) target['track_queries_mask'] = torch.zeros(self.num_queries).bool().to(device) target['track_queries_fal_pos_mask'] = torch.zeros(self.num_queries).bool().to(device) target['track_query_boxes'] = torch.zeros(0, 4).to(device) target['track_query_match_ids'] = torch.tensor([]).long().to(device) out, targets, features, memory, hs = super().forward(samples, targets, prev_features) return out, targets, features, memory, hs # TODO: with meta classes class DETRTracking(DETRTrackingBase, DETR): def __init__(self, tracking_kwargs, detr_kwargs): DETR.__init__(self, **detr_kwargs) DETRTrackingBase.__init__(self, **tracking_kwargs) class DeformableDETRTracking(DETRTrackingBase, DeformableDETR): def __init__(self, tracking_kwargs, detr_kwargs): DeformableDETR.__init__(self, **detr_kwargs) DETRTrackingBase.__init__(self, **tracking_kwargs) ================================================ FILE: src/trackformer/models/matcher.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Modules to compute the matching cost and solve the corresponding LSAP. """ import numpy as np import torch from scipy.optimize import linear_sum_assignment from torch import nn from ..util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou class HungarianMatcher(nn.Module): """This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched (and thus treated as non-objects). """ def __init__(self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1, focal_loss: bool = False, focal_alpha: float = 0.25, focal_gamma: float = 2.0): """Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost """ super().__init__() self.cost_class = cost_class self.cost_bbox = cost_bbox self.cost_giou = cost_giou self.focal_loss = focal_loss self.focal_alpha = focal_alpha self.focal_gamma = focal_gamma assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0" @torch.no_grad() def forward(self, outputs, targets): """ Performs the matching Params: outputs: This is a dict that contains at least these entries: "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing: "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth objects in the target) containing the class labels "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates Returns: A list of size batch_size, containing tuples of (index_i, index_j) where: - index_i is the indices of the selected predictions (in order) - index_j is the indices of the corresponding selected targets (in order) For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes) """ batch_size, num_queries = outputs["pred_logits"].shape[:2] # We flatten to compute the cost matrices in a batch # # [batch_size * num_queries, num_classes] if self.focal_loss: out_prob = outputs["pred_logits"].flatten(0, 1).sigmoid() else: out_prob = outputs["pred_logits"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, 4] out_bbox = outputs["pred_boxes"].flatten(0, 1) # Also concat the target labels and boxes tgt_ids = torch.cat([v["labels"] for v in targets]) tgt_bbox = torch.cat([v["boxes"] for v in targets]) # Compute the classification cost. if self.focal_loss: neg_cost_class = (1 - self.focal_alpha) * (out_prob ** self.focal_gamma) * (-(1 - out_prob + 1e-8).log()) pos_cost_class = self.focal_alpha * ((1 - out_prob) ** self.focal_gamma) * (-(out_prob + 1e-8).log()) cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids] else: # Contrary to the loss, we don't use the NLL, but approximate it in 1 - proba[target class]. # The 1 is a constant that doesn't change the matching, it can be ommitted. cost_class = -out_prob[:, tgt_ids] # Compute the L1 cost between boxes cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1) # Compute the giou cost betwen boxes cost_giou = -generalized_box_iou( box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)) # Final cost matrix cost_matrix = self.cost_bbox * cost_bbox \ + self.cost_class * cost_class \ + self.cost_giou * cost_giou cost_matrix = cost_matrix.view(batch_size, num_queries, -1).cpu() sizes = [len(v["boxes"]) for v in targets] for i, target in enumerate(targets): if 'track_query_match_ids' not in target: continue prop_i = 0 for j in range(cost_matrix.shape[1]): # if target['track_queries_fal_pos_mask'][j] or target['track_queries_placeholder_mask'][j]: if target['track_queries_fal_pos_mask'][j]: # false positive and palceholder track queries should not # be matched to any target cost_matrix[i, j] = np.inf elif target['track_queries_mask'][j]: track_query_id = target['track_query_match_ids'][prop_i] prop_i += 1 cost_matrix[i, j] = np.inf cost_matrix[i, :, track_query_id + sum(sizes[:i])] = np.inf cost_matrix[i, j, track_query_id + sum(sizes[:i])] = -1 indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))] return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices] def build_matcher(args): return HungarianMatcher( cost_class=args.set_cost_class, cost_bbox=args.set_cost_bbox, cost_giou=args.set_cost_giou, focal_loss=args.focal_loss, focal_alpha=args.focal_alpha, focal_gamma=args.focal_gamma,) ================================================ FILE: src/trackformer/models/ops/.gitignore ================================================ build dist *egg-info *.linux* ================================================ FILE: src/trackformer/models/ops/functions/__init__.py ================================================ from .ms_deform_attn_func import MSDeformAttnFunction, ms_deform_attn_core_pytorch, ms_deform_attn_core_pytorch_mot ================================================ FILE: src/trackformer/models/ops/functions/ms_deform_attn_func.py ================================================ #!/usr/bin/env python from __future__ import absolute_import from __future__ import print_function from __future__ import division import torch import torch.nn.functional as F from torch.autograd import Function from torch.autograd.function import once_differentiable import MultiScaleDeformableAttention as MSDA class MSDeformAttnFunction(Function): @staticmethod def forward(ctx, value, value_spatial_shapes, sampling_locations, attention_weights, im2col_step): ctx.im2col_step = im2col_step output = MSDA.ms_deform_attn_forward( value, value_spatial_shapes, sampling_locations, attention_weights, ctx.im2col_step) ctx.save_for_backward(value, value_spatial_shapes, sampling_locations, attention_weights) return output @staticmethod @once_differentiable def backward(ctx, grad_output): value, value_spatial_shapes, sampling_locations, attention_weights = ctx.saved_tensors grad_value, grad_sampling_loc, grad_attn_weight = \ MSDA.ms_deform_attn_backward( value, value_spatial_shapes, sampling_locations, attention_weights, grad_output, ctx.im2col_step) return grad_value, None, grad_sampling_loc, grad_attn_weight, None def ms_deform_attn_core_pytorch(value, value_spatial_shapes, sampling_locations, attention_weights): # for debug and test only, # need to use cuda version instead N_, S_, M_, D_ = value.shape _, Lq_, M_, L_, P_, _ = sampling_locations.shape value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1) sampling_grids = 2 * sampling_locations - 1 sampling_value_list = [] for lid_, (H_, W_) in enumerate(value_spatial_shapes): # N_, H_*W_, M_, D_ -> N_, H_*W_, M_*D_ -> N_, M_*D_, H_*W_ -> N_*M_, D_, H_, W_ value_l_ = value_list[lid_].flatten(2).transpose(1, 2).reshape(N_*M_, D_, H_, W_) # N_, Lq_, M_, P_, 2 -> N_, M_, Lq_, P_, 2 -> N_*M_, Lq_, P_, 2 sampling_grid_l_ = sampling_grids[:, :, :, lid_].transpose(1, 2).flatten(0, 1) # N_*M_, D_, Lq_, P_ sampling_value_l_ = F.grid_sample(value_l_, sampling_grid_l_, mode='bilinear', padding_mode='zeros', align_corners=False) sampling_value_list.append(sampling_value_l_) # (N_, Lq_, M_, L_, P_) -> (N_, M_, Lq_, L_, P_) -> (N_, M_, 1, Lq_, L_*P_) attention_weights = attention_weights.transpose(1, 2).reshape(N_*M_, 1, Lq_, L_*P_) output = (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights).sum(-1).view(N_, M_*D_, Lq_) return output.transpose(1, 2).contiguous() def ms_deform_attn_core_pytorch_mot(query, value, value_spatial_shapes, sampling_locations, key_proj, attention_weights=None): # for debug and test only, # need to use cuda version instead N_, S_, M_, D_ = value.shape _, Lq_, M_, L_, P_, _ = sampling_locations.shape value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1) sampling_grids = 2 * sampling_locations - 1 sampling_value_list = [] for lid_, (H_, W_) in enumerate(value_spatial_shapes): # N_, H_*W_, M_, D_ -> N_, H_*W_, M_*D_ -> N_, M_*D_, H_*W_ -> N_*M_, D_, H_, W_ value_l_ = value_list[lid_].flatten(2).transpose(1, 2).reshape(N_*M_, D_, H_, W_) # N_, Lq_, M_, P_, 2 -> N_, M_, Lq_, P_, 2 -> N_*M_, Lq_, P_, 2 sampling_grid_l_ = sampling_grids[:, :, :, lid_].transpose(1, 2).flatten(0, 1) # N_*M_, D_, Lq_, P_ sampling_value_l_ = F.grid_sample(value_l_, sampling_grid_l_, mode='bilinear', padding_mode='zeros', align_corners=False) sampling_value_list.append(sampling_value_l_) # (N_, Lq_, M_, L_, P_) -> (N_, M_, Lq_, L_, P_) -> (N_, M_, 1, Lq_, L_*P_) q = query.transpose(1, 2).reshape(N_*M_, D_, Lq_, 1) v = torch.stack(sampling_value_list, dim=-2).flatten(-2) # (N_*M_, D_, Lq_, L_*P_) k = key_proj(v.reshape(N_, M_*D_, Lq_, L_*P_).permute(0, 2, 3, 1)).permute(0, 3, 1, 2).reshape(N_*M_, D_, Lq_, L_*P_) sim = (q * k).sum(1).reshape(N_*M_, 1, Lq_, L_*P_) attention_weights = F.softmax(sim, -1) output = (v * attention_weights).sum(-1).view(N_, M_*D_, Lq_) return output.transpose(1, 2).contiguous() ================================================ FILE: src/trackformer/models/ops/make.sh ================================================ python setup.py build install ================================================ FILE: src/trackformer/models/ops/modules/__init__.py ================================================ from .ms_deform_attn import MSDeformAttn ================================================ FILE: src/trackformer/models/ops/modules/ms_deform_attn.py ================================================ #!/usr/bin/env python from __future__ import absolute_import from __future__ import print_function from __future__ import division import torch from torch import nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_, constant_ from ..functions import MSDeformAttnFunction, ms_deform_attn_core_pytorch from ..functions import ms_deform_attn_core_pytorch_mot class MSDeformAttn(nn.Module): def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4, im2col_step=64): super().__init__() assert d_model % n_heads == 0 self.im2col_step = im2col_step self.d_model = d_model self.n_levels = n_levels self.n_heads = n_heads self.n_points = n_points self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2) self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points) self.value_proj = nn.Linear(d_model, d_model) self.output_proj = nn.Linear(d_model, d_model) self._reset_parameters() def _reset_parameters(self): constant_(self.sampling_offsets.weight.data, 0.) grid_init = torch.tensor([-1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1], dtype=torch.float32) \ .view(self.n_heads, 1, 1, 2).repeat(1, self.n_levels, self.n_points, 1) for i in range(self.n_points): grid_init[:, :, i, :] *= i + 1 with torch.no_grad(): self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1)) constant_(self.attention_weights.weight.data, 0.) constant_(self.attention_weights.bias.data, 0.) xavier_uniform_(self.value_proj.weight.data) constant_(self.value_proj.bias.data, 0.) xavier_uniform_(self.output_proj.weight.data) constant_(self.output_proj.bias.data, 0.) def forward(self, query, reference_points, input_flatten, input_spatial_shapes, input_padding_mask=None, query_attn_mask=None): """ :param query (N, Length_{query}, C) :param reference_points (N, Length_{query}, n_levels, 2), range in [0, 1], top-left (0,0), bottom-right (1, 1), including padding area or (N, Length_{query}, n_levels, 4), add additional (w, h) to form reference boxes :param input_flatten (N, \sum_{l=0}^{L-1} H_l \cdot W_l, C) :param input_spatial_shapes (n_levels, 2), [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})] :param input_padding_mask (N, \sum_{l=0}^{L-1} H_l \cdot W_l), True for padding elements, False for non-padding elements :return output (N, Length_{query}, C) """ N, Len_q, _ = query.shape N, Len_in, _ = input_flatten.shape assert (input_spatial_shapes[:, 0] * input_spatial_shapes[:, 1]).sum() == Len_in value = self.value_proj(input_flatten) if input_padding_mask is not None: value = value.masked_fill(input_padding_mask[..., None], float(0)) value = value.view(N, Len_in, self.n_heads, self.d_model // self.n_heads) sampling_offsets = self.sampling_offsets(query).view(N, Len_q, self.n_heads, self.n_levels, self.n_points, 2) attention_weights = self.attention_weights(query).view(N, Len_q, self.n_heads, self.n_levels * self.n_points) attention_weights = F.softmax(attention_weights, -1).view(N, Len_q, self.n_heads, self.n_levels, self.n_points) if query_attn_mask is not None: attention_weights = attention_weights.masked_fill(query_attn_mask[..., None, None, None], float(0)) # N, Len_q, n_heads, n_levels, n_points, 2 if reference_points.shape[-1] == 2: sampling_locations = reference_points[:, :, None, :, None, :] \ + sampling_offsets / input_spatial_shapes[None, None, None, :, None, :] elif reference_points.shape[-1] == 4: sampling_locations = reference_points[:, :, None, :, None, :2] \ + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5 else: raise ValueError( 'Last dim of reference_points must be 2 or 4, but get {} instead.'.format(reference_points.shape[-1])) output = MSDeformAttnFunction.apply( value, input_spatial_shapes, sampling_locations, attention_weights, self.im2col_step) output = self.output_proj(output) return output ================================================ FILE: src/trackformer/models/ops/setup.py ================================================ #!/usr/bin/env python import os import glob import torch from torch.utils.cpp_extension import CUDA_HOME from torch.utils.cpp_extension import CppExtension from torch.utils.cpp_extension import CUDAExtension from setuptools import find_packages from setuptools import setup requirements = ["torch", "torchvision"] def get_extensions(): this_dir = os.path.dirname(os.path.abspath(__file__)) extensions_dir = os.path.join(this_dir, "src") main_file = glob.glob(os.path.join(extensions_dir, "*.cpp")) source_cpu = glob.glob(os.path.join(extensions_dir, "cpu", "*.cpp")) source_cuda = glob.glob(os.path.join(extensions_dir, "cuda", "*.cu")) sources = main_file + source_cpu extension = CppExtension extra_compile_args = {"cxx": []} define_macros = [] if torch.cuda.is_available() and CUDA_HOME is not None: extension = CUDAExtension sources += source_cuda define_macros += [("WITH_CUDA", None)] extra_compile_args["nvcc"] = [ "-DCUDA_HAS_FP16=1", "-D__CUDA_NO_HALF_OPERATORS__", "-D__CUDA_NO_HALF_CONVERSIONS__", "-D__CUDA_NO_HALF2_OPERATORS__", ] else: raise NotImplementedError('Cuda is not available') sources = [os.path.join(extensions_dir, s) for s in sources] include_dirs = [extensions_dir] ext_modules = [ extension( "MultiScaleDeformableAttention", sources, include_dirs=include_dirs, define_macros=define_macros, extra_compile_args=extra_compile_args, ) ] return ext_modules setup( name="MultiScaleDeformableAttention", version="1.0", author="Weijie Su", url="xxx", description="Multi-Scale Deformable Attention Module in Deformable DETR", packages=find_packages(exclude=("configs", "tests",)), # install_requires=requirements, ext_modules=get_extensions(), cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension}, ) ================================================ FILE: src/trackformer/models/ops/src/cpu/ms_deform_attn_cpu.cpp ================================================ #include #include #include at::Tensor ms_deform_attn_cpu_forward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const int im2col_step) { AT_ERROR("Not implement on cpu"); } std::vector ms_deform_attn_cpu_backward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const at::Tensor &grad_output, const int im2col_step) { AT_ERROR("Not implement on cpu"); } ================================================ FILE: src/trackformer/models/ops/src/cpu/ms_deform_attn_cpu.h ================================================ #pragma once #include at::Tensor ms_deform_attn_cpu_forward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const int im2col_step); std::vector ms_deform_attn_cpu_backward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const at::Tensor &grad_output, const int im2col_step); ================================================ FILE: src/trackformer/models/ops/src/cuda/ms_deform_attn_cuda.cu ================================================ #include #include "cuda/ms_deform_im2col_cuda.cuh" #include #include #include #include // #include // #include // #include // extern THCState *state; // author: Charles Shang // https://github.com/torch/cunn/blob/master/lib/THCUNN/generic/SpatialConvolutionMM.cu at::Tensor ms_deform_attn_cuda_forward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const int im2col_step) // value: N_, S_, M_, D_ // spatial_shapes: L_, 2 // sampling_loc: N_, Lq_, M_, L_, P_, 2 { AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous"); AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor"); AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor"); AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor"); AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor"); const int batch = value.size(0); const int spatial_size = value.size(1); const int num_heads = value.size(2); const int channels = value.size(3); const int num_levels = spatial_shapes.size(0); const int num_query = sampling_loc.size(1); const int num_point = sampling_loc.size(4); const int im2col_step_ = std::min(batch, im2col_step); AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_); auto output = at::empty({batch, num_query, num_heads, channels}, value.options()); auto level_start_index = at::zeros({num_levels}, spatial_shapes.options()); for (int lvl = 1; lvl < num_levels; ++lvl) { auto shape_prev = spatial_shapes.select(0, lvl-1); auto size_prev = at::mul(shape_prev.select(0, 0), shape_prev.select(0, 1)); level_start_index.select(0, lvl) = at::add(level_start_index.select(0, lvl-1), size_prev); } // define alias for easy use const int batch_n = im2col_step_; auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels}); auto per_value_size = spatial_size * num_heads * channels; auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2; auto per_attn_weight_size = num_query * num_heads * num_levels * num_point; for (int n = 0; n < batch/im2col_step_; ++n) { auto columns = at::empty({num_levels*num_point, batch_n, num_query, num_heads, channels}, value.options()); AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] { ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(), value.data() + n * im2col_step_ * per_value_size, spatial_shapes.data(), level_start_index.data(), sampling_loc.data() + n * im2col_step_ * per_sample_loc_size, attn_weight.data() + n * im2col_step_ * per_attn_weight_size, batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point, columns.data()); })); output_n.select(0, n) = at::sum(columns, 0); } output = output.view({batch, num_query, num_heads*channels}); return output; } std::vector ms_deform_attn_cuda_backward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const at::Tensor &grad_output, const int im2col_step) { AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous"); AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor"); AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor"); AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor"); AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor"); const int batch = value.size(0); const int spatial_size = value.size(1); const int num_heads = value.size(2); const int channels = value.size(3); const int num_levels = spatial_shapes.size(0); const int num_query = sampling_loc.size(1); const int num_point = sampling_loc.size(4); const int im2col_step_ = std::min(batch, im2col_step); AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_); auto grad_value = at::zeros_like(value); auto grad_sampling_loc = at::zeros_like(sampling_loc); auto grad_attn_weight = at::zeros_like(attn_weight); auto level_start_index = at::zeros({num_levels}, spatial_shapes.options()); for (int lvl = 1; lvl < num_levels; ++lvl) { auto shape_prev = spatial_shapes.select(0, lvl-1); auto size_prev = at::mul(shape_prev.select(0, 0), shape_prev.select(0, 1)); level_start_index.select(0, lvl) = at::add(level_start_index.select(0, lvl-1), size_prev); } const int batch_n = im2col_step_; auto per_value_size = spatial_size * num_heads * channels; auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2; auto per_attn_weight_size = num_query * num_heads * num_levels * num_point; auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels}); for (int n = 0; n < batch/im2col_step_; ++n) { auto grad_output_g = grad_output_n.select(0, n); AT_DISPATCH_FLOATING_TYPES(value.type(), "deform_conv_backward_cuda", ([&] { // gradient w.r.t. sampling location & attention weight ms_deformable_col2im_coord_cuda(at::cuda::getCurrentCUDAStream(), grad_output_g.data(), value.data() + n * im2col_step_ * per_value_size, spatial_shapes.data(), level_start_index.data(), sampling_loc.data() + n * im2col_step_ * per_sample_loc_size, attn_weight.data() + n * im2col_step_ * per_attn_weight_size, batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point, grad_sampling_loc.data() + n * im2col_step_ * per_sample_loc_size, grad_attn_weight.data() + n * im2col_step_ * per_attn_weight_size); // gradient w.r.t. value ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(), grad_output_g.data(), spatial_shapes.data(), level_start_index.data(), sampling_loc.data() + n * im2col_step_ * per_sample_loc_size, attn_weight.data() + n * im2col_step_ * per_attn_weight_size, batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point, grad_value.data() + n * im2col_step_ * per_value_size); })); } return { grad_value, grad_sampling_loc, grad_attn_weight }; } ================================================ FILE: src/trackformer/models/ops/src/cuda/ms_deform_attn_cuda.h ================================================ #pragma once #include at::Tensor ms_deform_attn_cuda_forward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const int im2col_step); std::vector ms_deform_attn_cuda_backward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const at::Tensor &grad_output, const int im2col_step); ================================================ FILE: src/trackformer/models/ops/src/cuda/ms_deform_im2col_cuda.cuh ================================================ #include #include #include #include #include // #include #include // #include #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) const int CUDA_NUM_THREADS = 1024; inline int GET_BLOCKS(const int N) { return (N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS; } template __device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t *bottom_data, const int height, const int width, const int nheads, const int channels, scalar_t h, scalar_t w, const int m, const int c) { int h_low = floor(h); int w_low = floor(w); int h_high = h_low + 1; int w_high = w_low + 1; scalar_t lh = h - h_low; scalar_t lw = w - w_low; scalar_t hh = 1 - lh, hw = 1 - lw; scalar_t v1 = 0; if (h_low >= 0 && w_low >= 0) { int ptr1 = h_low * width * nheads * channels + w_low * nheads * channels + m * channels + c; v1 = bottom_data[ptr1]; } scalar_t v2 = 0; if (h_low >= 0 && w_high <= width - 1) { int ptr2 = h_low * width * nheads * channels + w_high * nheads * channels + m * channels + c; v2 = bottom_data[ptr2]; } scalar_t v3 = 0; if (h_high <= height - 1 && w_low >= 0) { int ptr3 = h_high * width * nheads * channels + w_low * nheads * channels + m * channels + c; v3 = bottom_data[ptr3]; } scalar_t v4 = 0; if (h_high <= height - 1 && w_high <= width - 1) { int ptr4 = h_high * width * nheads * channels + w_high * nheads * channels + m * channels + c; v4 = bottom_data[ptr4]; } scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw; scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); return val; } template __device__ scalar_t ms_deform_attn_get_gradient_weight(scalar_t h, scalar_t w, const int gh, const int gw, const int height, const int width) { if (h <= -1 || h >= height || w <= -1 || w >= width) { //empty return 0; } int h_low = floor(h); int w_low = floor(w); int h_high = h_low + 1; int w_high = w_low + 1; scalar_t weight = 0; if (gh == h_low && gw == w_low) weight = (gh + 1 - h) * (gw + 1 - w); if (gh == h_low && gw == w_high) weight = (gh + 1 - h) * (w + 1 - gw); if (gh == h_high && gw == w_low) weight = (h + 1 - gh) * (gw + 1 - w); if (gh == h_high && gw == w_high) weight = (h + 1 - gh) * (w + 1 - gw); return weight; } template __device__ scalar_t ms_deform_attn_get_coordinate_weight(scalar_t h, scalar_t w, const int m, const int c, const int height, const int width, const int nheads, const int channels, const scalar_t *bottom_data, const int bp_dir) { if (h <= -1 || h >= height || w <= -1 || w >= width) { //empty return 0; } int h_low = floor(h); int w_low = floor(w); int h_high = h_low + 1; int w_high = w_low + 1; scalar_t weight = 0; scalar_t v1 = 0; if (h_low >= 0 && w_low >= 0) { int ptr1 = h_low * width * nheads * channels + w_low * nheads * channels + m * channels + c; v1 = bottom_data[ptr1]; } scalar_t v2 = 0; if (h_low >= 0 && w_high <= width - 1) { int ptr2 = h_low * width * nheads * channels + w_high * nheads * channels + m * channels + c; v2 = bottom_data[ptr2]; } scalar_t v3 = 0; if (h_high <= height - 1 && w_low >= 0) { int ptr3 = h_high * width * nheads * channels + w_low * nheads * channels + m * channels + c; v3 = bottom_data[ptr3]; } scalar_t v4 = 0; if (h_high <= height - 1 && w_high <= width - 1) { int ptr4 = h_high * width * nheads * channels + w_high * nheads * channels + m * channels + c; v4 = bottom_data[ptr4]; } if (bp_dir == 1) { if (h_low >= 0 && w_low >= 0) weight += -1 * (w_low + 1 - w) * v1; if (h_low >= 0 && w_high <= width - 1) weight += -1 * (w - w_low) * v2; if (h_high <= height - 1 && w_low >= 0) weight += (w_low + 1 - w) * v3; if (h_high <= height - 1 && w_high <= width - 1) weight += (w - w_low) * v4; } else if (bp_dir == 0) { if (h_low >= 0 && w_low >= 0) weight += -1 * (h_low + 1 - h) * v1; if (h_low >= 0 && w_high <= width - 1) weight += (h_low + 1 - h) * v2; if (h_high <= height - 1 && w_low >= 0) weight += -1 * (h - h_low) * v3; if (h_high <= height - 1 && w_high <= width - 1) weight += (h - h_low) * v4; } return weight; } template __global__ void ms_deformable_im2col_gpu_kernel(const int n, const scalar_t *data_value, const int64_t *data_spatial_shapes, const int64_t *data_level_start_index, const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight, const int batch_size, const int spatial_size, const int num_heads, const int channels, const int num_levels, const int num_query, const int num_point, scalar_t *data_col) { // launch batch_size * num_levels * num_query * num_point * channels cores // data_value: batch_size, spatial_size, num_heads, channels // data_sampling_loc: batch_size, num_query, num_heads, num_levels, num_point, 2 // data_attn_weight: batch_size, num_query, num_heads, num_levels, num_point // data_col: num_levels*num_point, batch_size, num_query, num_heads, channels CUDA_KERNEL_LOOP(index, n) { // index index of output matrix const int c_col = index % channels; const int p_col = (index / channels) % num_point; const int q_col = (index / channels / num_point) % num_query; const int l_col = (index / channels / num_point / num_query) % num_levels; const int b_col = index / channels / num_point / num_query / num_levels; const int level_start_id = data_level_start_index[l_col]; const int spatial_h = data_spatial_shapes[l_col * 2]; const int spatial_w = data_spatial_shapes[l_col * 2 + 1]; // num_heads, channels scalar_t *data_col_ptr = data_col + ( c_col + channels * 0 + channels * num_heads * q_col + channels * num_heads * num_query * b_col + channels * num_heads * num_query * batch_size * p_col + channels * num_heads * num_query * batch_size * num_point * l_col); // spatial_h, spatial_w, num_heads, channels const scalar_t *data_value_ptr = data_value + (b_col * spatial_size * num_heads * channels + level_start_id * num_heads * channels); // num_heads, num_levels, num_point, 2 const scalar_t *data_sampling_loc_ptr = data_sampling_loc + ( b_col * num_query * num_heads * num_levels * num_point * 2 + q_col * num_heads * num_levels * num_point * 2); // num_heads, num_levels, num_point const scalar_t *data_attn_weight_ptr = data_attn_weight + ( b_col * num_query * num_heads * num_levels * num_point + q_col * num_heads * num_levels * num_point); for (int i = 0; i < num_heads; ++i) { const int data_loc_h_ptr = i * num_levels * num_point * 2 + l_col * num_point * 2 + p_col * 2 + 1; const int data_loc_w_ptr = i * num_levels * num_point * 2 + l_col * num_point * 2 + p_col * 2; const int data_weight_ptr = i * num_levels * num_point + l_col * num_point + p_col; const scalar_t loc_h = data_sampling_loc_ptr[data_loc_h_ptr]; const scalar_t loc_w = data_sampling_loc_ptr[data_loc_w_ptr]; const scalar_t weight = data_attn_weight_ptr[data_weight_ptr]; scalar_t val = static_cast(0); const scalar_t h_im = loc_h * spatial_h - 0.5; const scalar_t w_im = loc_w * spatial_w - 0.5; if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) { val = ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, i, c_col); } *data_col_ptr = val * weight; data_col_ptr += channels; } } } template __global__ void ms_deformable_col2im_gpu_kernel(const int n, const scalar_t *data_col, const int64_t *data_spatial_shapes, const int64_t *data_level_start_index, const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight, const int batch_size, const int spatial_size, const int num_heads, const int channels, const int num_levels, const int num_query, const int num_point, scalar_t *grad_value) { // launch batch_size * num_levels * num_query * num_point * num_heads * channels cores // grad_value: batch_size, spatial_size, num_heads, channels // data_sampling_loc: batch_size, num_query, num_heads, num_levels, num_point, 2 // data_attn_weight: batch_size, num_query, num_heads, num_levels, num_point // data_col: batch_size, num_query, num_heads, channels CUDA_KERNEL_LOOP(index, n) { const int c_col = index % channels; const int m_col = (index / channels) % num_heads; const int p_col = (index / channels / num_heads) % num_point; const int q_col = (index / channels / num_heads / num_point) % num_query; const int l_col = (index / channels / num_heads / num_point / num_query) % num_levels; const int b_col = index / channels / num_heads / num_point / num_query / num_levels; const int level_start_id = data_level_start_index[l_col]; const int spatial_h = data_spatial_shapes[l_col * 2]; const int spatial_w = data_spatial_shapes[l_col * 2 + 1]; const scalar_t col = data_col[ c_col + channels * m_col + channels * num_heads * q_col + channels * num_heads * num_query * b_col]; int sampling_ptr = b_col * num_query * num_heads * num_levels * num_point + q_col * num_heads * num_levels * num_point + m_col * num_levels * num_point + l_col * num_point + p_col; const scalar_t sampling_x = data_sampling_loc[2 * sampling_ptr] * spatial_w - 0.5; const scalar_t sampling_y = data_sampling_loc[2 * sampling_ptr + 1] * spatial_h - 0.5; const scalar_t attn_weight = data_attn_weight[sampling_ptr]; const scalar_t cur_top_grad = col * attn_weight; const int cur_h = (int)sampling_y; const int cur_w = (int)sampling_x; for (int dy = -2; dy <= 2; dy++) { for (int dx = -2; dx <= 2; dx++) { if (cur_h + dy >= 0 && cur_h + dy < spatial_h && cur_w + dx >= 0 && cur_w + dx < spatial_w && abs(sampling_y - (cur_h + dy)) < 1 && abs(sampling_x - (cur_w + dx)) < 1) { int cur_bottom_grad_pos = b_col * spatial_size * num_heads * channels + (level_start_id + (cur_h+dy)*spatial_w + (cur_w+dx)) * num_heads * channels + m_col * channels + c_col; scalar_t weight = ms_deform_attn_get_gradient_weight(sampling_y, sampling_x, cur_h + dy, cur_w + dx, spatial_h, spatial_w); atomicAdd(grad_value + cur_bottom_grad_pos, weight * cur_top_grad); } } } } } template __global__ void ms_deformable_col2im_coord_gpu_kernel(const int n, const scalar_t *data_col, const scalar_t *data_value, const int64_t *data_spatial_shapes, const int64_t *data_level_start_index, const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight, const int batch_size, const int spatial_size, const int num_heads, const int channels, const int num_levels, const int num_query, const int num_point, scalar_t *grad_sampling_loc, scalar_t *grad_attn_weight) { // sampling_loc: batch_size, num_query, num_heads, num_levels, num_point, 2 // attn_weight: batch_size, num_query, num_heads, num_levels, num_point // column: batch_size, num_query, num_heads, channels // value: batch_size, spatial_size, num_heads, channels // num_kernels = batch_size * num_query * num_heads * num_levels * num_point * 2 CUDA_KERNEL_LOOP(index, n) { scalar_t val = 0, wval = 0; const int loc_c = index % 2; const int k = (index / 2) % num_point; const int l = (index / 2 / num_point) % num_levels; const int m = (index / 2 / num_point / num_levels) % num_heads; const int q = (index / 2 / num_point / num_levels / num_heads) % num_query; const int b = index / 2 / num_point / num_levels / num_heads / num_query; const int level_start_id = data_level_start_index[l]; const int spatial_h = data_spatial_shapes[l * 2]; const int spatial_w = data_spatial_shapes[l * 2 + 1]; const scalar_t *data_col_ptr = data_col +( m * channels + q * channels * num_heads + b * channels * num_heads * num_query); const scalar_t *data_value_ptr = data_value + ( 0 * channels + level_start_id * channels * num_heads + b * channels * num_heads * spatial_size); scalar_t sampling_x = data_sampling_loc[(index / 2) * 2] * spatial_w - 0.5; scalar_t sampling_y = data_sampling_loc[(index / 2) * 2 + 1] * spatial_h - 0.5; const scalar_t attn_weight = data_attn_weight[index / 2]; for (int col_c = 0; col_c < channels; col_c += 1) { const scalar_t col = data_col_ptr[col_c]; if (sampling_x <= -1 || sampling_y <= -1 || sampling_x >= spatial_w || sampling_y >= spatial_h) { sampling_x = sampling_y = -2; } else { wval += col * ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, sampling_y, sampling_x, m, col_c); } const scalar_t weight = ms_deform_attn_get_coordinate_weight( sampling_y, sampling_x, m, col_c, spatial_h, spatial_w, num_heads, channels, data_value_ptr, loc_c); val += weight * col * attn_weight; } if (loc_c == 0) val *= spatial_w; else if (loc_c == 1) val *= spatial_h; grad_sampling_loc[index] = val; if (loc_c % 2 == 0) grad_attn_weight[index / 2] = wval; } } template void ms_deformable_im2col_cuda(cudaStream_t stream, const scalar_t* data_value, const int64_t* data_spatial_shapes, const int64_t* data_level_start_index, const scalar_t* data_sampling_loc, const scalar_t* data_attn_weight, const int batch_size, const int spatial_size, const int num_heads, const int channels, const int num_levels, const int num_query, const int num_point, scalar_t* data_col) { // num_axes should be smaller than block size const int num_kernels = batch_size * num_levels * num_query * num_point * channels; ms_deformable_im2col_gpu_kernel <<>>( num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight, batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err)); } } template void ms_deformable_col2im_cuda(cudaStream_t stream, const scalar_t* data_col, const int64_t *data_spatial_shapes, const int64_t *data_level_start_index, const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight, const int batch_size, const int spatial_size, const int num_heads, const int channels, const int num_levels, const int num_query, const int num_point, scalar_t* grad_value) { const int num_kernels = batch_size * num_levels * num_query * num_point * num_heads * channels; ms_deformable_col2im_gpu_kernel <<>>( num_kernels, data_col, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight, batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, grad_value); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err)); } } template void ms_deformable_col2im_coord_cuda(cudaStream_t stream, const scalar_t* data_col, const scalar_t *data_value, const int64_t *data_spatial_shapes, const int64_t *data_level_start_index, const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight, const int batch_size, const int spatial_size, const int num_heads, const int channels, const int num_levels, const int num_query, const int num_point, scalar_t *grad_sampling_loc, scalar_t *grad_attn_weight) { // data_sampling_loc: batch_size, num_query, num_heads, num_levels, num_point, 2 // data_attn_weight: batch_size, num_query, num_heads, num_levels, num_point const int num_kernels = batch_size * num_query * num_heads * num_levels * num_point * 2; ms_deformable_col2im_coord_gpu_kernel <<>>(num_kernels, data_col, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight, batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, grad_sampling_loc, grad_attn_weight); cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { printf("error in ms_deformable_col2im_coord_cuda: %s\n", cudaGetErrorString(err)); } } ================================================ FILE: src/trackformer/models/ops/src/ms_deform_attn.h ================================================ #pragma once #include "cpu/ms_deform_attn_cpu.h" #ifdef WITH_CUDA #include "cuda/ms_deform_attn_cuda.h" #endif at::Tensor ms_deform_attn_forward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const int im2col_step) { if (value.type().is_cuda()) { #ifdef WITH_CUDA return ms_deform_attn_cuda_forward( value, spatial_shapes, sampling_loc, attn_weight, im2col_step); #else AT_ERROR("Not compiled with GPU support"); #endif } AT_ERROR("Not implemented on the CPU"); } std::vector ms_deform_attn_backward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const at::Tensor &grad_output, const int im2col_step) { if (value.type().is_cuda()) { #ifdef WITH_CUDA return ms_deform_attn_cuda_backward( value, spatial_shapes, sampling_loc, attn_weight, grad_output, im2col_step); #else AT_ERROR("Not compiled with GPU support"); #endif } AT_ERROR("Not implemented on the CPU"); } ================================================ FILE: src/trackformer/models/ops/src/vision.cpp ================================================ #include "ms_deform_attn.h" PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("ms_deform_attn_forward", &ms_deform_attn_forward, "ms_deform_attn_forward"); m.def("ms_deform_attn_backward", &ms_deform_attn_backward, "ms_deform_attn_backward"); } ================================================ FILE: src/trackformer/models/ops/test.py ================================================ #!/usr/bin/env python from __future__ import absolute_import from __future__ import print_function from __future__ import division import time import torch import torch.nn as nn from torch.autograd import gradcheck from functions.ms_deform_attn_func import MSDeformAttnFunction, ms_deform_attn_core_pytorch N, M, D = 2, 2, 4 Lq, L, P = 3, 3, 2 shapes = torch.as_tensor([(8, 8), (4, 4), (2, 2)], dtype=torch.long).cuda() S = sum([(H*W).item() for H, W in shapes]) torch.manual_seed(3) def check_forward_equal_with_pytorch(): value = torch.rand(N, S, M, D).cuda() * 0.01 sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() attention_weights = torch.rand(N, Lq, M, L, P).cuda() + 1e-5 attention_weights /= attention_weights.sum(-1, keepdim=True).sum(-2, keepdim=True) im2col_step = 2 output_pytorch = ms_deform_attn_core_pytorch(value, shapes, sampling_locations, attention_weights) output_cuda = MSDeformAttnFunction.apply(value, shapes, sampling_locations, attention_weights, im2col_step) fwdok = torch.allclose(output_cuda, output_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (output_cuda - output_pytorch).abs().max() max_rel_err = ((output_cuda - output_pytorch).abs() / output_pytorch.abs()).max() print(f'* {fwdok} check_forward_equal_with_pytorch: max_abs_err {max_abs_err:.2e} max_rel_err {max_rel_err:.2e}') def check_backward_equal_with_pytorch(): value = torch.rand(N, S, M, D).cuda() * 0.01 sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() attention_weights = torch.rand(N, Lq, M, L, P).cuda() + 1e-5 attention_weights /= attention_weights.sum(-1, keepdim=True).sum(-2, keepdim=True) im2col_step = 2 value.requires_grad = True sampling_locations.requires_grad = True attention_weights.requires_grad = True output_pytorch = ms_deform_attn_core_pytorch(value, shapes, sampling_locations, attention_weights) output_cuda = MSDeformAttnFunction.apply(value, shapes, sampling_locations, attention_weights, im2col_step) loss_pytorch = output_pytorch.abs().sum() loss_cuda = output_cuda.abs().sum() grad_value_pytorch = torch.autograd.grad(loss_pytorch, value, retain_graph=True)[0] grad_value_cuda = torch.autograd.grad(loss_cuda, value, retain_graph=True)[0] bwdok = torch.allclose(grad_value_cuda, grad_value_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (grad_value_cuda - grad_value_pytorch).abs().max() zero_grad_mask = grad_value_pytorch == 0 max_rel_err = ((grad_value_cuda - grad_value_pytorch).abs() / grad_value_pytorch.abs())[~zero_grad_mask].max() if zero_grad_mask.sum() == 0: max_abs_err_0 = 0 else: max_abs_err_0 = (grad_value_cuda - grad_value_pytorch).abs()[zero_grad_mask].max() print(f'* {bwdok} check_backward_equal_with_pytorch - input1: ' f'max_abs_err {max_abs_err:.2e} ' f'max_rel_err {max_rel_err:.2e} ' f'max_abs_err_0 {max_abs_err_0:.2e}') grad_sampling_loc_pytorch = torch.autograd.grad(loss_pytorch, sampling_locations, retain_graph=True)[0] grad_sampling_loc_cuda = torch.autograd.grad(loss_cuda, sampling_locations, retain_graph=True)[0] bwdok = torch.allclose(grad_sampling_loc_cuda, grad_sampling_loc_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (grad_sampling_loc_cuda - grad_sampling_loc_pytorch).abs().max() zero_grad_mask = grad_sampling_loc_pytorch == 0 max_rel_err = ((grad_sampling_loc_cuda - grad_sampling_loc_pytorch).abs() / grad_sampling_loc_pytorch.abs())[~zero_grad_mask].max() if zero_grad_mask.sum() == 0: max_abs_err_0 = 0 else: max_abs_err_0 = (grad_sampling_loc_cuda - grad_sampling_loc_pytorch).abs()[zero_grad_mask].max() print(f'* {bwdok} check_backward_equal_with_pytorch - input2: ' f'max_abs_err {max_abs_err:.2e} ' f'max_rel_err {max_rel_err:.2e} ' f'max_abs_err_0 {max_abs_err_0:.2e}') grad_attn_weight_pytorch = torch.autograd.grad(loss_pytorch, attention_weights, retain_graph=True)[0] grad_attn_weight_cuda = torch.autograd.grad(loss_cuda, attention_weights, retain_graph=True)[0] bwdok = torch.allclose(grad_attn_weight_cuda, grad_attn_weight_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (grad_attn_weight_cuda - grad_attn_weight_pytorch).abs().max() zero_grad_mask = grad_attn_weight_pytorch == 0 max_rel_err = ((grad_attn_weight_cuda - grad_attn_weight_pytorch).abs() / grad_attn_weight_pytorch.abs())[~zero_grad_mask].max() if zero_grad_mask.sum() == 0: max_abs_err_0 = 0 else: max_abs_err_0 = (grad_attn_weight_cuda - grad_attn_weight_pytorch).abs()[zero_grad_mask].max() print(f'* {bwdok} check_backward_equal_with_pytorch - input3: ' f'max_abs_err {max_abs_err:.2e} ' f'max_rel_err {max_rel_err:.2e} ' f'max_abs_err_0 {max_abs_err_0:.2e}') def check_gradient_ms_deform_attn( use_pytorch=False, grad_value=True, grad_sampling_loc=True, grad_attn_weight=True): value = torch.rand(N, S, M, D).cuda() * 0.01 sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() attention_weights = torch.rand(N, Lq, M, L, P).cuda() + 1e-5 attention_weights /= attention_weights.sum(-1, keepdim=True).sum(-2, keepdim=True) im2col_step = 2 if use_pytorch: func = ms_deform_attn_core_pytorch else: func = MSDeformAttnFunction.apply value.requires_grad = grad_value sampling_locations.requires_grad = grad_sampling_loc attention_weights.requires_grad = grad_attn_weight eps = 1e-3 if not grad_sampling_loc else 2e-4 if use_pytorch: gradok = gradcheck(func, (value, shapes, sampling_locations, attention_weights), eps=eps, atol=1e-3, rtol=1e-2, raise_exception=True) else: gradok = gradcheck(func, (value, shapes, sampling_locations, attention_weights, im2col_step), eps=eps, atol=1e-3, rtol=1e-2, raise_exception=True) print(f'* {gradok} ' f'check_gradient_ms_deform_attn(' f'{use_pytorch}, {grad_value}, {grad_sampling_loc}, {grad_attn_weight})') if __name__ == '__main__': print('checking forward') check_forward_equal_with_pytorch() print('checking backward') check_backward_equal_with_pytorch() print('checking gradient of pytorch version') check_gradient_ms_deform_attn(True, True, False, False) check_gradient_ms_deform_attn(True, False, True, False) check_gradient_ms_deform_attn(True, False, False, True) check_gradient_ms_deform_attn(True, True, True, True) print('checking gradient of cuda version') check_gradient_ms_deform_attn(False, True, False, False) check_gradient_ms_deform_attn(False, False, True, False) check_gradient_ms_deform_attn(False, False, False, True) check_gradient_ms_deform_attn(False, True, True, True) ================================================ FILE: src/trackformer/models/ops/test_double_precision.py ================================================ #!/usr/bin/env python from __future__ import absolute_import from __future__ import print_function from __future__ import division import time import torch import torch.nn as nn from torch.autograd import gradcheck from functions.ms_deform_attn_func import MSDeformAttnFunction, ms_deform_attn_core_pytorch N, M, D = 2, 2, 4 Lq, L, P = 3, 3, 2 shapes = torch.as_tensor([(12, 8), (6, 4), (3, 2)], dtype=torch.long).cuda() S = sum([(H*W).item() for H, W in shapes]) torch.manual_seed(3) @torch.no_grad() def check_forward_equal_with_pytorch(): value = torch.rand(N, S, M, D).cuda() * 0.01 sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() attention_weights = torch.rand(N, Lq, M, L, P).cuda() + 1e-5 attention_weights /= attention_weights.sum(-1, keepdim=True).sum(-2, keepdim=True) im2col_step = 2 output_pytorch = ms_deform_attn_core_pytorch(value.double(), shapes, sampling_locations.double(), attention_weights.double()).detach().cpu() output_cuda = MSDeformAttnFunction.apply(value.double(), shapes, sampling_locations.double(), attention_weights.double(), im2col_step).detach().cpu() fwdok = torch.allclose(output_cuda, output_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (output_cuda - output_pytorch).abs().max() max_rel_err = ((output_cuda - output_pytorch).abs() / output_pytorch.abs()).max() print(f'* {fwdok} check_forward_equal_with_pytorch: max_abs_err {max_abs_err:.2e} max_rel_err {max_rel_err:.2e}') def check_backward_equal_with_pytorch(): value = torch.rand(N, S, M, D).cuda() * 0.01 sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() attention_weights = torch.rand(N, Lq, M, L, P).cuda() + 1e-5 attention_weights /= attention_weights.sum(-1, keepdim=True).sum(-2, keepdim=True) im2col_step = 2 value.requires_grad = True sampling_locations.requires_grad = True attention_weights.requires_grad = True output_pytorch = ms_deform_attn_core_pytorch(value.double(), shapes, sampling_locations.double(), attention_weights.double()) output_cuda = MSDeformAttnFunction.apply(value.double(), shapes, sampling_locations.double(), attention_weights.double(), im2col_step) loss_pytorch = output_pytorch.abs().sum() loss_cuda = output_cuda.abs().sum() grad_value_pytorch = torch.autograd.grad(loss_pytorch, value, retain_graph=True)[0].detach().cpu() grad_value_cuda = torch.autograd.grad(loss_cuda, value, retain_graph=True)[0].detach().cpu() bwdok = torch.allclose(grad_value_cuda, grad_value_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (grad_value_cuda - grad_value_pytorch).abs().max() zero_grad_mask = grad_value_pytorch == 0 max_rel_err = ((grad_value_cuda - grad_value_pytorch).abs() / grad_value_pytorch.abs())[~zero_grad_mask].max() if zero_grad_mask.sum() == 0: max_abs_err_0 = 0 else: max_abs_err_0 = (grad_value_cuda - grad_value_pytorch).abs()[zero_grad_mask].max() print(f'* {bwdok} check_backward_equal_with_pytorch - input1: ' f'max_abs_err {max_abs_err:.2e} ' f'max_rel_err {max_rel_err:.2e} ' f'max_abs_err_0 {max_abs_err_0:.2e}') grad_sampling_loc_pytorch = torch.autograd.grad(loss_pytorch, sampling_locations, retain_graph=True)[0].detach().cpu() grad_sampling_loc_cuda = torch.autograd.grad(loss_cuda, sampling_locations, retain_graph=True)[0].detach().cpu() bwdok = torch.allclose(grad_sampling_loc_cuda, grad_sampling_loc_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (grad_sampling_loc_cuda - grad_sampling_loc_pytorch).abs().max() zero_grad_mask = grad_sampling_loc_pytorch == 0 max_rel_err = ((grad_sampling_loc_cuda - grad_sampling_loc_pytorch).abs() / grad_sampling_loc_pytorch.abs())[~zero_grad_mask].max() if zero_grad_mask.sum() == 0: max_abs_err_0 = 0 else: max_abs_err_0 = (grad_sampling_loc_cuda - grad_sampling_loc_pytorch).abs()[zero_grad_mask].max() print(f'* {bwdok} check_backward_equal_with_pytorch - input2: ' f'max_abs_err {max_abs_err:.2e} ' f'max_rel_err {max_rel_err:.2e} ' f'max_abs_err_0 {max_abs_err_0:.2e}') grad_attn_weight_pytorch = torch.autograd.grad(loss_pytorch, attention_weights, retain_graph=True)[0].detach().cpu() grad_attn_weight_cuda = torch.autograd.grad(loss_cuda, attention_weights, retain_graph=True)[0].detach().cpu() bwdok = torch.allclose(grad_attn_weight_cuda, grad_attn_weight_pytorch, rtol=1e-2, atol=1e-3) max_abs_err = (grad_attn_weight_cuda - grad_attn_weight_pytorch).abs().max() zero_grad_mask = grad_attn_weight_pytorch == 0 max_rel_err = ((grad_attn_weight_cuda - grad_attn_weight_pytorch).abs() / grad_attn_weight_pytorch.abs())[~zero_grad_mask].max() if zero_grad_mask.sum() == 0: max_abs_err_0 = 0 else: max_abs_err_0 = (grad_attn_weight_cuda - grad_attn_weight_pytorch).abs()[zero_grad_mask].max() print(f'* {bwdok} check_backward_equal_with_pytorch - input3: ' f'max_abs_err {max_abs_err:.2e} ' f'max_rel_err {max_rel_err:.2e} ' f'max_abs_err_0 {max_abs_err_0:.2e}') def check_gradient_ms_deform_attn( use_pytorch=False, grad_value=True, grad_sampling_loc=True, grad_attn_weight=True): value = torch.rand(N, S, M, D).cuda() * 0.01 sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() attention_weights = torch.rand(N, Lq, M, L, P).cuda() + 1e-5 attention_weights /= attention_weights.sum(-1, keepdim=True).sum(-2, keepdim=True) im2col_step = 2 if use_pytorch: func = ms_deform_attn_core_pytorch else: func = MSDeformAttnFunction.apply value.requires_grad = grad_value sampling_locations.requires_grad = grad_sampling_loc attention_weights.requires_grad = grad_attn_weight eps = 1e-3 if not grad_sampling_loc else 2e-4 if use_pytorch: gradok = gradcheck(func, (value.double(), shapes, sampling_locations.double(), attention_weights.double())) else: gradok = gradcheck(func, (value.double(), shapes, sampling_locations.double(), attention_weights.double(), im2col_step)) print(f'* {gradok} ' f'check_gradient_ms_deform_attn(' f'{use_pytorch}, {grad_value}, {grad_sampling_loc}, {grad_attn_weight})') if __name__ == '__main__': print('checking forward') check_forward_equal_with_pytorch() print('checking backward') check_backward_equal_with_pytorch() print('checking gradient of pytorch version') check_gradient_ms_deform_attn(True, True, False, False) check_gradient_ms_deform_attn(True, False, True, False) check_gradient_ms_deform_attn(True, False, False, True) check_gradient_ms_deform_attn(True, True, True, True) print('checking gradient of cuda version') check_gradient_ms_deform_attn(False, True, False, False) check_gradient_ms_deform_attn(False, False, True, False) check_gradient_ms_deform_attn(False, False, False, True) check_gradient_ms_deform_attn(False, True, True, True) ================================================ FILE: src/trackformer/models/position_encoding.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Various positional encodings for the transformer. """ import math import torch from torch import nn from ..util.misc import NestedTensor class PositionEmbeddingSine3D(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you need paper, generalized to work on images. """ # def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): def __init__(self, num_pos_feats=64, num_frames=2, temperature=10000, normalize=False, scale=None): super().__init__() self.num_pos_feats = num_pos_feats self.temperature = temperature self.normalize = normalize self.frames = num_frames if scale is not None and normalize is False: raise ValueError("normalize should be True if scale is passed") if scale is None: scale = 2 * math.pi self.scale = scale def forward(self, tensor_list: NestedTensor): x = tensor_list.tensors mask = tensor_list.mask n, h, w = mask.shape # assert n == 1 # mask = mask.reshape(1, 1, h, w) mask = mask.view(n, 1, h, w) mask = mask.expand(n, self.frames, h, w) assert mask is not None not_mask = ~mask # y_embed = not_mask.cumsum(1, dtype=torch.float32) # x_embed = not_mask.cumsum(2, dtype=torch.float32) z_embed = not_mask.cumsum(1, dtype=torch.float32) y_embed = not_mask.cumsum(2, dtype=torch.float32) x_embed = not_mask.cumsum(3, dtype=torch.float32) if self.normalize: eps = 1e-6 # y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale # x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale z_embed = z_embed / (z_embed[:, -1:, :, :] + eps) * self.scale y_embed = y_embed / (y_embed[:, :, -1:, :] + eps) * self.scale x_embed = x_embed / (x_embed[:, :, :, -1:] + eps) * self.scale dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) # pos_x = x_embed[:, :, :, None] / dim_t # pos_y = y_embed[:, :, :, None] / dim_t # pos_x = torch.stack(( # pos_x[:, :, :, 0::2].sin(), # pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) # pos_y = torch.stack(( # pos_y[:, :, :, 0::2].sin(), # pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) # pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) pos_x = x_embed[:, :, :, :, None] / dim_t pos_y = y_embed[:, :, :, :, None] / dim_t pos_z = z_embed[:, :, :, :, None] / dim_t pos_x = torch.stack((pos_x[:, :, :, :, 0::2].sin(), pos_x[:, :, :, :, 1::2].cos()), dim=5).flatten(4) pos_y = torch.stack((pos_y[:, :, :, :, 0::2].sin(), pos_y[:, :, :, :, 1::2].cos()), dim=5).flatten(4) pos_z = torch.stack((pos_z[:, :, :, :, 0::2].sin(), pos_z[:, :, :, :, 1::2].cos()), dim=5).flatten(4) # pos_w = torch.zeros_like(pos_z) # pos = torch.cat((pos_w, pos_z, pos_y, pos_x), dim=4).permute(0, 1, 4, 2, 3) pos = torch.cat((pos_z, pos_y, pos_x), dim=4).permute(0, 1, 4, 2, 3) return pos class PositionEmbeddingSine(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you need paper, generalized to work on images. """ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): super().__init__() self.num_pos_feats = num_pos_feats self.temperature = temperature self.normalize = normalize if scale is not None and normalize is False: raise ValueError("normalize should be True if scale is passed") if scale is None: scale = 2 * math.pi self.scale = scale def forward(self, tensor_list: NestedTensor): x = tensor_list.tensors mask = tensor_list.mask assert mask is not None not_mask = ~mask y_embed = not_mask.cumsum(1, dtype=torch.float32) x_embed = not_mask.cumsum(2, dtype=torch.float32) if self.normalize: eps = 1e-6 y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) pos_x = x_embed[:, :, :, None] / dim_t pos_y = y_embed[:, :, :, None] / dim_t pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) return pos class PositionEmbeddingLearned(nn.Module): """ Absolute pos embedding, learned. """ def __init__(self, num_pos_feats=256): super().__init__() self.row_embed = nn.Embedding(50, num_pos_feats) self.col_embed = nn.Embedding(50, num_pos_feats) self.reset_parameters() def reset_parameters(self): nn.init.uniform_(self.row_embed.weight) nn.init.uniform_(self.col_embed.weight) def forward(self, tensor_list: NestedTensor): x = tensor_list.tensors h, w = x.shape[-2:] i = torch.arange(w, device=x.device) j = torch.arange(h, device=x.device) x_emb = self.col_embed(i) y_emb = self.row_embed(j) pos = torch.cat([ x_emb.unsqueeze(0).repeat(h, 1, 1), y_emb.unsqueeze(1).repeat(1, w, 1), ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1) return pos def build_position_encoding(args): # n_steps = args.hidden_dim // 2 # n_steps = args.hidden_dim // 4 if args.multi_frame_attention and args.multi_frame_encoding: n_steps = args.hidden_dim // 3 sine_emedding_func = PositionEmbeddingSine3D else: n_steps = args.hidden_dim // 2 sine_emedding_func = PositionEmbeddingSine if args.position_embedding in ('v2', 'sine'): # TODO find a better way of exposing other arguments position_embedding = sine_emedding_func(n_steps, normalize=True) elif args.position_embedding in ('v3', 'learned'): position_embedding = PositionEmbeddingLearned(n_steps) else: raise ValueError(f"not supported {args.position_embedding}") return position_embedding ================================================ FILE: src/trackformer/models/tracker.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Tracker which achieves MOT with the provided object detector. """ from collections import deque import numpy as np import torch import torch.nn.functional as F from scipy.optimize import linear_sum_assignment from torchvision.ops.boxes import clip_boxes_to_image, nms, box_iou from ..util.box_ops import box_xyxy_to_cxcywh class Tracker: """The main tracking file, here is where magic happens.""" def __init__(self, obj_detector, obj_detector_post, tracker_cfg, generate_attention_maps, logger=None, verbose=False): self.obj_detector = obj_detector self.obj_detector_post = obj_detector_post self.detection_obj_score_thresh = tracker_cfg['detection_obj_score_thresh'] self.track_obj_score_thresh = tracker_cfg['track_obj_score_thresh'] self.detection_nms_thresh = tracker_cfg['detection_nms_thresh'] self.track_nms_thresh = tracker_cfg['track_nms_thresh'] self.public_detections = tracker_cfg['public_detections'] self.inactive_patience = float(tracker_cfg['inactive_patience']) self.reid_sim_threshold = tracker_cfg['reid_sim_threshold'] self.reid_sim_only = tracker_cfg['reid_sim_only'] self.generate_attention_maps = generate_attention_maps self.reid_score_thresh = tracker_cfg['reid_score_thresh'] self.reid_greedy_matching = tracker_cfg['reid_greedy_matching'] self.prev_frame_dist = tracker_cfg['prev_frame_dist'] self.steps_termination = tracker_cfg['steps_termination'] if self.generate_attention_maps: assert hasattr(self.obj_detector.transformer.decoder.layers[-1], 'multihead_attn'), 'Generation of attention maps not possible for deformable DETR.' attention_data = { 'maps': None, 'conv_features': {}, 'hooks': []} hook = self.obj_detector.backbone[-2].register_forward_hook( lambda self, input, output: attention_data.update({'conv_features': output})) attention_data['hooks'].append(hook) def add_attention_map_to_data(self, input, output): height, width = attention_data['conv_features']['3'].tensors.shape[-2:] attention_maps = output[1].view(-1, height, width) attention_data.update({'maps': attention_maps}) multihead_attn = self.obj_detector.transformer.decoder.layers[-1].multihead_attn hook = multihead_attn.register_forward_hook( add_attention_map_to_data) attention_data['hooks'].append(hook) self.attention_data = attention_data self._logger = logger if self._logger is None: self._logger = lambda *log_strs: None self._verbose = verbose @property def num_object_queries(self): return self.obj_detector.num_queries def reset(self, hard=True): self.tracks = [] self.inactive_tracks = [] self._prev_features = deque([None], maxlen=self.prev_frame_dist) if hard: self.track_num = 0 self.results = {} self.frame_index = 0 self.num_reids = 0 @property def device(self): return next(self.obj_detector.parameters()).device def tracks_to_inactive(self, tracks): self.tracks = [t for t in self.tracks if t not in tracks] for track in tracks: track.pos = track.last_pos[-1] self.inactive_tracks += tracks def add_tracks(self, pos, scores, hs_embeds, indices, masks=None, attention_maps=None, aux_results=None): """Initializes new Track objects and saves them.""" new_track_ids = [] for i in range(len(pos)): self.tracks.append(Track( pos[i], scores[i], self.track_num + i, hs_embeds[i], indices[i], None if masks is None else masks[i], None if attention_maps is None else attention_maps[i], )) new_track_ids.append(self.track_num + i) self.track_num += len(new_track_ids) if new_track_ids: self._logger( f'INIT TRACK IDS (detection_obj_score_thresh={self.detection_obj_score_thresh}): ' f'{new_track_ids}') if aux_results is not None: aux_scores = torch.cat([ a['scores'][-self.num_object_queries:][indices] for a in aux_results] + [scores[..., None], ], dim=-1) for new_track_id, aux_score in zip(new_track_ids, aux_scores): self._logger(f"AUX SCORES ID {new_track_id}: {[f'{s:.2f}' for s in aux_score]}") return new_track_ids def public_detections_mask(self, new_det_boxes, public_det_boxes): """Returns mask to filter current frame detections with provided set of public detections.""" if not self.public_detections: return torch.ones(new_det_boxes.size(0)).bool().to(self.device) if not len(public_det_boxes) or not len(new_det_boxes): return torch.zeros(new_det_boxes.size(0)).bool().to(self.device) public_detections_mask = torch.zeros(new_det_boxes.size(0)).bool().to(self.device) if self.public_detections == 'center_distance': item_size = [((box[2] - box[0]) * (box[3] - box[1])) for box in new_det_boxes] item_size = np.array(item_size, np.float32) new_det_boxes_cxcy = box_xyxy_to_cxcywh(new_det_boxes).cpu().numpy()[:,:2] public_det_boxes_cxcy = box_xyxy_to_cxcywh(public_det_boxes).cpu().numpy()[:,:2] dist3 = new_det_boxes_cxcy.reshape(-1, 1, 2) - public_det_boxes_cxcy.reshape(1, -1, 2) dist3 = (dist3 ** 2).sum(axis=2) for j in range(len(public_det_boxes)): i = dist3[:, j].argmin() if dist3[i, j] < item_size[i]: dist3[i, :] = 1e18 public_detections_mask[i] = True elif self.public_detections == 'min_iou_0_5': iou_matrix = box_iou(new_det_boxes, public_det_boxes.to(self.device)) for j in range(len(public_det_boxes)): i = iou_matrix[:, j].argmax() if iou_matrix[i, j] >= 0.5: iou_matrix[i, :] = 0 public_detections_mask[i] = True else: raise NotImplementedError return public_detections_mask def reid(self, new_det_boxes, new_det_scores, new_det_hs_embeds, new_det_masks=None, new_det_attention_maps=None): """Tries to ReID inactive tracks with provided detections.""" self.inactive_tracks = [ t for t in self.inactive_tracks if t.has_positive_area() and t.count_inactive <= self.inactive_patience ] if not self.inactive_tracks or not len(new_det_boxes): return torch.ones(new_det_boxes.size(0)).bool().to(self.device) # calculate distances dist_mat = [] if self.reid_greedy_matching: new_det_boxes_cxcyhw = box_xyxy_to_cxcywh(new_det_boxes).cpu().numpy() inactive_boxes_cxcyhw = box_xyxy_to_cxcywh(torch.stack([ track.pos for track in self.inactive_tracks])).cpu().numpy() dist_mat = inactive_boxes_cxcyhw[:, :2].reshape(-1, 1, 2) - \ new_det_boxes_cxcyhw[:, :2].reshape(1, -1, 2) dist_mat = (dist_mat ** 2).sum(axis=2) track_size = inactive_boxes_cxcyhw[:, 2] * inactive_boxes_cxcyhw[:, 3] item_size = new_det_boxes_cxcyhw[:, 2] * new_det_boxes_cxcyhw[:, 3] invalid = ((dist_mat > track_size.reshape(len(track_size), 1)) + \ (dist_mat > item_size.reshape(1, len(item_size)))) dist_mat = dist_mat + invalid * 1e18 def greedy_assignment(dist): matched_indices = [] if dist.shape[1] == 0: return np.array(matched_indices, np.int32).reshape(-1, 2) for i in range(dist.shape[0]): j = dist[i].argmin() if dist[i][j] < 1e16: dist[:, j] = 1e18 dist[i, j] = 0.0 matched_indices.append([i, j]) return np.array(matched_indices, np.int32).reshape(-1, 2) matched_indices = greedy_assignment(dist_mat) row_indices, col_indices = matched_indices[:, 0], matched_indices[:, 1] else: for track in self.inactive_tracks: track_sim = track.hs_embed[-1] track_sim_dists = torch.cat([ F.pairwise_distance(track_sim, sim.unsqueeze(0)) for sim in new_det_hs_embeds]) dist_mat.append(track_sim_dists) dist_mat = torch.stack(dist_mat) dist_mat = dist_mat.cpu().numpy() row_indices, col_indices = linear_sum_assignment(dist_mat) assigned_indices = [] remove_inactive = [] for row_ind, col_ind in zip(row_indices, col_indices): if dist_mat[row_ind, col_ind] <= self.reid_sim_threshold: track = self.inactive_tracks[row_ind] self._logger( f'REID: track.id={track.id} - ' f'count_inactive={track.count_inactive} - ' f'to_inactive_frame={self.frame_index - track.count_inactive}') track.count_inactive = 0 track.pos = new_det_boxes[col_ind] track.score = new_det_scores[col_ind] track.hs_embed.append(new_det_hs_embeds[col_ind]) track.reset_last_pos() if new_det_masks is not None: track.mask = new_det_masks[col_ind] if new_det_attention_maps is not None: track.attention_map = new_det_attention_maps[col_ind] assigned_indices.append(col_ind) remove_inactive.append(track) self.tracks.append(track) self.num_reids += 1 for track in remove_inactive: self.inactive_tracks.remove(track) reid_mask = torch.ones(new_det_boxes.size(0)).bool().to(self.device) for ind in assigned_indices: reid_mask[ind] = False return reid_mask def step(self, blob): """This function should be called every timestep to perform tracking with a blob containing the image information. """ self.inactive_tracks = [ t for t in self.inactive_tracks if t.has_positive_area() and t.count_inactive <= self.inactive_patience ] self._logger(f'FRAME: {self.frame_index + 1}') if self.inactive_tracks: self._logger(f'INACTIVE TRACK IDS: {[t.id for t in self.inactive_tracks]}') # add current position to last_pos list for track in self.tracks: track.last_pos.append(track.pos.clone()) img = blob['img'].to(self.device) orig_size = blob['orig_size'].to(self.device) target = None num_prev_track = len(self.tracks + self.inactive_tracks) if num_prev_track: track_query_boxes = torch.stack([ t.pos for t in self.tracks + self.inactive_tracks], dim=0).cpu() track_query_boxes = box_xyxy_to_cxcywh(track_query_boxes) track_query_boxes = track_query_boxes / torch.tensor([ orig_size[0, 1], orig_size[0, 0], orig_size[0, 1], orig_size[0, 0]], dtype=torch.float32) target = {'track_query_boxes': track_query_boxes} target['image_id'] = torch.tensor([1]).to(self.device) target['track_query_hs_embeds'] = torch.stack([ t.hs_embed[-1] for t in self.tracks + self.inactive_tracks], dim=0) target = {k: v.to(self.device) for k, v in target.items()} target = [target] outputs, _, features, _, _ = self.obj_detector(img, target, self._prev_features[0]) hs_embeds = outputs['hs_embed'][0] results = self.obj_detector_post['bbox'](outputs, orig_size) if "segm" in self.obj_detector_post: results = self.obj_detector_post['segm']( results, outputs, orig_size, blob["size"].to(self.device), return_probs=True) result = results[0] if 'masks' in result: result['masks'] = result['masks'].squeeze(dim=1) if self.obj_detector.overflow_boxes: boxes = result['boxes'] else: boxes = clip_boxes_to_image(result['boxes'], orig_size[0]) # TRACKS if num_prev_track: track_scores = result['scores'][:-self.num_object_queries] track_boxes = boxes[:-self.num_object_queries] if 'masks' in result: track_masks = result['masks'][:-self.num_object_queries] if self.generate_attention_maps: track_attention_maps = self.attention_data['maps'][:-self.num_object_queries] track_keep = torch.logical_and( track_scores > self.track_obj_score_thresh, result['labels'][:-self.num_object_queries] == 0) tracks_to_inactive = [] tracks_from_inactive = [] for i, track in enumerate(self.tracks): if track_keep[i]: track.score = track_scores[i] track.hs_embed.append(hs_embeds[i]) track.pos = track_boxes[i] track.count_termination = 0 if 'masks' in result: track.mask = track_masks[i] if self.generate_attention_maps: track.attention_map = track_attention_maps[i] else: track.count_termination += 1 if track.count_termination >= self.steps_termination: tracks_to_inactive.append(track) track_keep = torch.logical_and( track_scores > self.reid_score_thresh, result['labels'][:-self.num_object_queries] == 0) # reid queries for i, track in enumerate(self.inactive_tracks, start=len(self.tracks)): if track_keep[i]: track.score = track_scores[i] track.hs_embed.append(hs_embeds[i]) track.pos = track_boxes[i] if 'masks' in result: track.mask = track_masks[i] if self.generate_attention_maps: track.attention_map = track_attention_maps[i] tracks_from_inactive.append(track) if tracks_to_inactive: self._logger( f'NEW INACTIVE TRACK IDS ' f'(track_obj_score_thresh={self.track_obj_score_thresh}): ' f'{[t.id for t in tracks_to_inactive]}') self.num_reids += len(tracks_from_inactive) for track in tracks_from_inactive: self.inactive_tracks.remove(track) self.tracks.append(track) self.tracks_to_inactive(tracks_to_inactive) # self.tracks = [ # track for track in self.tracks # if track not in tracks_to_inactive] if self.track_nms_thresh and self.tracks: track_boxes = torch.stack([t.pos for t in self.tracks]) track_scores = torch.stack([t.score for t in self.tracks]) keep = nms(track_boxes, track_scores, self.track_nms_thresh) remove_tracks = [ track for i, track in enumerate(self.tracks) if i not in keep] if remove_tracks: self._logger( f'REMOVE TRACK IDS (track_nms_thresh={self.track_nms_thresh}): ' f'{[track.id for track in remove_tracks]}') # self.tracks_to_inactive(remove_tracks) self.tracks = [ track for track in self.tracks if track not in remove_tracks] # NEW DETS new_det_scores = result['scores'][-self.num_object_queries:] new_det_boxes = boxes[-self.num_object_queries:] new_det_hs_embeds = hs_embeds[-self.num_object_queries:] if 'masks' in result: new_det_masks = result['masks'][-self.num_object_queries:] if self.generate_attention_maps: new_det_attention_maps = self.attention_data['maps'][-self.num_object_queries:] new_det_keep = torch.logical_and( new_det_scores > self.detection_obj_score_thresh, result['labels'][-self.num_object_queries:] == 0) new_det_boxes = new_det_boxes[new_det_keep] new_det_scores = new_det_scores[new_det_keep] new_det_hs_embeds = new_det_hs_embeds[new_det_keep] new_det_indices = new_det_keep.float().nonzero() if 'masks' in result: new_det_masks = new_det_masks[new_det_keep] if self.generate_attention_maps: new_det_attention_maps = new_det_attention_maps[new_det_keep] # public detection public_detections_mask = self.public_detections_mask( new_det_boxes, blob['dets'][0]) new_det_boxes = new_det_boxes[public_detections_mask] new_det_scores = new_det_scores[public_detections_mask] new_det_hs_embeds = new_det_hs_embeds[public_detections_mask] new_det_indices = new_det_indices[public_detections_mask] if 'masks' in result: new_det_masks = new_det_masks[public_detections_mask] if self.generate_attention_maps: new_det_attention_maps = new_det_attention_maps[public_detections_mask] # reid reid_mask = self.reid( new_det_boxes, new_det_scores, new_det_hs_embeds, new_det_masks if 'masks' in result else None, new_det_attention_maps if self.generate_attention_maps else None) new_det_boxes = new_det_boxes[reid_mask] new_det_scores = new_det_scores[reid_mask] new_det_hs_embeds = new_det_hs_embeds[reid_mask] new_det_indices = new_det_indices[reid_mask] if 'masks' in result: new_det_masks = new_det_masks[reid_mask] if self.generate_attention_maps: new_det_attention_maps = new_det_attention_maps[reid_mask] # final add track aux_results = None if self._verbose: aux_results = [ self.obj_detector_post['bbox'](out, orig_size)[0] for out in outputs['aux_outputs']] new_track_ids = self.add_tracks( new_det_boxes, new_det_scores, new_det_hs_embeds, new_det_indices, new_det_masks if 'masks' in result else None, new_det_attention_maps if self.generate_attention_maps else None, aux_results) # NMS if self.detection_nms_thresh and self.tracks: track_boxes = torch.stack([t.pos for t in self.tracks]) track_scores = torch.stack([t.score for t in self.tracks]) new_track_mask = torch.tensor([ True if t.id in new_track_ids else False for t in self.tracks]) track_scores[~new_track_mask] = np.inf keep = nms(track_boxes, track_scores, self.detection_nms_thresh) remove_tracks = [track for i, track in enumerate(self.tracks) if i not in keep] if remove_tracks: self._logger( f'REMOVE TRACK IDS (detection_nms_thresh={self.detection_nms_thresh}): ' f'{[track.id for track in remove_tracks]}') self.tracks = [track for track in self.tracks if track not in remove_tracks] #################### # Generate Results # #################### if 'masks' in result and self.tracks: track_mask_probs = torch.stack([track.mask for track in self.tracks]) index_map = torch.arange(track_mask_probs.size(0))[:, None, None] index_map = index_map.expand_as(track_mask_probs) track_masks = torch.logical_and( # remove background track_mask_probs > 0.5, # remove overlapp by largest probablity index_map == track_mask_probs.argmax(dim=0) ) for i, track in enumerate(self.tracks): track.mask = track_masks[i] for track in self.tracks: if track.id not in self.results: self.results[track.id] = {} self.results[track.id][self.frame_index] = {} if self.obj_detector.overflow_boxes: self.results[track.id][self.frame_index]['bbox'] = track.pos.cpu().numpy() else: self.results[track.id][self.frame_index]['bbox'] = clip_boxes_to_image(track.pos, orig_size[0]).cpu().numpy() self.results[track.id][self.frame_index]['score'] = track.score.cpu().numpy() self.results[track.id][self.frame_index]['obj_ind'] = track.obj_ind.cpu().item() if track.mask is not None: self.results[track.id][self.frame_index]['mask'] = track.mask.cpu().numpy() if track.attention_map is not None: self.results[track.id][self.frame_index]['attention_map'] = \ track.attention_map.cpu().numpy() for t in self.inactive_tracks: t.count_inactive += 1 self.frame_index += 1 self._prev_features.append(features) if self.reid_sim_only: self.tracks_to_inactive(self.tracks) def get_results(self): """Return current tracking results.""" return self.results class Track(object): """This class contains all necessary for every individual track.""" def __init__(self, pos, score, track_id, hs_embed, obj_ind, mask=None, attention_map=None): self.id = track_id self.pos = pos self.last_pos = deque([pos.clone()]) self.score = score self.ims = deque([]) self.count_inactive = 0 self.count_termination = 0 self.gt_id = None self.hs_embed = [hs_embed] self.mask = mask self.attention_map = attention_map self.obj_ind = obj_ind def has_positive_area(self) -> bool: """Checks if the current position of the track has a valid, .i.e., positive area, bounding box.""" return self.pos[2] > self.pos[0] and self.pos[3] > self.pos[1] def reset_last_pos(self) -> None: """Reset last_pos to the current position of the track.""" self.last_pos.clear() self.last_pos.append(self.pos.clone()) ================================================ FILE: src/trackformer/models/transformer.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ DETR Transformer class. Copy-paste from torch.nn.Transformer with modifications: * positional encodings are passed in MHattention * extra LN at the end of encoder is removed * decoder returns a stack of activations from all decoding layers """ import copy from typing import Optional import torch import torch.nn.functional as F from torch import Tensor, nn class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, return_intermediate_dec=False, track_attention=False): super().__init__() encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before) encoder_norm = nn.LayerNorm(d_model) if normalize_before else None self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm) decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before) decoder_norm = nn.LayerNorm(d_model) self.decoder = TransformerDecoder( decoder_layer, encoder_layer, num_decoder_layers, decoder_norm, return_intermediate=return_intermediate_dec, track_attention=track_attention) self._reset_parameters() self.d_model = d_model self.nhead = nhead def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def forward(self, src, mask, query_embed, pos_embed, tgt=None, prev_frame=None): # flatten NxCxHxW to HWxNxC bs, c, h, w = src.shape src = src.flatten(2).permute(2, 0, 1) pos_embed = pos_embed.flatten(2).permute(2, 0, 1) mask = mask.flatten(1) if tgt is None: tgt = torch.zeros_like(query_embed) memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed) memory_prev_frame = None if prev_frame is not None: src_prev_frame = prev_frame['src'].flatten(2).permute(2, 0, 1) pos_embed_prev_frame = prev_frame['pos'].flatten(2).permute(2, 0, 1) mask_prev_frame = prev_frame['mask'].flatten(1) memory_prev_frame = self.encoder( src_prev_frame, src_key_padding_mask=mask_prev_frame, pos=pos_embed_prev_frame) prev_frame['memory'] = memory_prev_frame prev_frame['memory_key_padding_mask'] = mask_prev_frame prev_frame['pos'] = pos_embed_prev_frame hs, hs_without_norm = self.decoder(tgt, memory, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed, prev_frame=prev_frame) return (hs.transpose(1, 2), hs_without_norm.transpose(1, 2), memory.permute(1, 2, 0).view(bs, c, h, w)) class TransformerEncoder(nn.Module): def __init__(self, encoder_layer, num_layers, norm=None): super().__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self, src, mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None): output = src for layer in self.layers: output = layer(output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, pos=pos) if self.norm is not None: output = self.norm(output) return output class TransformerDecoder(nn.Module): def __init__(self, decoder_layer, encoder_layer, num_layers, norm=None, return_intermediate=False, track_attention=False): super().__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm self.return_intermediate = return_intermediate self.track_attention = track_attention if self.track_attention: self.layers_track_attention = _get_clones(encoder_layer, num_layers) def forward(self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, prev_frame: Optional[dict] = None): output = tgt intermediate = [] if self.track_attention: track_query_pos = query_pos[:-100].clone() query_pos[:-100] = 0.0 for i, layer in enumerate(self.layers): if self.track_attention: track_output = output[:-100].clone() track_output = self.layers_track_attention[i]( track_output, src_mask=tgt_mask, src_key_padding_mask=tgt_key_padding_mask, pos=track_query_pos) output = torch.cat([track_output, output[-100:]]) output = layer(output, memory, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask, pos=pos, query_pos=query_pos) if self.return_intermediate: intermediate.append(output) if self.return_intermediate: output = torch.stack(intermediate) if self.norm is not None: return self.norm(output), output return output, output class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post(self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None): q = k = self.with_pos_embed(src, pos) src2 = self.self_attn(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] src = src + self.dropout1(src2) src = self.norm1(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) src = src + self.dropout2(src2) src = self.norm2(src) return src def forward_pre(self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None): src2 = self.norm1(src) q = k = self.with_pos_embed(src2, pos) src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] src = src + self.dropout1(src2) src2 = self.norm2(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src2)))) src = src + self.dropout2(src2) return src def forward(self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None): if self.normalize_before: return self.forward_pre(src, src_mask, src_key_padding_mask, pos) return self.forward_post(src, src_mask, src_key_padding_mask, pos) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.norm3 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post(self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): q = k = self.with_pos_embed(tgt, query_pos) tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] tgt = tgt + self.dropout1(tgt2) tgt = self.norm1(tgt) tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)[0] tgt = tgt + self.dropout2(tgt2) tgt = self.norm2(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout3(tgt2) tgt = self.norm3(tgt) return tgt def forward_pre(self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): tgt2 = self.norm1(tgt) q = k = self.with_pos_embed(tgt2, query_pos) tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] tgt = tgt + self.dropout1(tgt2) tgt2 = self.norm2(tgt) tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)[0] tgt = tgt + self.dropout2(tgt2) tgt2 = self.norm3(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout3(tgt2) return tgt def forward(self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): if self.normalize_before: return self.forward_pre(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) return self.forward_post(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(F"activation should be relu/gelu, not {activation}.") def build_transformer(args): return Transformer( d_model=args.hidden_dim, dropout=args.dropout, nhead=args.nheads, dim_feedforward=args.dim_feedforward, num_encoder_layers=args.enc_layers, num_decoder_layers=args.dec_layers, normalize_before=args.pre_norm, return_intermediate_dec=True, track_attention=args.track_attention ) ================================================ FILE: src/trackformer/util/__init__.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved ================================================ FILE: src/trackformer/util/box_ops.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Utilities for bounding box manipulation and GIoU. """ import torch from torchvision.ops.boxes import box_area def box_cxcywh_to_xyxy(x): x_c, y_c, w, h = x.unbind(-1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch.stack(b, dim=-1) def box_xyxy_to_cxcywh(x): x0, y0, x1, y1 = x.unbind(-1) b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)] return torch.stack(b, dim=-1) # modified from torchvision to also return the union def box_iou(boxes1, boxes2): area1 = box_area(boxes1) area2 = box_area(boxes2) lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] wh = (rb - lt).clamp(min=0) # [N,M,2] inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] union = area1[:, None] + area2 - inter iou = inter / union return iou, union def generalized_box_iou(boxes1, boxes2): """ Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2) """ # degenerate boxes gives inf / nan results # so do an early check assert (boxes1[:, 2:] >= boxes1[:, :2]).all() assert (boxes2[:, 2:] >= boxes2[:, :2]).all() iou, union = box_iou(boxes1, boxes2) lt = torch.min(boxes1[:, None, :2], boxes2[:, :2]) rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:]) wh = (rb - lt).clamp(min=0) # [N,M,2] area = wh[:, :, 0] * wh[:, :, 1] return iou - (area - union) / area def masks_to_boxes(masks): """Compute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format """ if masks.numel() == 0: return torch.zeros((0, 4), device=masks.device) h, w = masks.shape[-2:] y = torch.arange(0, h, dtype=torch.float) x = torch.arange(0, w, dtype=torch.float) y, x = torch.meshgrid(y, x) x_mask = (masks * x.unsqueeze(0)) x_max = x_mask.flatten(1).max(-1)[0] x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] y_mask = (masks * y.unsqueeze(0)) y_max = y_mask.flatten(1).max(-1)[0] y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] return torch.stack([x_min, y_min, x_max, y_max], 1) ================================================ FILE: src/trackformer/util/misc.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Misc functions, including distributed helpers. Mostly copy-paste from torchvision references. """ import datetime import os import pickle import subprocess import time from argparse import Namespace from collections import defaultdict, deque from typing import List, Optional import torch import torch.distributed as dist import torch.nn.functional as F # needed due to empty tensor bug in pytorch and torchvision 0.5 import torchvision from torch import Tensor from visdom import Visdom if int(torchvision.__version__.split('.')[0]) <= 0 and int(torchvision.__version__.split('.')[1]) < 7: from torchvision.ops import _new_empty_tensor from torchvision.ops.misc import _output_size class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a window or the global series average. """ def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{median:.4f} ({global_avg:.4f})" self.deque = deque(maxlen=window_size) self.total = 0.0 self.count = 0 self.fmt = fmt def update(self, value, n=1): self.deque.append(value) self.count += n self.total += value * n def synchronize_between_processes(self): """ Warning: does not synchronize the deque! """ if not is_dist_avail_and_initialized(): return t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') dist.barrier() dist.all_reduce(t) t = t.tolist() self.count = int(t[0]) self.total = t[1] @property def median(self): d = torch.tensor(list(self.deque)) return d.median().item() @property def avg(self): d = torch.tensor(list(self.deque), dtype=torch.float32) return d.mean().item() @property def global_avg(self): return self.total / self.count @property def max(self): return max(self.deque) @property def value(self): return self.deque[-1] def __str__(self): return self.fmt.format( median=self.median, avg=self.avg, global_avg=self.global_avg, max=self.max, value=self.value) def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] # serialized to a Tensor buffer = pickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to("cuda") # obtain Tensor size of each rank local_size = torch.tensor([tensor.numel()], device="cuda") size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] dist.all_gather(size_list, local_size) size_list = [int(size.item()) for size in size_list] max_size = max(size_list) # receiving Tensor from all ranks # we pad the tensor because torch all_gather does not support # gathering tensors of different shapes tensor_list = [] for _ in size_list: tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) if local_size != max_size: padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") tensor = torch.cat((tensor, padding), dim=0) dist.all_gather(tensor_list, tensor) data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that all processes have the averaged results. Returns a dict with the same fields as input_dict, after reduction. """ world_size = get_world_size() if world_size < 2: return input_dict with torch.no_grad(): names = [] values = [] # sort the keys so that they are consistent across processes for k in sorted(input_dict.keys()): names.append(k) values.append(input_dict[k]) values = torch.stack(values, dim=0) dist.all_reduce(values) if average: values /= world_size reduced_dict = {k: v for k, v in zip(names, values)} return reduced_dict class MetricLogger(object): def __init__(self, print_freq, delimiter="\t", vis=None, debug=False): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter self.vis = vis self.print_freq = print_freq self.debug = debug def update(self, **kwargs): for k, v in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert isinstance(v, (float, int)) self.meters[k].update(v) def __getattr__(self, attr): if attr in self.meters: return self.meters[attr] if attr in self.__dict__: return self.__dict__[attr] raise AttributeError("'{}' object has no attribute '{}'".format( type(self).__name__, attr)) def __str__(self): loss_str = [] for name, meter in self.meters.items(): loss_str.append(f"{name}: {meter}") return self.delimiter.join(loss_str) def synchronize_between_processes(self): for meter in self.meters.values(): meter.synchronize_between_processes() def add_meter(self, name, meter): self.meters[name] = meter def log_every(self, iterable, epoch=None, header=None): i = 0 if header is None: header = 'Epoch: [{}]'.format(epoch) world_len_iterable = get_world_size() * len(iterable) start_time = time.time() end = time.time() iter_time = SmoothedValue(fmt='{avg:.4f}') data_time = SmoothedValue(fmt='{avg:.4f}') space_fmt = ':' + str(len(str(world_len_iterable))) + 'd' if torch.cuda.is_available(): log_msg = self.delimiter.join([ header, '[{0' + space_fmt + '}/{1}]', 'eta: {eta}', '{meters}', 'time: {time}', 'data: {data}', 'max mem: {memory:.0f}' ]) else: log_msg = self.delimiter.join([ header, '[{0' + space_fmt + '}/{1}]', 'eta: {eta}', '{meters}', 'time: {time}', 'data_time: {data}' ]) MB = 1024.0 * 1024.0 for obj in iterable: data_time.update(time.time() - end) yield obj iter_time.update(time.time() - end) if i % self.print_freq == 0 or i == len(iterable) - 1: eta_seconds = iter_time.global_avg * (len(iterable) - i) eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) if torch.cuda.is_available(): print(log_msg.format( i * get_world_size(), world_len_iterable, eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time), memory=torch.cuda.max_memory_allocated() / MB)) else: print(log_msg.format( i * get_world_size(), world_len_iterable, eta=eta_string, meters=str(self), time=str(iter_time), data=str(data_time))) if self.vis is not None: y_data = [self.meters[legend_name].median for legend_name in self.vis.viz_opts['legend'] if legend_name in self.meters] y_data.append(iter_time.median) self.vis.plot(y_data, i * get_world_size() + (epoch - 1) * world_len_iterable) # DEBUG # if i != 0 and i % self.print_freq == 0: if self.debug and i % self.print_freq == 0: break i += 1 end = time.time() # if self.vis is not None: # self.vis.reset() total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('{} Total time: {} ({:.4f} s / it)'.format( header, total_time_str, total_time / len(iterable))) def get_sha(): cwd = os.path.dirname(os.path.abspath(__file__)) def _run(command): return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() sha = 'N/A' diff = "clean" branch = 'N/A' try: sha = _run(['git', 'rev-parse', 'HEAD']) subprocess.check_output(['git', 'diff'], cwd=cwd) diff = _run(['git', 'diff-index', 'HEAD']) diff = "has uncommited changes" if diff else "clean" branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) except Exception: pass message = f"sha: {sha}, status: {diff}, branch: {branch}" return message def collate_fn(batch): batch = list(zip(*batch)) batch[0] = nested_tensor_from_tensor_list(batch[0]) return tuple(batch) def _max_by_axis(the_list): # type: (List[List[int]]) -> List[int] maxes = the_list[0] for sublist in the_list[1:]: for index, item in enumerate(sublist): maxes[index] = max(maxes[index], item) return maxes def nested_tensor_from_tensor_list(tensor_list: List[Tensor]): # TODO make this more general if tensor_list[0].ndim == 3: # TODO make it support different-sized images max_size = _max_by_axis([list(img.shape) for img in tensor_list]) # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list])) batch_shape = [len(tensor_list)] + max_size b, _, h, w = batch_shape dtype = tensor_list[0].dtype device = tensor_list[0].device tensor = torch.zeros(batch_shape, dtype=dtype, device=device) mask = torch.ones((b, h, w), dtype=torch.bool, device=device) for img, pad_img, m in zip(tensor_list, tensor, mask): pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) m[: img.shape[1], :img.shape[2]] = False else: raise ValueError('not supported') return NestedTensor(tensor, mask) class NestedTensor(object): def __init__(self, tensors, mask: Optional[Tensor] = None): self.tensors = tensors self.mask = mask def to(self, device): # type: (Device) -> NestedTensor # noqa cast_tensor = self.tensors.to(device) mask = self.mask if mask is not None: assert mask is not None cast_mask = mask.to(device) else: cast_mask = None return NestedTensor(cast_tensor, cast_mask) def decompose(self): return self.tensors, self.mask def __repr__(self): return str(self.tensors) def unmasked_tensor(self, index: int): tensor = self.tensors[index] if not self.mask[index].any(): return tensor h_index = self.mask[index, 0, :].nonzero(as_tuple=True)[0] if len(h_index): tensor = tensor[:, :, :h_index[0]] w_index = self.mask[index, :, 0].nonzero(as_tuple=True)[0] if len(w_index): tensor = tensor[:, :w_index[0], :] return tensor def setup_for_distributed(is_master): """ This function disables printing when not in master process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) __builtin__.print = print if not is_master: def line(*args, **kwargs): pass def images(*args, **kwargs): pass Visdom.line = line Visdom.images = images def is_dist_avail_and_initialized(): if not dist.is_available(): return False if not dist.is_initialized(): return False return True def get_world_size(): if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size() def get_rank(): if not is_dist_avail_and_initialized(): return 0 return dist.get_rank() def is_main_process(): return get_rank() == 0 def save_on_master(*args, **kwargs): if is_main_process(): torch.save(*args, **kwargs) def init_distributed_mode(args): if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: args.rank = int(os.environ["RANK"]) args.world_size = int(os.environ['WORLD_SIZE']) args.gpu = int(os.environ['LOCAL_RANK']) elif 'SLURM_PROCID' in os.environ and 'SLURM_PTY_PORT' not in os.environ: # slurm process but not interactive args.rank = int(os.environ['SLURM_PROCID']) args.gpu = args.rank % torch.cuda.device_count() else: print('Not using distributed mode') args.distributed = False return args.distributed = True torch.cuda.set_device(args.gpu) args.dist_backend = 'nccl' print(f'| distributed init (rank {args.rank}): {args.dist_url}', flush=True) torch.distributed.init_process_group( backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank) # torch.distributed.barrier() setup_for_distributed(args.rank == 0) @torch.no_grad() def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" if target.numel() == 0: return [torch.zeros([], device=output.device)] maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor """ Equivalent to nn.functional.interpolate, but with support for empty batch sizes. This will eventually be supported natively by PyTorch, and this class can go away. """ if int(torchvision.__version__.split('.')[0]) <= 0 and int(torchvision.__version__.split('.')[1]) < 7: if input.numel() > 0: return torch.nn.functional.interpolate( input, size, scale_factor, mode, align_corners ) output_shape = _output_size(2, input, size, scale_factor) output_shape = list(input.shape[:-2]) + list(output_shape) return _new_empty_tensor(input, output_shape) else: return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners) class DistributedWeightedSampler(torch.utils.data.DistributedSampler): def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, replacement=True): super(DistributedWeightedSampler, self).__init__(dataset, num_replicas, rank, shuffle) assert replacement self.replacement = replacement def __iter__(self): iter_indices = super(DistributedWeightedSampler, self).__iter__() if hasattr(self.dataset, 'sample_weight'): indices = list(iter_indices) weights = torch.tensor([self.dataset.sample_weight(idx) for idx in indices]) g = torch.Generator() g.manual_seed(self.epoch) weight_indices = torch.multinomial( weights, self.num_samples, self.replacement, generator=g) indices = torch.tensor(indices)[weight_indices] iter_indices = iter(indices.tolist()) return iter_indices def __len__(self): return self.num_samples def inverse_sigmoid(x, eps=1e-5): x = x.clamp(min=0, max=1) x1 = x.clamp(min=eps) x2 = (1 - x).clamp(min=eps) return torch.log(x1/x2) def dice_loss(inputs, targets, num_boxes): """ Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). """ inputs = inputs.sigmoid() inputs = inputs.flatten(1) numerator = 2 * (inputs * targets).sum(1) denominator = inputs.sum(-1) + targets.sum(-1) loss = 1 - (numerator + 1) / (denominator + 1) return loss.sum() / num_boxes def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2, query_mask=None, reduction=True): """ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). alpha: (optional) Weighting factor in range (0,1) to balance positive vs negative examples. Default = -1 (no weighting). gamma: Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. Returns: Loss tensor """ prob = inputs.sigmoid() ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") p_t = prob * targets + (1 - prob) * (1 - targets) loss = ce_loss * ((1 - p_t) ** gamma) if alpha >= 0: alpha_t = alpha * targets + (1 - alpha) * (1 - targets) loss = alpha_t * loss if not reduction: return loss if query_mask is not None: loss = torch.stack([l[m].mean(0) for l, m in zip(loss, query_mask)]) return loss.sum() / num_boxes return loss.mean(1).sum() / num_boxes def nested_dict_to_namespace(dictionary): namespace = dictionary if isinstance(dictionary, dict): namespace = Namespace(**dictionary) for key, value in dictionary.items(): setattr(namespace, key, nested_dict_to_namespace(value)) return namespace def nested_dict_to_device(dictionary, device): output = {} if isinstance(dictionary, dict): for key, value in dictionary.items(): output[key] = nested_dict_to_device(value, device) return output return dictionary.to(device) ================================================ FILE: src/trackformer/util/plot_utils.py ================================================ """ Plotting utilities to visualize training logs. """ from pathlib import Path, PurePath import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas def fig_to_numpy(fig): w, h = fig.get_size_inches() * fig.dpi w = int(w.item()) h = int(h.item()) canvas = FigureCanvas(fig) canvas.draw() numpy_image = np.frombuffer(canvas.tostring_rgb(), dtype='uint8').reshape(h, w, 3) return np.copy(numpy_image) def get_vis_win_names(vis_dict): vis_win_names = { outer_k: { inner_k: inner_v.win for inner_k, inner_v in outer_v.items() } for outer_k, outer_v in vis_dict.items() } return vis_win_names def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'): ''' Function to plot specific fields from training log(s). Plots both training and test results. :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file - fields = which results to plot from each log file - plots both training and test for each field. - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots - log_name = optional, name of log file if different than default 'log.txt'. :: Outputs - matplotlib plots of results in fields, color coded for each log file. - solid lines are training results, dashed lines are test results. ''' func_name = "plot_utils.py::plot_logs" # verify logs is a list of Paths (list[Paths]) or single Pathlib object Path, # convert single Path to list to avoid 'not iterable' error if not isinstance(logs, list): if isinstance(logs, PurePath): logs = [logs] print(f"{func_name} info: logs param expects a list argument, converted to list[Path].") else: raise ValueError(f"{func_name} - invalid argument for logs parameter.\n \ Expect list[Path] or single Path obj, received {type(logs)}") # verify valid dir(s) and that every item in list is Path object for i, dir in enumerate(logs): if not isinstance(dir, PurePath): raise ValueError(f"{func_name} - non-Path object in logs argument of {type(dir)}: \n{dir}") if dir.exists(): continue raise ValueError(f"{func_name} - invalid directory in logs argument:\n{dir}") # load log file(s) and plot dfs = [pd.read_json(Path(p) / log_name, lines=True) for p in logs] fig, axs = plt.subplots(ncols=len(fields), figsize=(16, 5)) for df, color in zip(dfs, sns.color_palette(n_colors=len(logs))): for j, field in enumerate(fields): if field == 'mAP': coco_eval = pd.DataFrame(pd.np.stack(df.test_coco_eval.dropna().values)[:, 1]).ewm(com=ewm_col).mean() axs[j].plot(coco_eval, c=color) else: df.interpolate().ewm(com=ewm_col).mean().plot( y=[f'train_{field}', f'test_{field}'], ax=axs[j], color=[color] * 2, style=['-', '--'] ) for ax, field in zip(axs, fields): ax.legend([Path(p).name for p in logs]) ax.set_title(field) def plot_precision_recall(files, naming_scheme='iter'): if naming_scheme == 'exp_id': # name becomes exp_id names = [f.parts[-3] for f in files] elif naming_scheme == 'iter': names = [f.stem for f in files] else: raise ValueError(f'not supported {naming_scheme}') fig, axs = plt.subplots(ncols=2, figsize=(16, 5)) for f, color, name in zip(files, sns.color_palette("Blues", n_colors=len(files)), names): data = torch.load(f) # precision is n_iou, n_points, n_cat, n_area, max_det precision = data['precision'] recall = data['params'].recThrs scores = data['scores'] # take precision for all classes, all areas and 100 detections precision = precision[0, :, :, 0, -1].mean(1) scores = scores[0, :, :, 0, -1].mean(1) prec = precision.mean() rec = data['recall'][0, :, 0, -1].mean() print(f'{naming_scheme} {name}: mAP@50={prec * 100: 05.1f}, ' + f'score={scores.mean():0.3f}, ' + f'f1={2 * prec * rec / (prec + rec + 1e-8):0.3f}' ) axs[0].plot(recall, precision, c=color) axs[1].plot(recall, scores, c=color) axs[0].set_title('Precision / Recall') axs[0].legend(names) axs[1].set_title('Scores / Recall') axs[1].legend(names) return fig, axs ================================================ FILE: src/trackformer/util/track_utils.py ================================================ ######################################### # Still ugly file with helper functions # ######################################### import os from collections import defaultdict from os import path as osp import cv2 import matplotlib import matplotlib.pyplot as plt import motmetrics as mm import numpy as np import torch import torchvision.transforms.functional as F import tqdm from cycler import cycler as cy from matplotlib import colors from scipy.interpolate import interp1d matplotlib.use('Agg') # From frcnn/utils/bbox.py def bbox_overlaps(boxes, query_boxes): """ Parameters ---------- boxes: (N, 4) ndarray or tensor or variable query_boxes: (K, 4) ndarray or tensor or variable Returns ------- overlaps: (N, K) overlap between boxes and query_boxes """ if isinstance(boxes, np.ndarray): boxes = torch.from_numpy(boxes) query_boxes = torch.from_numpy(query_boxes) out_fn = lambda x: x.numpy() # If input is ndarray, turn the overlaps back to ndarray when return else: out_fn = lambda x: x box_areas = (boxes[:, 2] - boxes[:, 0] + 1) * (boxes[:, 3] - boxes[:, 1] + 1) query_areas = (query_boxes[:, 2] - query_boxes[:, 0] + 1) * (query_boxes[:, 3] - query_boxes[:, 1] + 1) iw = (torch.min(boxes[:, 2:3], query_boxes[:, 2:3].t()) - torch.max(boxes[:, 0:1], query_boxes[:, 0:1].t()) + 1).clamp(min=0) ih = (torch.min(boxes[:, 3:4], query_boxes[:, 3:4].t()) - torch.max(boxes[:, 1:2], query_boxes[:, 1:2].t()) + 1).clamp(min=0) ua = box_areas.view(-1, 1) + query_areas.view(1, -1) - iw * ih overlaps = iw * ih / ua return out_fn(overlaps) def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=False): """ Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks :param nlabels: Number of labels (size of colormap) :param type: 'bright' for strong colors, 'soft' for pastel colors :param first_color_black: Option to use first color as black, True or False :param last_color_black: Option to use last color as black, True or False :param verbose: Prints the number of labels and shows the colormap. True or False :return: colormap for matplotlib """ import colorsys import numpy as np from matplotlib.colors import LinearSegmentedColormap if type not in ('bright', 'soft'): print ('Please choose "bright" or "soft" for type') return if verbose: print('Number of labels: ' + str(nlabels)) # Generate color map for bright colors, based on hsv if type == 'bright': randHSVcolors = [(np.random.uniform(low=0.0, high=1), np.random.uniform(low=0.2, high=1), np.random.uniform(low=0.9, high=1)) for i in range(nlabels)] # Convert HSV list to RGB randRGBcolors = [] for HSVcolor in randHSVcolors: randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2])) if first_color_black: randRGBcolors[0] = [0, 0, 0] if last_color_black: randRGBcolors[-1] = [0, 0, 0] random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) # Generate soft pastel colors, by limiting the RGB spectrum if type == 'soft': low = 0.6 high = 0.95 randRGBcolors = [(np.random.uniform(low=low, high=high), np.random.uniform(low=low, high=high), np.random.uniform(low=low, high=high)) for i in range(nlabels)] if first_color_black: randRGBcolors[0] = [0, 0, 0] if last_color_black: randRGBcolors[-1] = [0, 0, 0] random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) # Display colorbar if verbose: from matplotlib import colorbar, colors from matplotlib import pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(15, 0.5)) bounds = np.linspace(0, nlabels, nlabels + 1) norm = colors.BoundaryNorm(bounds, nlabels) colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None, boundaries=bounds, format='%1i', orientation=u'horizontal') return random_colormap def plot_sequence(tracks, data_loader, output_dir, write_images, generate_attention_maps): """Plots a whole sequence Args: tracks (dict): The dictionary containing the track dictionaries in the form tracks[track_id][frame] = bb db (torch.utils.data.Dataset): The dataset with the images belonging to the tracks (e.g. MOT_Sequence object) output_dir (String): Directory where to save the resulting images """ if not osp.exists(output_dir): os.makedirs(output_dir) # infinite color loop # cyl = cy('ec', COLORS) # loop_cy_iter = cyl() # styles = defaultdict(lambda: next(loop_cy_iter)) # cmap = plt.cm.get_cmap('hsv', ) mx = 0 for track_id, track_data in tracks.items(): mx = max(mx, track_id) cmap = rand_cmap(mx, type='bright', first_color_black=False, last_color_black=False) # if generate_attention_maps: # attention_maps_per_track = { # track_id: (np.concatenate([t['attention_map'] for t in track.values()]) # if len(track) > 1 # else list(track.values())[0]['attention_map']) # for track_id, track in tracks.items()} # attention_map_thresholds = { # track_id: np.histogram(maps, bins=2)[1][1] # for track_id, maps in attention_maps_per_track.items()} # _, attention_maps_bin_edges = np.histogram(all_attention_maps, bins=2) for frame_id, frame_data in enumerate(tqdm.tqdm(data_loader)): img_path = frame_data['img_path'][0] img = cv2.imread(img_path)[:, :, (2, 1, 0)] height, width, _ = img.shape fig = plt.figure() fig.set_size_inches(width / 96, height / 96) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(img) if generate_attention_maps: attention_map_img = np.zeros((height, width, 4)) for track_id, track_data in tracks.items(): if frame_id in track_data.keys(): bbox = track_data[frame_id]['bbox'] if 'mask' in track_data[frame_id]: mask = track_data[frame_id]['mask'] mask = np.ma.masked_where(mask == 0.0, mask) ax.imshow(mask, alpha=0.5, cmap=colors.ListedColormap([cmap(track_id)])) annotate_color = 'white' else: ax.add_patch( plt.Rectangle( (bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, linewidth=2.0, color=cmap(track_id), )) annotate_color = cmap(track_id) if write_images == 'debug': ax.annotate( f"{track_id} - {track_data[frame_id]['obj_ind']} ({track_data[frame_id]['score']:.2f})", (bbox[0] + (bbox[2] - bbox[0]) / 2.0, bbox[1] + (bbox[3] - bbox[1]) / 2.0), color=annotate_color, weight='bold', fontsize=12, ha='center', va='center') if 'attention_map' in track_data[frame_id]: attention_map = track_data[frame_id]['attention_map'] attention_map = cv2.resize(attention_map, (width, height)) # attention_map_img = np.ones((height, width, 4)) * cmap(track_id) # # max value will be at 0.75 transparency # attention_map_img[:, :, 3] = attention_map * 0.75 / attention_map.max() # _, bin_edges = np.histogram(attention_map, bins=2) # attention_map_img[:, :][attention_map < bin_edges[1]] = 0.0 # attention_map_img += attention_map_img # _, bin_edges = np.histogram(attention_map, bins=2) norm_attention_map = attention_map / attention_map.max() high_att_mask = norm_attention_map > 0.25 # bin_edges[1] attention_map_img[:, :][high_att_mask] = cmap(track_id) attention_map_img[:, :, 3][high_att_mask] = norm_attention_map[high_att_mask] * 0.5 # attention_map_img[:, :] += (np.tile(attention_map[..., np.newaxis], (1,1,4)) / attention_map.max()) * cmap(track_id) # attention_map_img[:, :, 3] = 0.75 if generate_attention_maps: ax.imshow(attention_map_img, vmin=0.0, vmax=1.0) plt.axis('off') # plt.tight_layout() plt.draw() plt.savefig(osp.join(output_dir, osp.basename(img_path)), dpi=96) plt.close() def interpolate_tracks(tracks): for i, track in tracks.items(): frames = [] x0 = [] y0 = [] x1 = [] y1 = [] for f, data in track.items(): frames.append(f) x0.append(data['bbox'][0]) y0.append(data['bbox'][1]) x1.append(data['bbox'][2]) y1.append(data['bbox'][3]) if frames: x0_inter = interp1d(frames, x0) y0_inter = interp1d(frames, y0) x1_inter = interp1d(frames, x1) y1_inter = interp1d(frames, y1) for f in range(min(frames), max(frames) + 1): bbox = np.array([ x0_inter(f), y0_inter(f), x1_inter(f), y1_inter(f)]) tracks[i][f]['bbox'] = bbox else: tracks[i][frames[0]]['bbox'] = np.array([ x0[0], y0[0], x1[0], y1[0]]) return interpolated def bbox_transform_inv(boxes, deltas): # Input should be both tensor or both Variable and on the same device if len(boxes) == 0: return deltas.detach() * 0 widths = boxes[:, 2] - boxes[:, 0] + 1.0 heights = boxes[:, 3] - boxes[:, 1] + 1.0 ctr_x = boxes[:, 0] + 0.5 * widths ctr_y = boxes[:, 1] + 0.5 * heights dx = deltas[:, 0::4] dy = deltas[:, 1::4] dw = deltas[:, 2::4] dh = deltas[:, 3::4] pred_ctr_x = dx * widths.unsqueeze(1) + ctr_x.unsqueeze(1) pred_ctr_y = dy * heights.unsqueeze(1) + ctr_y.unsqueeze(1) pred_w = torch.exp(dw) * widths.unsqueeze(1) pred_h = torch.exp(dh) * heights.unsqueeze(1) pred_boxes = torch.cat( [_.unsqueeze(2) for _ in [pred_ctr_x - 0.5 * pred_w, pred_ctr_y - 0.5 * pred_h, pred_ctr_x + 0.5 * pred_w, pred_ctr_y + 0.5 * pred_h]], 2).view(len(boxes), -1) return pred_boxes def clip_boxes(boxes, im_shape): """ Clip boxes to image boundaries. boxes must be tensor or Variable, im_shape can be anything but Variable """ if not hasattr(boxes, 'data'): boxes_ = boxes.numpy() boxes = boxes.view(boxes.size(0), -1, 4) boxes = torch.stack([ boxes[:, :, 0].clamp(0, im_shape[1] - 1), boxes[:, :, 1].clamp(0, im_shape[0] - 1), boxes[:, :, 2].clamp(0, im_shape[1] - 1), boxes[:, :, 3].clamp(0, im_shape[0] - 1) ], 2).view(boxes.size(0), -1) return boxes def get_center(pos): x1 = pos[0, 0] y1 = pos[0, 1] x2 = pos[0, 2] y2 = pos[0, 3] return torch.Tensor([(x2 + x1) / 2, (y2 + y1) / 2]).cuda() def get_width(pos): return pos[0, 2] - pos[0, 0] def get_height(pos): return pos[0, 3] - pos[0, 1] def make_pos(cx, cy, width, height): return torch.Tensor([[ cx - width / 2, cy - height / 2, cx + width / 2, cy + height / 2 ]]).cuda() def warp_pos(pos, warp_matrix): p1 = torch.Tensor([pos[0, 0], pos[0, 1], 1]).view(3, 1) p2 = torch.Tensor([pos[0, 2], pos[0, 3], 1]).view(3, 1) p1_n = torch.mm(warp_matrix, p1).view(1, 2) p2_n = torch.mm(warp_matrix, p2).view(1, 2) return torch.cat((p1_n, p2_n), 1).view(1, -1).cuda() def get_mot_accum(results, seq_loader): mot_accum = mm.MOTAccumulator(auto_id=True) for frame_id, frame_data in enumerate(seq_loader): gt = frame_data['gt'] gt_ids = [] if gt: gt_boxes = [] for gt_id, gt_box in gt.items(): gt_ids.append(gt_id) gt_boxes.append(gt_box[0]) gt_boxes = np.stack(gt_boxes, axis=0) # x1, y1, x2, y2 --> x1, y1, width, height gt_boxes = np.stack( (gt_boxes[:, 0], gt_boxes[:, 1], gt_boxes[:, 2] - gt_boxes[:, 0], gt_boxes[:, 3] - gt_boxes[:, 1]), axis=1) else: gt_boxes = np.array([]) track_ids = [] track_boxes = [] for track_id, track_data in results.items(): if frame_id in track_data: track_ids.append(track_id) # frames = x1, y1, x2, y2, score track_boxes.append(track_data[frame_id]['bbox']) if track_ids: track_boxes = np.stack(track_boxes, axis=0) # x1, y1, x2, y2 --> x1, y1, width, height track_boxes = np.stack( (track_boxes[:, 0], track_boxes[:, 1], track_boxes[:, 2] - track_boxes[:, 0], track_boxes[:, 3] - track_boxes[:, 1]), axis=1) else: track_boxes = np.array([]) distance = mm.distances.iou_matrix(gt_boxes, track_boxes, max_iou=0.5) mot_accum.update( gt_ids, track_ids, distance) return mot_accum def evaluate_mot_accums(accums, names, generate_overall=True): mh = mm.metrics.create() summary = mh.compute_many( accums, metrics=mm.metrics.motchallenge_metrics, names=names, generate_overall=generate_overall,) str_summary = mm.io.render_summary( summary, formatters=mh.formatters, namemap=mm.io.motchallenge_metric_names,) return summary, str_summary ================================================ FILE: src/trackformer/vis.py ================================================ import copy import logging import matplotlib.patches as mpatches import numpy as np import torch import torchvision.transforms as T from matplotlib import colors from matplotlib import pyplot as plt from torchvision.ops.boxes import clip_boxes_to_image from visdom import Visdom from .util.plot_utils import fig_to_numpy logging.getLogger('visdom').setLevel(logging.CRITICAL) class BaseVis(object): def __init__(self, viz_opts, update_mode='append', env=None, win=None, resume=False, port=8097, server='http://localhost'): self.viz_opts = viz_opts self.update_mode = update_mode self.win = win if env is None: env = 'main' self.viz = Visdom(env=env, port=port, server=server) # if resume first plot should not update with replace self.removed = not resume def win_exists(self): return self.viz.win_exists(self.win) def close(self): if self.win is not None: self.viz.close(win=self.win) self.win = None def register_event_handler(self, handler): self.viz.register_event_handler(handler, self.win) class LineVis(BaseVis): """Visdom Line Visualization Helper Class.""" def plot(self, y_data, x_label): """Plot given data. Appends new data to exisiting line visualization. """ update = self.update_mode # update mode must be None the first time or after plot data was removed if self.removed: update = None self.removed = False if isinstance(x_label, list): Y = torch.Tensor(y_data) X = torch.Tensor(x_label) else: y_data = [d.cpu() if torch.is_tensor(d) else torch.tensor(d) for d in y_data] Y = torch.Tensor(y_data).unsqueeze(dim=0) X = torch.Tensor([x_label]) win = self.viz.line(X=X, Y=Y, opts=self.viz_opts, win=self.win, update=update) if self.win is None: self.win = win self.viz.save([self.viz.env]) def reset(self): #TODO: currently reset does not empty directly only on the next plot. # update='remove' is not working as expected. if self.win is not None: # self.viz.line(X=None, Y=None, win=self.win, update='remove') self.removed = True class ImgVis(BaseVis): """Visdom Image Visualization Helper Class.""" def plot(self, images): """Plot given images.""" # images = [img.data if isinstance(img, torch.autograd.Variable) # else img for img in images] # images = [img.squeeze(dim=0) if len(img.size()) == 4 # else img for img in images] self.win = self.viz.images( images, nrow=1, opts=self.viz_opts, win=self.win, ) self.viz.save([self.viz.env]) def vis_results(visualizer, img, result, target, tracking): inv_normalize = T.Normalize( mean=[-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.255], std=[1 / 0.229, 1 / 0.224, 1 / 0.255] ) imgs = [inv_normalize(img).cpu()] img_ids = [target['image_id'].item()] for key in ['prev', 'prev_prev']: if f'{key}_image' in target: imgs.append(inv_normalize(target[f'{key}_image']).cpu()) img_ids.append(target[f'{key}_target'][f'image_id'].item()) # img.shape=[3, H, W] dpi = 96 figure, axarr = plt.subplots(len(imgs)) figure.tight_layout() figure.set_dpi(dpi) figure.set_size_inches( imgs[0].shape[2] / dpi, imgs[0].shape[1] * len(imgs) / dpi) if len(imgs) == 1: axarr = [axarr] for ax, img, img_id in zip(axarr, imgs, img_ids): ax.set_axis_off() ax.imshow(img.permute(1, 2, 0).clamp(0, 1)) ax.text( 0, 0, f'IMG_ID={img_id}', fontsize=20, bbox=dict(facecolor='white', alpha=0.5)) num_track_queries = num_track_queries_with_id = 0 if tracking: num_track_queries = len(target['track_query_boxes']) num_track_queries_with_id = len(target['track_query_match_ids']) track_ids = target['track_ids'][target['track_query_match_ids']] keep = result['scores'].cpu() > result['scores_no_object'].cpu() cmap = plt.cm.get_cmap('hsv', len(keep)) prop_i = 0 for box_id in range(len(keep)): rect_color = 'green' offset = 0 text = f"{result['scores'][box_id]:0.2f}" if tracking: if target['track_queries_fal_pos_mask'][box_id]: rect_color = 'red' elif target['track_queries_mask'][box_id]: offset = 50 rect_color = 'blue' text = ( f"{track_ids[prop_i]}\n" f"{text}\n" f"{result['track_queries_with_id_iou'][prop_i]:0.2f}") prop_i += 1 if not keep[box_id]: continue # x1, y1, x2, y2 = result['boxes'][box_id] result_boxes = clip_boxes_to_image(result['boxes'], target['size']) x1, y1, x2, y2 = result_boxes[box_id] axarr[0].add_patch(plt.Rectangle( (x1, y1), x2 - x1, y2 - y1, fill=False, color=rect_color, linewidth=2)) axarr[0].text( x1, y1 + offset, text, fontsize=10, bbox=dict(facecolor='white', alpha=0.5)) if 'masks' in result: mask = result['masks'][box_id][0].numpy() mask = np.ma.masked_where(mask == 0.0, mask) axarr[0].imshow( mask, alpha=0.5, cmap=colors.ListedColormap([cmap(box_id)])) query_keep = keep if tracking: query_keep = keep[target['track_queries_mask'] == 0] legend_handles = [mpatches.Patch( color='green', label=f"object queries ({query_keep.sum()}/{len(target['boxes']) - num_track_queries_with_id})\n- cls_score")] if num_track_queries: track_queries_label = ( f"track queries ({keep[target['track_queries_mask']].sum() - keep[target['track_queries_fal_pos_mask']].sum()}" f"/{num_track_queries_with_id})\n- track_id\n- cls_score\n- iou") legend_handles.append(mpatches.Patch( color='blue', label=track_queries_label)) if num_track_queries_with_id != num_track_queries: track_queries_fal_pos_label = ( f"false track queries ({keep[target['track_queries_fal_pos_mask']].sum()}" f"/{num_track_queries - num_track_queries_with_id})") legend_handles.append(mpatches.Patch( color='red', label=track_queries_fal_pos_label)) axarr[0].legend(handles=legend_handles) i = 1 for frame_prefix in ['prev', 'prev_prev']: # if f'{frame_prefix}_image_id' not in target or f'{frame_prefix}_boxes' not in target: if f'{frame_prefix}_target' not in target: continue frame_target = target[f'{frame_prefix}_target'] cmap = plt.cm.get_cmap('hsv', len(frame_target['track_ids'])) for j, track_id in enumerate(frame_target['track_ids']): x1, y1, x2, y2 = frame_target['boxes'][j] axarr[i].text( x1, y1, f"track_id={track_id}", fontsize=10, bbox=dict(facecolor='white', alpha=0.5)) axarr[i].add_patch(plt.Rectangle( (x1, y1), x2 - x1, y2 - y1, fill=False, color='green', linewidth=2)) if 'masks' in frame_target: mask = frame_target['masks'][j].cpu().numpy() mask = np.ma.masked_where(mask == 0.0, mask) axarr[i].imshow( mask, alpha=0.5, cmap=colors.ListedColormap([cmap(j)])) i += 1 plt.subplots_adjust(wspace=0.01, hspace=0.01) plt.axis('off') img = fig_to_numpy(figure).transpose(2, 0, 1) plt.close() visualizer.plot(img) def build_visualizers(args: dict, train_loss_names: list): visualizers = {} visualizers['train'] = {} visualizers['val'] = {} if args.eval_only or args.no_vis or not args.vis_server: return visualizers env_name = str(args.output_dir).split('/')[-1] vis_kwargs = { 'env': env_name, 'resume': args.resume and args.resume_vis, 'port': args.vis_port, 'server': args.vis_server} # # METRICS # legend = ['loss'] legend.extend(train_loss_names) # for i in range(len(train_loss_names)): # legend.append(f"{train_loss_names[i]}_unscaled") legend.extend([ 'class_error', # 'loss', # 'loss_bbox', # 'loss_ce', # 'loss_giou', # 'loss_mask', # 'loss_dice', # 'cardinality_error_unscaled', # 'loss_bbox_unscaled', # 'loss_ce_unscaled', # 'loss_giou_unscaled', # 'loss_mask_unscaled', # 'loss_dice_unscaled', 'lr', 'lr_backbone', 'iter_time' ]) # if not args.masks: # legend.remove('loss_mask') # legend.remove('loss_mask_unscaled') # legend.remove('loss_dice') # legend.remove('loss_dice_unscaled') opts = dict( title="TRAIN METRICS ITERS", xlabel='ITERS', ylabel='METRICS', width=1000, height=500, legend=legend) # TRAIN visualizers['train']['iter_metrics'] = LineVis(opts, **vis_kwargs) opts = copy.deepcopy(opts) opts['title'] = "TRAIN METRICS EPOCHS" opts['xlabel'] = "EPOCHS" opts['legend'].remove('lr') opts['legend'].remove('lr_backbone') opts['legend'].remove('iter_time') visualizers['train']['epoch_metrics'] = LineVis(opts, **vis_kwargs) # VAL opts = copy.deepcopy(opts) opts['title'] = "VAL METRICS EPOCHS" opts['xlabel'] = "EPOCHS" visualizers['val']['epoch_metrics'] = LineVis(opts, **vis_kwargs) # # EVAL COCO # legend = [ 'BBOX AP IoU=0.50:0.95', 'BBOX AP IoU=0.50', 'BBOX AP IoU=0.75', ] if args.masks: legend.extend([ 'MASK AP IoU=0.50:0.95', 'MASK AP IoU=0.50', 'MASK AP IoU=0.75']) if args.tracking and args.tracking_eval: legend.extend(['MOTA', 'IDF1']) opts = dict( title='TRAIN EVAL EPOCHS', xlabel='EPOCHS', ylabel='METRICS', width=1000, height=500, legend=legend) # TRAIN visualizers['train']['epoch_eval'] = LineVis(opts, **vis_kwargs) # VAL opts = copy.deepcopy(opts) opts['title'] = 'VAL EVAL EPOCHS' visualizers['val']['epoch_eval'] = LineVis(opts, **vis_kwargs) # # EXAMPLE RESULTS # opts = dict( title="TRAIN EXAMPLE RESULTS", width=2500, height=2500) # TRAIN visualizers['train']['example_results'] = ImgVis(opts, **vis_kwargs) # VAL opts = copy.deepcopy(opts) opts['title'] = 'VAL EXAMPLE RESULTS' visualizers['val']['example_results'] = ImgVis(opts, **vis_kwargs) return visualizers ================================================ FILE: src/train.py ================================================ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import datetime import os import random import time from argparse import Namespace from pathlib import Path import numpy as np import sacred import torch import yaml from torch.utils.data import DataLoader, DistributedSampler import trackformer.util.misc as utils from trackformer.datasets import build_dataset from trackformer.engine import evaluate, train_one_epoch from trackformer.models import build_model from trackformer.util.misc import nested_dict_to_namespace from trackformer.util.plot_utils import get_vis_win_names from trackformer.vis import build_visualizers ex = sacred.Experiment('train') ex.add_config('cfgs/train.yaml') ex.add_named_config('deformable', 'cfgs/train_deformable.yaml') ex.add_named_config('tracking', 'cfgs/train_tracking.yaml') ex.add_named_config('crowdhuman', 'cfgs/train_crowdhuman.yaml') ex.add_named_config('mot_coco_person', 'cfgs/train_mot_coco_person.yaml') ex.add_named_config('mot17_crowdhuman', 'cfgs/train_mot17_crowdhuman.yaml') ex.add_named_config('mot17', 'cfgs/train_mot17.yaml') ex.add_named_config('mots20', 'cfgs/train_mots20.yaml') ex.add_named_config('mot20_crowdhuman', 'cfgs/train_mot20_crowdhuman.yaml') ex.add_named_config('coco_person_masks', 'cfgs/train_coco_person_masks.yaml') ex.add_named_config('full_res', 'cfgs/train_full_res.yaml') ex.add_named_config('multi_frame', 'cfgs/train_multi_frame.yaml') def train(args: Namespace) -> None: print(args) utils.init_distributed_mode(args) print("git:\n {}\n".format(utils.get_sha())) if args.debug: # args.tracking_eval = False args.num_workers = 0 if not args.deformable: assert args.num_feature_levels == 1 if args.tracking: # assert args.batch_size == 1 if args.tracking_eval: assert 'mot' in args.dataset output_dir = Path(args.output_dir) if args.output_dir: output_dir.mkdir(parents=True, exist_ok=True) yaml.dump( vars(args), open(output_dir / 'config.yaml', 'w'), allow_unicode=True) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + utils.get_rank() os.environ['PYTHONHASHSEED'] = str(seed) # os.environ['NCCL_DEBUG'] = 'INFO' # os.environ["NCCL_TREE_THRESHOLD"] = "0" np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True model, criterion, postprocessors = build_model(args) model.to(device) visualizers = build_visualizers(args, list(criterion.weight_dict.keys())) model_without_ddp = model if args.distributed: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[args.gpu], find_unused_parameters=True) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print('NUM TRAINABLE MODEL PARAMS:', n_parameters) def match_name_keywords(n, name_keywords): out = False for b in name_keywords: if b in n: out = True break return out param_dicts = [ {"params": [p for n, p in model_without_ddp.named_parameters() if not match_name_keywords(n, args.lr_backbone_names + args.lr_linear_proj_names + ['layers_track_attention']) and p.requires_grad], "lr": args.lr,}, {"params": [p for n, p in model_without_ddp.named_parameters() if match_name_keywords(n, args.lr_backbone_names) and p.requires_grad], "lr": args.lr_backbone}, {"params": [p for n, p in model_without_ddp.named_parameters() if match_name_keywords(n, args.lr_linear_proj_names) and p.requires_grad], "lr": args.lr * args.lr_linear_proj_mult}] if args.track_attention: param_dicts.append({ "params": [p for n, p in model_without_ddp.named_parameters() if match_name_keywords(n, ['layers_track_attention']) and p.requires_grad], "lr": args.lr_track}) optimizer = torch.optim.AdamW(param_dicts, lr=args.lr, weight_decay=args.weight_decay) lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [args.lr_drop]) dataset_train = build_dataset(split='train', args=args) dataset_val = build_dataset(split='val', args=args) if args.distributed: sampler_train = utils.DistributedWeightedSampler(dataset_train) # sampler_train = DistributedSampler(dataset_train) sampler_val = DistributedSampler(dataset_val, shuffle=False) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) batch_sampler_train = torch.utils.data.BatchSampler( sampler_train, args.batch_size, drop_last=True) data_loader_train = DataLoader( dataset_train, batch_sampler=batch_sampler_train, collate_fn=utils.collate_fn, num_workers=args.num_workers) data_loader_val = DataLoader( dataset_val, args.batch_size, sampler=sampler_val, drop_last=False, collate_fn=utils.collate_fn, num_workers=args.num_workers) best_val_stats = None if args.resume: if args.resume.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( args.resume, map_location='cpu', check_hash=True) else: checkpoint = torch.load(args.resume, map_location='cpu') model_state_dict = model_without_ddp.state_dict() checkpoint_state_dict = checkpoint['model'] checkpoint_state_dict = { k.replace('detr.', ''): v for k, v in checkpoint['model'].items()} for k, v in checkpoint_state_dict.items(): if k not in model_state_dict: print(f'Where is {k} {tuple(v.shape)}?') resume_state_dict = {} for k, v in model_state_dict.items(): if k not in checkpoint_state_dict: resume_value = v print(f'Load {k} {tuple(v.shape)} from scratch.') elif v.shape != checkpoint_state_dict[k].shape: checkpoint_value = checkpoint_state_dict[k] num_dims = len(checkpoint_value.shape) if 'norm' in k: resume_value = checkpoint_value.repeat(2) elif 'multihead_attn' in k or 'self_attn' in k: resume_value = checkpoint_value.repeat(num_dims * (2, )) elif 'reference_points' in k and checkpoint_value.shape[0] * 2 == v.shape[0]: resume_value = v resume_value[:2] = checkpoint_value.clone() elif 'linear1' in k or 'query_embed' in k: resume_state_dict[k] = v print(f'Load {k} {tuple(v.shape)} from scratch.') continue # if checkpoint_value.shape[1] * 2 == v.shape[1]: # # from hidden size 256 to 512 # resume_value = checkpoint_value.repeat(1, 2) # elif checkpoint_value.shape[0] * 5 == v.shape[0]: # # from 100 to 500 object queries # resume_value = checkpoint_value.repeat(5, 1) # elif checkpoint_value.shape[0] > v.shape[0]: # resume_value = checkpoint_value[:v.shape[0]] # elif checkpoint_value.shape[0] < v.shape[0]: # resume_value = v # else: # raise NotImplementedError elif 'linear2' in k or 'input_proj' in k: resume_value = checkpoint_value.repeat((2,) + (num_dims - 1) * (1, )) elif 'class_embed' in k: # person and no-object class # resume_value = checkpoint_value[[1, -1]] # resume_value = checkpoint_value[[0, -1]] # resume_value = checkpoint_value[[1,]] resume_value = checkpoint_value[list(range(0, 20))] # resume_value = v # print(f'Load {k} {tuple(v.shape)} from scratch.') else: raise NotImplementedError(f"No rule for {k} with shape {v.shape}.") print(f"Load {k} {tuple(v.shape)} from resume model " f"{tuple(checkpoint_value.shape)}.") elif args.resume_shift_neuron and 'class_embed' in k: checkpoint_value = checkpoint_state_dict[k] # no-object class resume_value = checkpoint_value.clone() # no-object class # resume_value[:-2] = checkpoint_value[1:-1].clone() resume_value[:-1] = checkpoint_value[1:].clone() resume_value[-2] = checkpoint_value[0].clone() print(f"Load {k} {tuple(v.shape)} from resume model and " "shift class embed neurons to start with label=0 at neuron=0.") else: resume_value = checkpoint_state_dict[k] resume_state_dict[k] = resume_value if args.masks and args.load_mask_head_from_model is not None: checkpoint_mask_head = torch.load( args.load_mask_head_from_model, map_location='cpu') for k, v in resume_state_dict.items(): if (('bbox_attention' in k or 'mask_head' in k) and v.shape == checkpoint_mask_head['model'][k].shape): print(f'Load {k} {tuple(v.shape)} from mask head model.') resume_state_dict[k] = checkpoint_mask_head['model'][k] model_without_ddp.load_state_dict(resume_state_dict) # RESUME OPTIM if not args.eval_only and args.resume_optim: if 'optimizer' in checkpoint: if args.overwrite_lrs: for c_p, p in zip(checkpoint['optimizer']['param_groups'], param_dicts): c_p['lr'] = p['lr'] optimizer.load_state_dict(checkpoint['optimizer']) if 'lr_scheduler' in checkpoint: if args.overwrite_lr_scheduler: checkpoint['lr_scheduler'].pop('milestones') lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) if args.overwrite_lr_scheduler: lr_scheduler.step(checkpoint['lr_scheduler']['last_epoch']) if 'epoch' in checkpoint: args.start_epoch = checkpoint['epoch'] + 1 print(f"RESUME EPOCH: {args.start_epoch}") best_val_stats = checkpoint['best_val_stats'] # RESUME VIS if not args.eval_only and args.resume_vis and 'vis_win_names' in checkpoint: for k, v in visualizers.items(): for k_inner in v.keys(): visualizers[k][k_inner].win = checkpoint['vis_win_names'][k][k_inner] if args.eval_only: _, coco_evaluator = evaluate( model, criterion, postprocessors, data_loader_val, device, output_dir, visualizers['val'], args, 0) if args.output_dir: utils.save_on_master(coco_evaluator.coco_eval["bbox"].eval, output_dir / "eval.pth") return print("Start training") start_time = time.time() for epoch in range(args.start_epoch, args.epochs + 1): # TRAIN if args.distributed: sampler_train.set_epoch(epoch) train_one_epoch( model, criterion, postprocessors, data_loader_train, optimizer, device, epoch, visualizers['train'], args) if args.eval_train: random_transforms = data_loader_train.dataset._transforms data_loader_train.dataset._transforms = data_loader_val.dataset._transforms evaluate( model, criterion, postprocessors, data_loader_train, device, output_dir, visualizers['train'], args, epoch) data_loader_train.dataset._transforms = random_transforms lr_scheduler.step() checkpoint_paths = [output_dir / 'checkpoint.pth'] # VAL if epoch == 1 or not epoch % args.val_interval: val_stats, _ = evaluate( model, criterion, postprocessors, data_loader_val, device, output_dir, visualizers['val'], args, epoch) checkpoint_paths = [output_dir / 'checkpoint.pth'] # extra checkpoint before LR drop and every 100 epochs # if (epoch + 1) % args.lr_drop == 0 or (epoch + 1) % 10 == 0: # checkpoint_paths.append(output_dir / f'checkpoint{epoch:04}.pth') # checkpoint for best validation stats stat_names = ['BBOX_AP_IoU_0_50-0_95', 'BBOX_AP_IoU_0_50', 'BBOX_AP_IoU_0_75'] if args.masks: stat_names.extend(['MASK_AP_IoU_0_50-0_95', 'MASK_AP_IoU_0_50', 'MASK_AP_IoU_0_75']) if args.tracking and args.tracking_eval: stat_names.extend(['MOTA', 'IDF1']) if best_val_stats is None: best_val_stats = val_stats best_val_stats = [best_stat if best_stat > stat else stat for best_stat, stat in zip(best_val_stats, val_stats)] for b_s, s, n in zip(best_val_stats, val_stats, stat_names): if b_s == s: checkpoint_paths.append(output_dir / f"checkpoint_best_{n}.pth") # MODEL SAVING if args.output_dir: if args.save_model_interval and not epoch % args.save_model_interval: checkpoint_paths.append(output_dir / f"checkpoint_epoch_{epoch}.pth") for checkpoint_path in checkpoint_paths: utils.save_on_master({ 'model': model_without_ddp.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict(), 'epoch': epoch, 'args': args, 'vis_win_names': get_vis_win_names(visualizers), 'best_val_stats': best_val_stats }, checkpoint_path) total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) @ex.main def load_config(_config, _run): """ We use sacred only for config loading from YAML files. """ sacred.commands.print_config(_run) if __name__ == '__main__': # TODO: hierachical Namespacing for nested dict config = ex.run_commandline().config args = nested_dict_to_namespace(config) # args.train = Namespace(**config['train']) train(args)