├── tox.ini ├── util ├── __init__.py ├── box_ops.py ├── plot_utils.py └── misc.py ├── models ├── __init__.py ├── position_encoding.py ├── backbone.py ├── matcher.py ├── segmentation.py └── transformer.py ├── d2 ├── detr │ ├── __init__.py │ ├── config.py │ ├── dataset_mapper.py │ └── detr.py ├── configs │ ├── detr_256_6_6_torchvision.yaml │ └── detr_segm_256_6_6_torchvision.yaml ├── README.md ├── converter.py └── train_net.py ├── requirements.txt ├── .gitignore ├── 网络结构.txt ├── datasets ├── __init__.py ├── panoptic_eval.py ├── coco_panoptic.py ├── coco.py ├── transforms.py └── coco_eval.py ├── 源码结构.md ├── loss内容.md ├── hubconf.py ├── engine.py ├── test_all.py ├── LICENSE ├── README.md └── main.py /tox.ini: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 120 3 | ignore = F401,E402,F403,W503,W504 4 | -------------------------------------------------------------------------------- /util/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | from .detr import build 3 | 4 | 5 | def build_model(args): 6 | return build(args) 7 | -------------------------------------------------------------------------------- /d2/detr/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | from .config import add_detr_config 3 | from .detr import Detr 4 | from .dataset_mapper import DetrDatasetMapper 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cython 2 | git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI&egg=pycocotools 3 | submitit 4 | torch>=1.5.0 5 | torchvision>=0.6.0 6 | git+https://github.com/cocodataset/panopticapi.git#egg=panopticapi 7 | scipy 8 | onnx 9 | onnxruntime 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .nfs* 2 | *.ipynb 3 | *.pyc 4 | .dumbo.json 5 | .DS_Store 6 | .*.swp 7 | *.pth 8 | **/__pycache__/** 9 | .ipynb_checkpoints/ 10 | datasets/data/ 11 | experiment-* 12 | *.tmp 13 | *.pkl 14 | **/.mypy_cache/* 15 | .mypy_cache/* 16 | not_tracked_dir/ 17 | .vscode 18 | 19 | .idea 20 | -------------------------------------------------------------------------------- /网络结构.txt: -------------------------------------------------------------------------------- 1 | 2 | 其他的部分是6个encoder,6个decoder,以及backbone部分 3 | 4 | (class_embed): Linear(in_features=256, out_features=81, bias=True) 5 | (bbox_embed): MLP( 6 | (layers): ModuleList( 7 | (0): Linear(in_features=256, out_features=256, bias=True) 8 | (1): Linear(in_features=256, out_features=256, bias=True) 9 | (2): Linear(in_features=256, out_features=4, bias=True) 10 | ) 11 | ) 12 | (query_embed): Embedding(100, 256) 13 | (input_proj): Conv2d(2048, 256, kernel_size=(1, 1), stride=(1, 1)) 14 | 15 | 16 | -------------------------------------------------------------------------------- /datasets/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import torch.utils.data 3 | import torchvision 4 | 5 | from .coco import build as build_coco 6 | 7 | 8 | def get_coco_api_from_dataset(dataset): 9 | # 找到套娃内的dataset 10 | for _ in range(10): 11 | if isinstance(dataset, torch.utils.data.Subset): 12 | dataset = dataset.dataset 13 | 14 | if isinstance(dataset, torchvision.datasets.CocoDetection): 15 | return dataset.coco 16 | 17 | 18 | def build_dataset(image_set, args): 19 | # coco 目标检测,以及coco的全景分割 20 | if args.dataset_file == 'coco': 21 | return build_coco(image_set, args) 22 | if args.dataset_file == 'coco_panoptic': 23 | # to avoid making panopticapi required for coco 24 | from .coco_panoptic import build as build_coco_panoptic 25 | return build_coco_panoptic(image_set, args) 26 | raise ValueError(f'dataset {args.dataset_file} not supported') 27 | -------------------------------------------------------------------------------- /d2/detr/config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 3 | from detectron2.config import CfgNode as CN 4 | 5 | 6 | def add_detr_config(cfg): 7 | """ 8 | Add config for DETR. 9 | """ 10 | cfg.MODEL.DETR = CN() 11 | cfg.MODEL.DETR.NUM_CLASSES = 80 12 | 13 | # For Segmentation 14 | cfg.MODEL.DETR.FROZEN_WEIGHTS = '' 15 | 16 | # LOSS 17 | cfg.MODEL.DETR.GIOU_WEIGHT = 2.0 18 | cfg.MODEL.DETR.L1_WEIGHT = 5.0 19 | 20 | cfg.MODEL.DETR.DEEP_SUPERVISION = True 21 | cfg.MODEL.DETR.NO_OBJECT_WEIGHT = 0.1 22 | 23 | # TRANSFORMER 24 | cfg.MODEL.DETR.NHEADS = 8 25 | cfg.MODEL.DETR.DROPOUT = 0.1 26 | # cnn之后的特征的尺寸 27 | cfg.MODEL.DETR.DIM_FEEDFORWARD = 2048 28 | # 编码层的层数 29 | cfg.MODEL.DETR.ENC_LAYERS = 6 30 | # 解码层的层数 31 | cfg.MODEL.DETR.DEC_LAYERS = 6 32 | cfg.MODEL.DETR.PRE_NORM = False 33 | # encoder,decoder内的维度 34 | cfg.MODEL.DETR.HIDDEN_DIM = 256 35 | # 最多预测100个 36 | cfg.MODEL.DETR.NUM_OBJECT_QUERIES = 100 37 | 38 | cfg.SOLVER.OPTIMIZER = "ADAMW" 39 | cfg.SOLVER.BACKBONE_MULTIPLIER = 0.1 40 | -------------------------------------------------------------------------------- /d2/configs/detr_256_6_6_torchvision.yaml: -------------------------------------------------------------------------------- 1 | MODEL: 2 | META_ARCHITECTURE: "Detr" 3 | WEIGHTS: "detectron2://ImageNetPretrained/torchvision/R-50.pkl" 4 | PIXEL_MEAN: [ 123.675, 116.280, 103.530 ] 5 | PIXEL_STD: [ 58.395, 57.120, 57.375 ] 6 | MASK_ON: False 7 | RESNETS: 8 | DEPTH: 50 9 | STRIDE_IN_1X1: False 10 | OUT_FEATURES: [ "res2", "res3", "res4", "res5" ] 11 | DETR: 12 | GIOU_WEIGHT: 2.0 13 | L1_WEIGHT: 5.0 14 | NUM_OBJECT_QUERIES: 100 15 | DATASETS: 16 | TRAIN: ("coco_2017_train",) 17 | TEST: ("coco_2017_val",) 18 | SOLVER: 19 | IMS_PER_BATCH: 3 20 | BASE_LR: 0.0001 21 | STEPS: (369600,) 22 | #Faster R-CNN+ 3x的轮次 23 | MAX_ITER: 554400 24 | WARMUP_FACTOR: 1.0 25 | WARMUP_ITERS: 10 26 | WEIGHT_DECAY: 0.0001 27 | OPTIMIZER: "ADAMW" 28 | BACKBONE_MULTIPLIER: 0.1 29 | CLIP_GRADIENTS: 30 | ENABLED: True 31 | CLIP_TYPE: "full_model" 32 | CLIP_VALUE: 0.01 33 | NORM_TYPE: 2.0 34 | INPUT: 35 | MIN_SIZE_TRAIN: (480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800) 36 | CROP: 37 | ENABLED: True 38 | TYPE: "absolute_range" 39 | SIZE: (384, 600) 40 | FORMAT: "RGB" 41 | TEST: 42 | # 每隔4000执行一下测试 43 | EVAL_PERIOD: 4000 44 | DATALOADER: 45 | FILTER_EMPTY_ANNOTATIONS: False 46 | NUM_WORKERS: 4 47 | VERSION: 2 48 | -------------------------------------------------------------------------------- /d2/configs/detr_segm_256_6_6_torchvision.yaml: -------------------------------------------------------------------------------- 1 | # 分割任务 2 | MODEL: 3 | META_ARCHITECTURE: "Detr" 4 | # WEIGHTS: "detectron2://ImageNetPretrained/torchvision/R-50.pkl" 5 | PIXEL_MEAN: [ 123.675, 116.280, 103.530 ] 6 | PIXEL_STD: [ 58.395, 57.120, 57.375 ] 7 | MASK_ON: True 8 | RESNETS: 9 | DEPTH: 50 10 | STRIDE_IN_1X1: False 11 | OUT_FEATURES: [ "res2", "res3", "res4", "res5" ] 12 | DETR: 13 | GIOU_WEIGHT: 2.0 14 | L1_WEIGHT: 5.0 15 | NUM_OBJECT_QUERIES: 100 16 | FROZEN_WEIGHTS: '' 17 | DATASETS: 18 | TRAIN: ("coco_2017_train",) 19 | TEST: ("coco_2017_val",) 20 | SOLVER: 21 | IMS_PER_BATCH: 64 22 | BASE_LR: 0.0001 23 | STEPS: (55440,) 24 | MAX_ITER: 92400 25 | WARMUP_FACTOR: 1.0 26 | WARMUP_ITERS: 10 27 | WEIGHT_DECAY: 0.0001 28 | OPTIMIZER: "ADAMW" 29 | BACKBONE_MULTIPLIER: 0.1 30 | CLIP_GRADIENTS: 31 | ENABLED: True 32 | CLIP_TYPE: "full_model" 33 | CLIP_VALUE: 0.01 34 | NORM_TYPE: 2.0 35 | INPUT: 36 | MIN_SIZE_TRAIN: (480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800) 37 | CROP: 38 | ENABLED: True 39 | TYPE: "absolute_range" 40 | SIZE: (384, 600) 41 | FORMAT: "RGB" 42 | TEST: 43 | EVAL_PERIOD: 4000 44 | DATALOADER: 45 | FILTER_EMPTY_ANNOTATIONS: False 46 | NUM_WORKERS: 4 47 | VERSION: 2 48 | -------------------------------------------------------------------------------- /datasets/panoptic_eval.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import json 3 | import os 4 | 5 | import util.misc as utils 6 | 7 | try: 8 | from panopticapi.evaluation import pq_compute 9 | except ImportError: 10 | pass 11 | 12 | 13 | class PanopticEvaluator(object): 14 | def __init__(self, ann_file, ann_folder, output_dir="panoptic_eval"): 15 | self.gt_json = ann_file 16 | self.gt_folder = ann_folder 17 | if utils.is_main_process(): 18 | if not os.path.exists(output_dir): 19 | os.mkdir(output_dir) 20 | self.output_dir = output_dir 21 | self.predictions = [] 22 | 23 | def update(self, predictions): 24 | for p in predictions: 25 | with open(os.path.join(self.output_dir, p["file_name"]), "wb") as f: 26 | f.write(p.pop("png_string")) 27 | 28 | self.predictions += predictions 29 | 30 | def synchronize_between_processes(self): 31 | all_predictions = utils.all_gather(self.predictions) 32 | merged_predictions = [] 33 | for p in all_predictions: 34 | merged_predictions += p 35 | self.predictions = merged_predictions 36 | 37 | def summarize(self): 38 | if utils.is_main_process(): 39 | json_data = {"annotations": self.predictions} 40 | predictions_json = os.path.join(self.output_dir, "predictions.json") 41 | with open(predictions_json, "w") as f: 42 | f.write(json.dumps(json_data)) 43 | return pq_compute(self.gt_json, predictions_json, gt_folder=self.gt_folder, pred_folder=self.output_dir) 44 | return None 45 | -------------------------------------------------------------------------------- /d2/README.md: -------------------------------------------------------------------------------- 1 | Detectron2 wrapper for DETR 2 | ======= 3 | 4 | We provide a Detectron2 wrapper for DETR, thus providing a way to better integrate it in the existing detection ecosystem. It can be used for example to easily leverage datasets or backbones provided in Detectron2. 5 | 6 | This wrapper currently supports only box detection, and is intended to be as close as possible to the original implementation, and we checked that it indeed match the results. Some notable facts and caveats: 7 | - The data augmentation matches DETR's original data augmentation. This required patching the RandomCrop augmentation from Detectron2, so you'll need a version from the master branch from June 24th 2020 or more recent. 8 | - To match DETR's original backbone initialization, we use the weights of a ResNet50 trained on imagenet using torchvision. This network uses a different pixel mean and std than most of the backbones available in Detectron2 by default, so extra care must be taken when switching to another one. Note that no other torchvision models are available in Detectron2 as of now, though it may change in the future. 9 | - The gradient clipping mode is "full_model", which is not the default in Detectron2. 10 | 11 | # Usage 12 | 13 | To install Detectron2, please follow the [official installation instructions](https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md). 14 | 15 | ## Evaluating a model 16 | 17 | For convenience, we provide a conversion script to convert models trained by the main DETR training loop into the format of this wrapper. To download and convert the main Resnet50 model, simply do: 18 | 19 | ``` 20 | python converter.py --source_model https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth --output_model converted_model.pth 21 | ``` 22 | 23 | You can then evaluate it using: 24 | ``` 25 | python train_net.py --eval-only --config configs/detr_256_6_6_torchvision.yaml MODEL.WEIGHTS "converted_model.pth" 26 | ``` 27 | 28 | 29 | ## Training 30 | 31 | To train DETR on a single node with 8 gpus, simply use: 32 | ``` 33 | python train_net.py --config configs/detr_256_6_6_torchvision.yaml --num-gpus 8 34 | ``` 35 | 36 | To fine-tune DETR for instance segmentation on a single node with 8 gpus, simply use: 37 | ``` 38 | python train_net.py --config configs/detr_segm_256_6_6_torchvision.yaml --num-gpus 8 MODEL.DETR.FROZEN_WEIGHTS 39 | ``` 40 | -------------------------------------------------------------------------------- /d2/converter.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Helper script to convert models trained with the main version of DETR to be used with the Detectron2 version. 4 | """ 5 | import json 6 | import argparse 7 | 8 | import numpy as np 9 | import torch 10 | 11 | 12 | # 转换模型使用的 13 | 14 | def parse_args(): 15 | parser = argparse.ArgumentParser("D2 model converter") 16 | 17 | parser.add_argument("--source_model", default="", type=str, help="Path or url to the DETR model to convert") 18 | parser.add_argument("--output_model", default="", type=str, help="Path where to save the converted model") 19 | return parser.parse_args() 20 | 21 | 22 | def main(): 23 | args = parse_args() 24 | 25 | # D2 expects contiguous classes, so we need to remap the 92 classes from DETR 26 | # fmt: off 27 | coco_idx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 28 | 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 29 | 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 30 | 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91] 31 | # fmt: on 32 | 33 | coco_idx = np.array(coco_idx) 34 | 35 | if args.source_model.startswith("https"): 36 | checkpoint = torch.hub.load_state_dict_from_url(args.source_model, map_location="cpu", check_hash=True) 37 | else: 38 | checkpoint = torch.load(args.source_model, map_location="cpu") 39 | model_to_convert = checkpoint["model"] 40 | 41 | model_converted = {} 42 | for k in model_to_convert.keys(): 43 | old_k = k 44 | if "backbone" in k: 45 | k = k.replace("backbone.0.body.", "") 46 | if "layer" not in k: 47 | k = "stem." + k 48 | for t in [1, 2, 3, 4]: 49 | k = k.replace(f"layer{t}", f"res{t + 1}") 50 | for t in [1, 2, 3]: 51 | k = k.replace(f"bn{t}", f"conv{t}.norm") 52 | k = k.replace("downsample.0", "shortcut") 53 | k = k.replace("downsample.1", "shortcut.norm") 54 | k = "backbone.0.backbone." + k 55 | k = "detr." + k 56 | print(old_k, "->", k) 57 | if "class_embed" in old_k: 58 | v = model_to_convert[old_k].detach() 59 | if v.shape[0] == 92: 60 | shape_old = v.shape 61 | model_converted[k] = v[coco_idx] 62 | print("Head conversion: changing shape from {} to {}".format(shape_old, model_converted[k].shape)) 63 | continue 64 | model_converted[k] = model_to_convert[old_k].detach() 65 | 66 | model_to_save = {"model": model_converted} 67 | torch.save(model_to_save, args.output_model) 68 | 69 | 70 | if __name__ == "__main__": 71 | main() 72 | -------------------------------------------------------------------------------- /util/box_ops.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Utilities for bounding box manipulation and GIoU. 4 | """ 5 | import torch 6 | from torchvision.ops.boxes import box_area 7 | 8 | 9 | def box_cxcywh_to_xyxy(x): 10 | # 中心点的x,y 以及宽高 11 | x_c, y_c, w, h = x.unbind(-1) 12 | # 返回的是左上,右下两个点的四个坐标 13 | b = [(x_c - 0.5 * w), (y_c - 0.5 * h), 14 | (x_c + 0.5 * w), (y_c + 0.5 * h)] 15 | return torch.stack(b, dim=-1) 16 | 17 | 18 | def box_xyxy_to_cxcywh(x): 19 | x0, y0, x1, y1 = x.unbind(-1) 20 | b = [(x0 + x1) / 2, (y0 + y1) / 2, 21 | (x1 - x0), (y1 - y0)] 22 | return torch.stack(b, dim=-1) 23 | 24 | 25 | # modified from torchvision to also return the union 26 | def box_iou(boxes1, boxes2): 27 | # box的面积 28 | area1 = box_area(boxes1) 29 | area2 = box_area(boxes2) 30 | # 两个box的左上,坐标的各自最大 31 | lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] 32 | # 两个box的右下,坐标的各自最小 33 | rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] 34 | # 一点不相交的就是0 35 | wh = (rb - lt).clamp(min=0) # [N,M,2] 36 | inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] 37 | 38 | union = area1[:, None] + area2 - inter 39 | 40 | iou = inter / union 41 | return iou, union 42 | 43 | 44 | def generalized_box_iou(boxes1, boxes2): 45 | """ 46 | 计算GIoU,这个只是GIoU,并不是计算GIoU Loss 47 | Generalized IoU from https://giou.stanford.edu/ 48 | 49 | The boxes should be in [x0, y0, x1, y1] format 50 | 51 | Returns a [N, M] pairwise matrix, where N = len(boxes1) 52 | and M = len(boxes2) 53 | """ 54 | # degenerate boxes gives inf / nan results 55 | # so do an early check 56 | # 右下要比左上大 57 | assert (boxes1[:, 2:] >= boxes1[:, :2]).all() 58 | assert (boxes2[:, 2:] >= boxes2[:, :2]).all() 59 | # iou 以及 并集的面积 60 | iou, union = box_iou(boxes1, boxes2) 61 | # 两个box的左上,坐标的各自最小 62 | lt = torch.min(boxes1[:, None, :2], boxes2[:, :2]) 63 | # 两个box的右下,坐标的各自最大 64 | rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:]) 65 | 66 | wh = (rb - lt).clamp(min=0) # [N,M,2] 67 | area = wh[:, :, 0] * wh[:, :, 1] 68 | # iou - (外接矩形的面积 - 并集的面积) / 外接矩形的面积 69 | return iou - (area - union) / area 70 | 71 | 72 | def masks_to_boxes(masks): 73 | """Compute the bounding boxes around the provided masks 74 | 75 | The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. 76 | 77 | Returns a [N, 4] tensors, with the boxes in xyxy format 78 | """ 79 | if masks.numel() == 0: 80 | return torch.zeros((0, 4), device=masks.device) 81 | 82 | h, w = masks.shape[-2:] 83 | 84 | y = torch.arange(0, h, dtype=torch.float) 85 | x = torch.arange(0, w, dtype=torch.float) 86 | y, x = torch.meshgrid(y, x) 87 | 88 | x_mask = (masks * x.unsqueeze(0)) 89 | x_max = x_mask.flatten(1).max(-1)[0] 90 | x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] 91 | 92 | y_mask = (masks * y.unsqueeze(0)) 93 | y_max = y_mask.flatten(1).max(-1)[0] 94 | y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] 95 | 96 | return torch.stack([x_min, y_min, x_max, y_max], 1) 97 | -------------------------------------------------------------------------------- /源码结构.md: -------------------------------------------------------------------------------- 1 | # DETR源码结构 2 | 3 | ## 简易流程 4 | 5 | 1. [创建模型](main.py) `model, criterion, postprocessors = build_model(args)` 6 | 2. [加载数据集](main.py) 7 | 3. for epoch in epochs 8 | 1. [train_one_epoch](engine.py) 9 | 1. `for samples, targets in` 10 | 1. `outputs=model(samples)` 11 | 1. `features,pos = self.backbone(samples)` 12 | 2. `hs=self.transformer` 13 | 1. query_embed 14 | 2. tgt 15 | 3. `memory=self.encoder` 16 | 4. `hs=self.decoder` 17 | 3. `outputs_class=self.class_embed(hs)` 18 | 4. `outputs_coord=self.bbox_embed(hs).sigmoid()` 19 | 2. `loss_dict = criterion(outputs,targets)` 20 | 1. `indices=self.matcher(outputs_without_aux, targets)` 21 | 2. `get_loss` 22 | 1. self.loss_labels 23 | 2. self.loss_boxes 24 | 25 | 2. 学习率更新 26 | 3. [evaluate](main.py) 27 | 28 | ## 模型结构 29 | 30 | ``` 31 | (class_embed): Linear(in_features=256, out_features=92, bias=True) 32 | (bbox_embed): MLP( 33 | (layers): ModuleList( 34 | (0): Linear(in_features=256, out_features=256, bias=True) 35 | (1): Linear(in_features=256, out_features=256, bias=True) 36 | (2): Linear(in_features=256, out_features=4, bias=True) 37 | ) 38 | ) 39 | (query_embed): Embedding(100, 256) 40 | (input_proj): Conv2d(2048, 256, kernel_size=(1, 1), stride=(1, 1)) 41 | 42 | (0): TransformerEncoderLayer( 43 | (self_attn): MultiheadAttention( 44 | (out_proj): NonDynamicallyQuantizableLinear(in_features=256, out_features=256, bias=True) 45 | ) 46 | (dropout1): Dropout(p=0.1, inplace=False) 47 | (norm1): LayerNorm((256,), eps=1e-05, elementwise_affine=True) 48 | (linear1): Linear(in_features=256, out_features=2048, bias=True) 49 | (dropout): Dropout(p=0.1, inplace=False) 50 | (linear2): Linear(in_features=2048, out_features=256, bias=True) 51 | (dropout2): Dropout(p=0.1, inplace=False) 52 | (norm2): LayerNorm((256,), eps=1e-05, elementwise_affine=True) 53 | ) 54 | 55 | 56 | (0): TransformerDecoderLayer( 57 | (self_attn): MultiheadAttention( 58 | (out_proj): NonDynamicallyQuantizableLinear(in_features=256, out_features=256, bias=True) 59 | ) 60 | (dropout1): Dropout(p=0.1, inplace=False) 61 | (norm1): LayerNorm((256,), eps=1e-05, elementwise_affine=True) 62 | (multihead_attn): MultiheadAttention( 63 | (out_proj): NonDynamicallyQuantizableLinear(in_features=256, out_features=256, bias=True) 64 | ) 65 | (dropout2): Dropout(p=0.1, inplace=False) 66 | (norm2): LayerNorm((256,), eps=1e-05, elementwise_affine=True) 67 | (linear1): Linear(in_features=256, out_features=2048, bias=True) 68 | (dropout): Dropout(p=0.1, inplace=False) 69 | (linear2): Linear(in_features=2048, out_features=256, bias=True) 70 | (dropout3): Dropout(p=0.1, inplace=False) 71 | (norm3): LayerNorm((256,), eps=1e-05, elementwise_affine=True) 72 | ) 73 | ``` 74 | 75 | ## Loss内容 76 | 77 | loss_ce: 2.223 loss_bbox: 2.227 loss_giou: 1.771 78 | loss_ce_0: 2.079 loss_bbox_0: 2.507 loss_giou_0: 1.828 79 | loss_ce_1: 2.097 loss_bbox_1: 2.436 loss_giou_1: 1.852 80 | loss_ce_2: 2.129 loss_bbox_2: 2.462 loss_giou_2: 1.749 81 | loss_ce_3: 2.149 loss_bbox_3: 2.38 loss_giou_3: 1.718 82 | loss_ce_4: 2.128 loss_bbox_4: 2.214 loss_giou_4: 1.712 -------------------------------------------------------------------------------- /datasets/coco_panoptic.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import json 3 | from pathlib import Path 4 | 5 | import numpy as np 6 | import torch 7 | from PIL import Image 8 | 9 | from panopticapi.utils import rgb2id 10 | from util.box_ops import masks_to_boxes 11 | 12 | from .coco import make_coco_transforms 13 | 14 | 15 | class CocoPanoptic: 16 | def __init__(self, img_folder, ann_folder, ann_file, transforms=None, return_masks=True): 17 | with open(ann_file, 'r') as f: 18 | self.coco = json.load(f) 19 | 20 | # sort 'images' field so that they are aligned with 'annotations' 21 | # i.e., in alphabetical order 22 | self.coco['images'] = sorted(self.coco['images'], key=lambda x: x['id']) 23 | # sanity check 24 | if "annotations" in self.coco: 25 | for img, ann in zip(self.coco['images'], self.coco['annotations']): 26 | assert img['file_name'][:-4] == ann['file_name'][:-4] 27 | 28 | self.img_folder = img_folder 29 | self.ann_folder = ann_folder 30 | self.ann_file = ann_file 31 | self.transforms = transforms 32 | self.return_masks = return_masks 33 | 34 | def __getitem__(self, idx): 35 | ann_info = self.coco['annotations'][idx] if "annotations" in self.coco else self.coco['images'][idx] 36 | img_path = Path(self.img_folder) / ann_info['file_name'].replace('.png', '.jpg') 37 | ann_path = Path(self.ann_folder) / ann_info['file_name'] 38 | 39 | img = Image.open(img_path).convert('RGB') 40 | w, h = img.size 41 | if "segments_info" in ann_info: 42 | masks = np.asarray(Image.open(ann_path), dtype=np.uint32) 43 | masks = rgb2id(masks) 44 | 45 | ids = np.array([ann['id'] for ann in ann_info['segments_info']]) 46 | masks = masks == ids[:, None, None] 47 | 48 | masks = torch.as_tensor(masks, dtype=torch.uint8) 49 | labels = torch.tensor([ann['category_id'] for ann in ann_info['segments_info']], dtype=torch.int64) 50 | 51 | target = {} 52 | target['image_id'] = torch.tensor([ann_info['image_id'] if "image_id" in ann_info else ann_info["id"]]) 53 | if self.return_masks: 54 | target['masks'] = masks 55 | target['labels'] = labels 56 | 57 | target["boxes"] = masks_to_boxes(masks) 58 | 59 | target['size'] = torch.as_tensor([int(h), int(w)]) 60 | target['orig_size'] = torch.as_tensor([int(h), int(w)]) 61 | if "segments_info" in ann_info: 62 | for name in ['iscrowd', 'area']: 63 | target[name] = torch.tensor([ann[name] for ann in ann_info['segments_info']]) 64 | 65 | if self.transforms is not None: 66 | img, target = self.transforms(img, target) 67 | 68 | return img, target 69 | 70 | def __len__(self): 71 | return len(self.coco['images']) 72 | 73 | def get_height_and_width(self, idx): 74 | img_info = self.coco['images'][idx] 75 | height = img_info['height'] 76 | width = img_info['width'] 77 | return height, width 78 | 79 | 80 | def build(image_set, args): 81 | img_folder_root = Path(args.coco_path) 82 | ann_folder_root = Path(args.coco_panoptic_path) 83 | assert img_folder_root.exists(), f'provided COCO path {img_folder_root} does not exist' 84 | assert ann_folder_root.exists(), f'provided COCO path {ann_folder_root} does not exist' 85 | mode = 'panoptic' 86 | PATHS = { 87 | "train": ("train2017", Path("annotations") / f'{mode}_train2017.json'), 88 | "val": ("val2017", Path("annotations") / f'{mode}_val2017.json'), 89 | } 90 | 91 | img_folder, ann_file = PATHS[image_set] 92 | img_folder_path = img_folder_root / img_folder 93 | ann_folder = ann_folder_root / f'{mode}_{img_folder}' 94 | ann_file = ann_folder_root / ann_file 95 | 96 | dataset = CocoPanoptic(img_folder_path, ann_folder, ann_file, 97 | transforms=make_coco_transforms(image_set), return_masks=args.masks) 98 | 99 | return dataset 100 | -------------------------------------------------------------------------------- /models/position_encoding.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Various positional encodings for the transformer. 4 | """ 5 | import math 6 | import torch 7 | from torch import nn 8 | 9 | from util.misc import NestedTensor 10 | 11 | 12 | class PositionEmbeddingSine(nn.Module): 13 | """ 14 | transformer中的三角函数位置编码 15 | 相比于原始的版本多了对mask的处理 16 | This is a more standard version of the position embedding, very similar to the one 17 | used by the Attention is all you need paper, generalized to work on images. 18 | """ 19 | 20 | def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): 21 | super().__init__() 22 | self.num_pos_feats = num_pos_feats 23 | self.temperature = temperature 24 | self.normalize = normalize 25 | if scale is not None and normalize is False: 26 | raise ValueError("normalize should be True if scale is passed") 27 | if scale is None: 28 | scale = 2 * math.pi 29 | self.scale = scale 30 | 31 | def forward(self, tensor_list: NestedTensor): 32 | x = tensor_list.tensors 33 | mask = tensor_list.mask 34 | assert mask is not None 35 | not_mask = ~mask 36 | y_embed = not_mask.cumsum(1, dtype=torch.float32) 37 | x_embed = not_mask.cumsum(2, dtype=torch.float32) 38 | if self.normalize: 39 | eps = 1e-6 40 | y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale 41 | x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale 42 | 43 | dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) 44 | dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) 45 | 46 | pos_x = x_embed[:, :, :, None] / dim_t 47 | pos_y = y_embed[:, :, :, None] / dim_t 48 | pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) 49 | pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) 50 | pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) 51 | return pos 52 | 53 | 54 | class PositionEmbeddingLearned(nn.Module): 55 | """ 56 | Absolute pos embedding, learned. 57 | """ 58 | 59 | def __init__(self, num_pos_feats=256): 60 | super().__init__() 61 | # 宽高不会超过50 50*32=1600 62 | # 两个参数张量 63 | self.row_embed = nn.Embedding(50, num_pos_feats) 64 | self.col_embed = nn.Embedding(50, num_pos_feats) 65 | self.reset_parameters() 66 | 67 | def reset_parameters(self): 68 | nn.init.uniform_(self.row_embed.weight) 69 | nn.init.uniform_(self.col_embed.weight) 70 | 71 | def forward(self, tensor_list: NestedTensor): 72 | # [bs,2048,h,w] 73 | x = tensor_list.tensors 74 | 75 | h, w = x.shape[-2:] 76 | # 0 -> w-1 77 | i = torch.arange(w, device=x.device) 78 | # 0 -> h-1 79 | j = torch.arange(h, device=x.device) 80 | # 宽方向上的参数 -> [w,128] 81 | x_emb = self.col_embed(i) 82 | # 高方向上的参数 -> [h,128] 83 | y_emb = self.row_embed(j) 84 | 85 | # x_emb [w,128] -> [1,w,128] -> [h,w,128] 86 | # y_emb [h,128] -> [h,1,128] -> [h,w,128] 87 | # cat (x_emb,y_emb) -> [h,w,256] --permute--> [256,h,w] --unsqueeze--> [1,256,h,w] --repeat-->[bs,256,h,w] 88 | pos = torch.cat([ 89 | x_emb.unsqueeze(0).repeat(h, 1, 1), 90 | y_emb.unsqueeze(1).repeat(1, w, 1), 91 | ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1) 92 | 93 | return pos 94 | 95 | 96 | # 创建position encoding 97 | def build_position_encoding(args): 98 | # todo 除2 99 | N_steps = args.hidden_dim // 2 100 | if args.position_embedding in ('v2', 'sine'): 101 | # TODO find a better way of exposing other arguments 102 | position_embedding = PositionEmbeddingSine(N_steps, normalize=True) 103 | elif args.position_embedding in ('v3', 'learned'): 104 | # learned vit的使用方式 105 | position_embedding = PositionEmbeddingLearned(N_steps) 106 | else: 107 | raise ValueError(f"not supported {args.position_embedding}") 108 | 109 | return position_embedding 110 | -------------------------------------------------------------------------------- /loss内容.md: -------------------------------------------------------------------------------- 1 | Epoch: [0] [ 380/59143] 2 | eta: 3:30:50 3 | lr: 0.000100 4 | class_error: 100.00 5 | loss: 37.0688 (43.5064) 6 | 7 | loss_ce: 1.8906 (2.0527) 8 | loss_bbox: 2.2118 (3.0787) 9 | loss_giou: 1.5819 (1.9712) 10 | 11 | loss_ce_0: 1.8465 (2.0304) 12 | loss_bbox_0: 2.3553 (3.2330) 13 | loss_giou_0: 1.6253 (2.0357) 14 | 15 | loss_ce_1: 1.9880 (2.0502) 16 | loss_bbox_1: 2.4649 (3.2072) 17 | loss_giou_1: 1.6095 (2.0125) 18 | 19 | loss_ce_2: 1.9501 (2.0554) 20 | loss_bbox_2: 2.5059 (3.2476) 21 | loss_giou_2: 1.6524 (2.0369) 22 | 23 | loss_ce_3: 1.8857 (2.0413) 24 | loss_bbox_3: 2.3753 (3.2298) 25 | loss_giou_3: 1.6526 (2.0376) 26 | 27 | loss_ce_4: 1.8875 (2.0482) 28 | loss_bbox_4: 2.3886 (3.1400) 29 | loss_giou_4: 1.6035 (1.9980) 30 | 31 | loss_ce_unscaled: 1.8906 (2.0527) 32 | class_error_unscaled: 100.0000 (99.9713) 33 | loss_bbox_unscaled: 0.4424 (0.6157) 34 | loss_giou_unscaled: 0.7909 (0.9856) 35 | cardinality_error_unscaled: 5.0000 (6.5551) 36 | 37 | loss_ce_0_unscaled: 1.8465 (2.0304) 38 | loss_bbox_0_unscaled: 0.4711 (0.6466) 39 | loss_giou_0_unscaled: 0.8126 (1.0179) 40 | cardinality_error_0_unscaled: 5.0000 (6.2992) 41 | 42 | loss_ce_1_unscaled: 1.9880 (2.0502) 43 | loss_bbox_1_unscaled: 0.4930 (0.6414) 44 | loss_giou_1_unscaled: 0.8048 (1.0062) 45 | cardinality_error_1_unscaled: 4.5000 (6.3648) 46 | 47 | loss_ce_2_unscaled: 1.9501 (2.0554) 48 | loss_bbox_2_unscaled: 0.5012 (0.6495) 49 | loss_giou_2_unscaled: 0.8262 (1.0185) 50 | cardinality_error_2_unscaled: 5.0000 (6.5459) 51 | 52 | loss_ce_3_unscaled: 1.8857 (2.0413) 53 | loss_bbox_3_unscaled: 0.4751 (0.6460) 54 | loss_giou_3_unscaled: 0.8263 (1.0188) 55 | cardinality_error_3_unscaled: 4.5000 (6.5617) 56 | 57 | loss_ce_4_unscaled: 1.8875 (2.0482) 58 | loss_bbox_4_unscaled: 0.4777 (0.6280) 59 | loss_giou_4_unscaled: 0.8017 (0.9990) 60 | cardinality_error_4_unscaled: 5.0000 (6.5118) 61 | 62 | time: 0.2208 data: 0.0062 max mem: 4129 63 | 64 | 这是一次输出的内容 65 | 66 | --- 67 | 68 | detectron2的loss输出 69 | 70 | 71 | eta: 1 day, 20:39:06 iter: 279 total_loss: 167.9 72 | loss_ce: 2.223 loss_bbox: 2.227 loss_giou: 1.771 73 | loss_ce_0: 2.079 loss_bbox_0: 2.507 loss_giou_0: 1.828 74 | loss_ce_1: 2.097 loss_bbox_1: 2.436 loss_giou_1: 1.852 75 | loss_ce_2: 2.129 loss_bbox_2: 2.462 loss_giou_2: 1.749 76 | loss_ce_3: 2.149 loss_bbox_3: 2.38 loss_giou_3: 1.718 77 | loss_ce_4: 2.128 loss_bbox_4: 2.214 loss_giou_4: 1.712 78 | time: 0.2972 data_time: 0.0051 lr: 0.0001 max_mem: 5221M 79 | 80 | 81 | --- 82 | masks 的输出 83 | 84 | Epoch: [0] [ 10/118287] 85 | eta: 13:14:09 lr: 0.000100 86 | class_error: 100.00 87 | loss: 61.5006 (58.2362) 88 | 89 | loss_ce: 2.7442 (2.6890) loss_bbox: 5.0085 (4.7323) loss_giou: 2.1325 (2.1217) loss_mask: 0.0761 (0.1005) 90 | loss_dice: 0.9621 (0.9419) 91 | 92 | loss_ce_0: 2.9160 (2.7079) loss_bbox_0: 5.0121 (4.6874) loss_giou_0: 2.1087 (2.0983) 93 | 94 | loss_ce_1: 2.7609 (2.6381) loss_bbox_1: 5.1135 (4.7626) loss_giou_1: 2.1065 (2.1132) 95 | 96 | loss_ce_2: 2.4731 (2.5986) loss_bbox_2: 5.0824 (4.7624) loss_giou_2: 2.1262 (2.1141) 97 | 98 | loss_ce_3: 2.5061 (2.6956) loss_bbox_3: 5.0058 (4.7577) loss_giou_3: 2.1415 (2.1284) 99 | 100 | loss_ce_4: 2.6394 (2.7492) loss_bbox_4: 4.9926 (4.7104) loss_giou_4: 2.1256 (2.1268) 101 | 102 | loss_ce_unscaled: 2.7442 (2.6890) class_error_unscaled: 100.0000 (100.0000) 103 | loss_bbox_unscaled: 1.0017 (0.9465) loss_giou_unscaled: 1.0662 (1.0608) 104 | cardinality_error_unscaled: 7.0000 (16.1818) 105 | loss_mask_unscaled: 0.0761 (0.1005) loss_dice_unscaled: 0.9621 (0.9419) 106 | 107 | loss_ce_0_unscaled: 2.9160 (2.7079) loss_bbox_0_unscaled: 1.0024 (0.9375) loss_giou_0_unscaled: 1.0543 (1.0491) 108 | cardinality_error_0_unscaled: 7.0000 (16.1818) 109 | 110 | loss_ce_1_unscaled: 2.7609 (2.6381) loss_bbox_1_unscaled: 1.0227 (0.9525) loss_giou_1_unscaled: 1.0533 (1.0566) 111 | cardinality_error_1_unscaled: 7.0000 (16.0909) 112 | 113 | loss_ce_2_unscaled: 2.4731 (2.5986) loss_bbox_2_unscaled: 1.0165 (0.9525) loss_giou_2_unscaled: 1.0631 (1.0571) 114 | cardinality_error_2_unscaled: 7.0000 (16.0909) 115 | 116 | loss_ce_3_unscaled: 2.5061 (2.6956) loss_bbox_3_unscaled: 1.0012 (0.9515) loss_giou_3_unscaled: 1.0707 (1.0642) 117 | cardinality_error_3_unscaled: 7.0000 (16.1818) 118 | 119 | loss_ce_4_unscaled: 2.6394 (2.7492) loss_bbox_4_unscaled: 0.9985 (0.9421) loss_giou_4_unscaled: 1.0628 (1.0634) 120 | cardinality_error_4_unscaled: 7.0000 (16.1818) 121 | 122 | time: 0.4029 data: 0.0325 max mem: 5384 123 | 124 | 多了一个mask的loss 125 | -------------------------------------------------------------------------------- /util/plot_utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plotting utilities to visualize training logs. 3 | """ 4 | import torch 5 | import pandas as pd 6 | import numpy as np 7 | import seaborn as sns 8 | import matplotlib.pyplot as plt 9 | 10 | from pathlib import Path, PurePath 11 | 12 | 13 | def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'): 14 | ''' 15 | Function to plot specific fields from training log(s). Plots both training and test results. 16 | 17 | :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file 18 | - fields = which results to plot from each log file - plots both training and test for each field. 19 | - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots 20 | - log_name = optional, name of log file if different than default 'log.txt'. 21 | 22 | :: Outputs - matplotlib plots of results in fields, color coded for each log file. 23 | - solid lines are training results, dashed lines are test results. 24 | 25 | ''' 26 | func_name = "plot_utils.py::plot_logs" 27 | 28 | # verify logs is a list of Paths (list[Paths]) or single Pathlib object Path, 29 | # convert single Path to list to avoid 'not iterable' error 30 | 31 | if not isinstance(logs, list): 32 | if isinstance(logs, PurePath): 33 | logs = [logs] 34 | print(f"{func_name} info: logs param expects a list argument, converted to list[Path].") 35 | else: 36 | raise ValueError(f"{func_name} - invalid argument for logs parameter.\n \ 37 | Expect list[Path] or single Path obj, received {type(logs)}") 38 | 39 | # Quality checks - verify valid dir(s), that every item in list is Path object, and that log_name exists in each dir 40 | for i, dir in enumerate(logs): 41 | if not isinstance(dir, PurePath): 42 | raise ValueError(f"{func_name} - non-Path object in logs argument of {type(dir)}: \n{dir}") 43 | if not dir.exists(): 44 | raise ValueError(f"{func_name} - invalid directory in logs argument:\n{dir}") 45 | # verify log_name exists 46 | fn = Path(dir / log_name) 47 | if not fn.exists(): 48 | print(f"-> missing {log_name}. Have you gotten to Epoch 1 in training?") 49 | print(f"--> full path of missing log file: {fn}") 50 | return 51 | 52 | # load log file(s) and plot 53 | dfs = [pd.read_json(Path(p) / log_name, lines=True) for p in logs] 54 | 55 | fig, axs = plt.subplots(ncols=len(fields), figsize=(16, 5)) 56 | 57 | for df, color in zip(dfs, sns.color_palette(n_colors=len(logs))): 58 | for j, field in enumerate(fields): 59 | if field == 'mAP': 60 | coco_eval = pd.DataFrame( 61 | np.stack(df.test_coco_eval_bbox.dropna().values)[:, 1] 62 | ).ewm(com=ewm_col).mean() 63 | axs[j].plot(coco_eval, c=color) 64 | else: 65 | df.interpolate().ewm(com=ewm_col).mean().plot( 66 | y=[f'train_{field}', f'test_{field}'], 67 | ax=axs[j], 68 | color=[color] * 2, 69 | style=['-', '--'] 70 | ) 71 | for ax, field in zip(axs, fields): 72 | ax.legend([Path(p).name for p in logs]) 73 | ax.set_title(field) 74 | 75 | 76 | def plot_precision_recall(files, naming_scheme='iter'): 77 | if naming_scheme == 'exp_id': 78 | # name becomes exp_id 79 | names = [f.parts[-3] for f in files] 80 | elif naming_scheme == 'iter': 81 | names = [f.stem for f in files] 82 | else: 83 | raise ValueError(f'not supported {naming_scheme}') 84 | fig, axs = plt.subplots(ncols=2, figsize=(16, 5)) 85 | for f, color, name in zip(files, sns.color_palette("Blues", n_colors=len(files)), names): 86 | data = torch.load(f) 87 | # precision is n_iou, n_points, n_cat, n_area, max_det 88 | precision = data['precision'] 89 | recall = data['params'].recThrs 90 | scores = data['scores'] 91 | # take precision for all classes, all areas and 100 detections 92 | precision = precision[0, :, :, 0, -1].mean(1) 93 | scores = scores[0, :, :, 0, -1].mean(1) 94 | prec = precision.mean() 95 | rec = data['recall'][0, :, 0, -1].mean() 96 | print(f'{naming_scheme} {name}: mAP@50={prec * 100: 05.1f}, ' + 97 | f'score={scores.mean():0.3f}, ' + 98 | f'f1={2 * prec * rec / (prec + rec + 1e-8):0.3f}' 99 | ) 100 | axs[0].plot(recall, precision, c=color) 101 | axs[1].plot(recall, scores, c=color) 102 | 103 | axs[0].set_title('Precision / Recall') 104 | axs[0].legend(names) 105 | axs[1].set_title('Scores / Recall') 106 | axs[1].legend(names) 107 | return fig, axs 108 | -------------------------------------------------------------------------------- /d2/detr/dataset_mapper.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import copy 3 | import logging 4 | 5 | import numpy as np 6 | import torch 7 | 8 | from detectron2.data import detection_utils as utils 9 | from detectron2.data import transforms as T 10 | from detectron2.data.transforms import TransformGen 11 | 12 | __all__ = ["DetrDatasetMapper"] 13 | 14 | 15 | def build_transform_gen(cfg, is_train): 16 | """ 17 | Create a list of :class:`TransformGen` from config. 18 | Returns: 19 | list[TransformGen] 20 | """ 21 | if is_train: 22 | # 最小尺寸 23 | min_size = cfg.INPUT.MIN_SIZE_TRAIN 24 | # 最大尺寸 25 | max_size = cfg.INPUT.MAX_SIZE_TRAIN 26 | 27 | sample_style = cfg.INPUT.MIN_SIZE_TRAIN_SAMPLING 28 | else: 29 | min_size = cfg.INPUT.MIN_SIZE_TEST 30 | max_size = cfg.INPUT.MAX_SIZE_TEST 31 | sample_style = "choice" 32 | if sample_style == "range": 33 | assert len(min_size) == 2, "more than 2 ({}) min_size(s) are provided for ranges".format(len(min_size)) 34 | 35 | logger = logging.getLogger(__name__) 36 | tfm_gens = [] 37 | if is_train: 38 | tfm_gens.append(T.RandomFlip()) 39 | tfm_gens.append(T.ResizeShortestEdge(min_size, max_size, sample_style)) 40 | if is_train: 41 | logger.info("TransformGens used in training: " + str(tfm_gens)) 42 | return tfm_gens 43 | 44 | 45 | class DetrDatasetMapper: 46 | """ 47 | A callable which takes a dataset dict in Detectron2 Dataset format, 48 | and map it into a format used by DETR. 49 | 50 | The callable currently does the following: 51 | 52 | 1. Read the image from "file_name" 53 | 2. Applies geometric transforms to the image and annotation 54 | 3. Find and applies suitable cropping to the image and annotation 55 | 4. Prepare image and annotation to Tensors 56 | """ 57 | 58 | def __init__(self, cfg, is_train=True): 59 | if cfg.INPUT.CROP.ENABLED and is_train: 60 | self.crop_gen = [ 61 | T.ResizeShortestEdge([400, 500, 600], sample_style="choice"), 62 | T.RandomCrop(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE), 63 | ] 64 | else: 65 | self.crop_gen = None 66 | 67 | self.mask_on = cfg.MODEL.MASK_ON 68 | self.tfm_gens = build_transform_gen(cfg, is_train) 69 | logging.getLogger(__name__).info( 70 | "Full TransformGens used in training: {}, crop: {}".format(str(self.tfm_gens), str(self.crop_gen)) 71 | ) 72 | 73 | self.img_format = cfg.INPUT.FORMAT 74 | self.is_train = is_train 75 | 76 | def __call__(self, dataset_dict): 77 | """ 78 | Args: 79 | dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format. 80 | 81 | Returns: 82 | dict: a format that builtin models in detectron2 accept 83 | """ 84 | dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below 85 | image = utils.read_image(dataset_dict["file_name"], format=self.img_format) 86 | utils.check_image_size(dataset_dict, image) 87 | 88 | if self.crop_gen is None: 89 | image, transforms = T.apply_transform_gens(self.tfm_gens, image) 90 | else: 91 | if np.random.rand() > 0.5: 92 | image, transforms = T.apply_transform_gens(self.tfm_gens, image) 93 | else: 94 | image, transforms = T.apply_transform_gens( 95 | self.tfm_gens[:-1] + self.crop_gen + self.tfm_gens[-1:], image 96 | ) 97 | 98 | image_shape = image.shape[:2] # h, w 99 | 100 | # 变成tensor 101 | # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory, 102 | # but not efficient on large generic data structures due to the use of pickle & mp.Queue. 103 | # Therefore it's important to use torch.Tensor. 104 | dataset_dict["image"] = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1))) 105 | 106 | if not self.is_train: 107 | # 不是训练模式,验证模式,移除annotations 108 | # USER: Modify this if you want to keep them for some reason. 109 | dataset_dict.pop("annotations", None) 110 | return dataset_dict 111 | 112 | if "annotations" in dataset_dict: 113 | # USER: Modify this if you want to keep them for some reason. 114 | for anno in dataset_dict["annotations"]: 115 | if not self.mask_on: 116 | anno.pop("segmentation", None) 117 | anno.pop("keypoints", None) 118 | 119 | # USER: Implement additional transformations if you have other types of data 120 | annos = [ 121 | utils.transform_instance_annotations(obj, transforms, image_shape) 122 | for obj in dataset_dict.pop("annotations") 123 | if obj.get("iscrowd", 0) == 0 124 | ] 125 | instances = utils.annotations_to_instances(annos, image_shape) 126 | dataset_dict["instances"] = utils.filter_empty_instances(instances) 127 | return dataset_dict 128 | -------------------------------------------------------------------------------- /models/backbone.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Backbone modules. 4 | """ 5 | from collections import OrderedDict 6 | 7 | import torch 8 | import torch.nn.functional as F 9 | import torchvision 10 | from torch import nn 11 | from torchvision.models._utils import IntermediateLayerGetter 12 | from typing import Dict, List 13 | 14 | from util.misc import NestedTensor, is_main_process 15 | 16 | from .position_encoding import build_position_encoding 17 | 18 | 19 | class FrozenBatchNorm2d(torch.nn.Module): 20 | """ 21 | BatchNorm2d where the batch statistics and the affine parameters are fixed. 22 | 23 | Copy-paste from torchvision.misc.ops with added eps before rqsrt, 24 | without which any other models than torchvision.models.resnet[18,34,50,101] 25 | produce nans. 26 | """ 27 | 28 | def __init__(self, n): 29 | super(FrozenBatchNorm2d, self).__init__() 30 | self.register_buffer("weight", torch.ones(n)) 31 | self.register_buffer("bias", torch.zeros(n)) 32 | self.register_buffer("running_mean", torch.zeros(n)) 33 | self.register_buffer("running_var", torch.ones(n)) 34 | 35 | def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, 36 | missing_keys, unexpected_keys, error_msgs): 37 | num_batches_tracked_key = prefix + 'num_batches_tracked' 38 | if num_batches_tracked_key in state_dict: 39 | del state_dict[num_batches_tracked_key] 40 | 41 | super(FrozenBatchNorm2d, self)._load_from_state_dict( 42 | state_dict, prefix, local_metadata, strict, 43 | missing_keys, unexpected_keys, error_msgs) 44 | 45 | def forward(self, x): 46 | # move reshapes to the beginning 47 | # to make it fuser-friendly 48 | w = self.weight.reshape(1, -1, 1, 1) 49 | b = self.bias.reshape(1, -1, 1, 1) 50 | rv = self.running_var.reshape(1, -1, 1, 1) 51 | rm = self.running_mean.reshape(1, -1, 1, 1) 52 | eps = 1e-5 53 | scale = w * (rv + eps).rsqrt() 54 | bias = b - rm * scale 55 | return x * scale + bias 56 | 57 | 58 | class BackboneBase(nn.Module): 59 | 60 | def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool): 61 | super().__init__() 62 | # conv1.weight 63 | # layer1... 64 | # layer2... 65 | # layer3... 66 | # layer4... 67 | # fc.weight 68 | # fc.bias 69 | # 第一个层不需要更新 70 | for name, parameter in backbone.named_parameters(): 71 | if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name: 72 | parameter.requires_grad_(False) 73 | if return_interm_layers: 74 | return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"} 75 | else: 76 | return_layers = {'layer4': "0"} 77 | # IntermediateLayerGetter 构建的backbone,其内部实现在构建时,到layer4之,后面的fc层就跳过了 78 | # 因此最后是特征,不会是分类头的输出 79 | self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) 80 | self.num_channels = num_channels 81 | 82 | def forward(self, tensor_list: NestedTensor): 83 | # [bs,3,h,w] -> [bs,2048,h/32,w/32] 84 | xs = self.body(tensor_list.tensors) 85 | 86 | out: Dict[str, NestedTensor] = {} 87 | # xs 可能包含了多层,目标检测任务只使用layer4,分割任务会使用layer1,2,3,4 88 | for name, x in xs.items(): 89 | 90 | m = tensor_list.mask 91 | assert m is not None 92 | # 分割任务的mask在不同的特征图尺寸上的插值 93 | mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0] 94 | out[name] = NestedTensor(x, mask) 95 | 96 | return out 97 | 98 | 99 | class Backbone(BackboneBase): 100 | """ResNet backbone with frozen BatchNorm.""" 101 | 102 | def __init__(self, name: str, 103 | train_backbone: bool, 104 | return_interm_layers: bool, 105 | dilation: bool): 106 | backbone = getattr(torchvision.models, name)( 107 | replace_stride_with_dilation=[False, False, dilation], 108 | pretrained=is_main_process(), norm_layer=FrozenBatchNorm2d) 109 | num_channels = 512 if name in ('resnet18', 'resnet34') else 2048 110 | super().__init__(backbone, train_backbone, num_channels, return_interm_layers) 111 | 112 | 113 | class Joiner(nn.Sequential): 114 | def __init__(self, backbone, position_embedding): 115 | super().__init__(backbone, position_embedding) 116 | 117 | def forward(self, tensor_list: NestedTensor): 118 | # 经过backbone 119 | xs = self[0](tensor_list) 120 | out: List[NestedTensor] = [] 121 | pos = [] 122 | # 每个特征层应该是,还是每个image 123 | for name, x in xs.items(): 124 | out.append(x) 125 | # position encoding 126 | pos.append(self[1](x).to(x.tensors.dtype)) 127 | 128 | return out, pos 129 | 130 | 131 | def build_backbone(args): 132 | # 创建位置编码 133 | position_embedding = build_position_encoding(args) 134 | # 如果backbone有学习率设置,那么backbone也将跟着进行训练 135 | train_backbone = args.lr_backbone > 0 136 | return_interm_layers = args.masks 137 | backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation) 138 | model = Joiner(backbone, position_embedding) 139 | model.num_channels = backbone.num_channels 140 | return model 141 | -------------------------------------------------------------------------------- /d2/train_net.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | DETR Training Script. 4 | 5 | This script is a simplified version of the training script in detectron2/tools. 6 | 7 | 使用detectron2进行训练 8 | """ 9 | import os 10 | import sys 11 | import itertools 12 | 13 | # fmt: off 14 | sys.path.insert(1, os.path.join(sys.path[0], '..')) 15 | # fmt: on 16 | 17 | import time 18 | from typing import Any, Dict, List, Set 19 | 20 | import torch 21 | 22 | import detectron2.utils.comm as comm 23 | from d2.detr import DetrDatasetMapper, add_detr_config 24 | from detectron2.checkpoint import DetectionCheckpointer 25 | from detectron2.config import get_cfg 26 | from detectron2.data import MetadataCatalog, build_detection_train_loader 27 | from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch 28 | from detectron2.evaluation import COCOEvaluator, verify_results 29 | 30 | from detectron2.solver.build import maybe_add_gradient_clipping 31 | 32 | 33 | class Trainer(DefaultTrainer): 34 | """ 35 | Extension of the Trainer class adapted to DETR. 36 | """ 37 | 38 | @classmethod 39 | def build_evaluator(cls, cfg, dataset_name, output_folder=None): 40 | """ 41 | Create evaluator(s) for a given dataset. 42 | This uses the special metadata "evaluator_type" associated with each builtin dataset. 43 | For your own dataset, you can simply create an evaluator manually in your 44 | script and do not have to worry about the hacky if-else logic here. 45 | """ 46 | if output_folder is None: 47 | output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") 48 | return COCOEvaluator(dataset_name, cfg, True, output_folder) 49 | 50 | @classmethod 51 | def build_train_loader(cls, cfg): 52 | if "Detr" == cfg.MODEL.META_ARCHITECTURE: 53 | mapper = DetrDatasetMapper(cfg, True) 54 | else: 55 | mapper = None 56 | return build_detection_train_loader(cfg, mapper=mapper) 57 | 58 | @classmethod 59 | def build_optimizer(cls, cfg, model): 60 | params: List[Dict[str, Any]] = [] 61 | memo: Set[torch.nn.parameter.Parameter] = set() 62 | for key, value in model.named_parameters(recurse=True): 63 | if not value.requires_grad: 64 | continue 65 | # Avoid duplicating parameters 66 | if value in memo: 67 | continue 68 | memo.add(value) 69 | lr = cfg.SOLVER.BASE_LR 70 | weight_decay = cfg.SOLVER.WEIGHT_DECAY 71 | if "backbone" in key: 72 | lr = lr * cfg.SOLVER.BACKBONE_MULTIPLIER 73 | params += [{"params": [value], "lr": lr, "weight_decay": weight_decay}] 74 | 75 | def maybe_add_full_model_gradient_clipping(optim): # optim: the optimizer class 76 | # detectron2 doesn't have full model gradient clipping now 77 | clip_norm_val = cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE 78 | enable = ( 79 | 80 | cfg.SOLVER.CLIP_GRADIENTS.ENABLED 81 | and cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model" 82 | and clip_norm_val > 0.0 83 | ) 84 | 85 | class FullModelGradientClippingOptimizer(optim): 86 | def step(self, closure=None): 87 | all_params = itertools.chain(*[x["params"] for x in self.param_groups]) 88 | torch.nn.utils.clip_grad_norm_(all_params, clip_norm_val) 89 | super().step(closure=closure) 90 | 91 | return FullModelGradientClippingOptimizer if enable else optim 92 | 93 | optimizer_type = cfg.SOLVER.OPTIMIZER 94 | if optimizer_type == "SGD": 95 | optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)( 96 | params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM 97 | ) 98 | elif optimizer_type == "ADAMW": 99 | optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)( 100 | params, cfg.SOLVER.BASE_LR 101 | ) 102 | else: 103 | raise NotImplementedError(f"no optimizer type {optimizer_type}") 104 | if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model": 105 | optimizer = maybe_add_gradient_clipping(cfg, optimizer) 106 | return optimizer 107 | 108 | 109 | def setup(args): 110 | """ 111 | Create configs and perform basic setups. 112 | """ 113 | cfg = get_cfg() 114 | # 这个配置是使用add的形式,并不需要更改detectron2中的配置文件 115 | add_detr_config(cfg) 116 | cfg.merge_from_file(args.config_file) 117 | cfg.merge_from_list(args.opts) 118 | cfg.freeze() 119 | default_setup(cfg, args) 120 | return cfg 121 | 122 | 123 | def main(args): 124 | cfg = setup(args) 125 | 126 | if args.eval_only: 127 | model = Trainer.build_model(cfg) 128 | DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume) 129 | res = Trainer.test(cfg, model) 130 | if comm.is_main_process(): 131 | verify_results(cfg, res) 132 | return res 133 | 134 | trainer = Trainer(cfg) 135 | trainer.resume_or_load(resume=args.resume) 136 | return trainer.train() 137 | 138 | 139 | if __name__ == "__main__": 140 | args = default_argument_parser().parse_args() 141 | print("Command Line Args:", args) 142 | launch( 143 | main, 144 | args.num_gpus, 145 | num_machines=args.num_machines, 146 | machine_rank=args.machine_rank, 147 | dist_url=args.dist_url, 148 | args=(args,), 149 | ) 150 | -------------------------------------------------------------------------------- /models/matcher.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Modules to compute the matching cost and solve the corresponding LSAP. 4 | """ 5 | import torch 6 | from scipy.optimize import linear_sum_assignment 7 | from torch import nn 8 | 9 | from util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou 10 | 11 | 12 | # 匈牙利匹配 13 | class HungarianMatcher(nn.Module): 14 | """This class computes an assignment between the targets and the predictions of the network 15 | 16 | For efficiency reasons, the targets don't include the no_object. Because of this, in general, 17 | there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, 18 | while the others are un-matched (and thus treated as non-objects). 19 | """ 20 | 21 | def __init__(self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1): 22 | """Creates the matcher 23 | 24 | Params: 25 | cost_class: This is the relative weight of the classification error in the matching cost 26 | cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost 27 | cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost 28 | """ 29 | super().__init__() 30 | self.cost_class = cost_class 31 | self.cost_bbox = cost_bbox 32 | self.cost_giou = cost_giou 33 | assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0" 34 | 35 | @torch.no_grad() 36 | def forward(self, outputs, targets): 37 | """ Performs the matching 38 | 39 | Params: 40 | outputs: This is a dict that contains at least these entries: 41 | "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits 42 | "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates 43 | 44 | targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing: 45 | "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth 46 | objects in the target) containing the class labels 47 | "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates 48 | 49 | Returns: 50 | A list of size batch_size, containing tuples of (index_i, index_j) where: 51 | - index_i is the indices of the selected predictions (in order) 52 | - index_j is the indices of the corresponding selected targets (in order) 53 | For each batch element, it holds: 54 | len(index_i) = len(index_j) = min(num_queries, num_target_boxes) 55 | """ 56 | 57 | # bs is batch_size num_queries 是配置的每张图片中多少个目标 58 | bs, num_queries = outputs["pred_logits"].shape[:2] 59 | 60 | # 前两个拉平在一起,最后一个维度是类别,进行softmax 61 | # [batch_size * num_queries, num_classes] 62 | # We flatten to compute the cost matrices in a batch 63 | out_prob = outputs["pred_logits"].flatten(0, 1).softmax(1) 64 | 65 | # [batch_size * num_queries, 4] 66 | out_bbox = outputs["pred_boxes"].flatten(0, 1) 67 | 68 | # Also concat the target labels and boxes 69 | tgt_ids = torch.cat([v["labels"] for v in targets]) # target label 70 | tgt_bbox = torch.cat([v["boxes"] for v in targets]) # target bbox 71 | 72 | # Compute the classification cost. Contrary to the loss, we don't use the NLL, 73 | # but approximate it in 1 - proba[target class]. 74 | # The 1 is a constant that doesn't change the matching, it can be ommitted. 75 | # 取出对应的类别的分数,每个框 的 所有gt的label的分数 [bs*100,92][:,tgt_ids] --> [bs*100, 所有bs中img上的gt的数量和] 76 | # 一个预测框上的 对应的 在所有的gt上的分数 77 | cost_class = -out_prob[:, tgt_ids] 78 | 79 | # out_bbox is [bs*100,4] tgt_box is [all_img_gt_count,4] 80 | # Compute the L1 cost between boxes -> [bs*100, all_img_gt_count] 81 | # p=1 计算l1距离 82 | cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1) # cost_bbox 和 cost_class的维度是一样的 83 | 84 | # 计算的GIoU 85 | # 先进行中心点宽高变成坐上右下四个坐标值 86 | # 所有的框,跟gt的giou [bs*100, all_img_gt_count] 87 | # Compute the giou cost betwen boxes 88 | # 完全相同位置的框 giou是1,完全不相交的框,giou是负数 89 | # 因此这里加了一个负号,完全不相交的框的值就变成了整数,表示了更大的代价 90 | cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)) 91 | 92 | # 最终的代价矩阵,匈牙利匹配使用的,最终是要总的分配的代价最小 93 | # 前面都是各个项的权重系数 94 | # Final cost matrix [bs*100, all_img_gt_count] 95 | C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou 96 | 97 | # [bs*100, all_img_gt_count] -> [3,100,all_img_gt_count] 98 | # .cpu 为了给scipy计算 维度变为 batch_size , 100, gt的数量 99 | C = C.view(bs, num_queries, -1).cpu() 100 | 101 | # 每个图片对应的gt的数量 102 | sizes = [len(v["boxes"]) for v in targets] 103 | 104 | # linear_sum_assignment 就是匈牙利算法 105 | # C.split 按照每个图片的gt的数量进行切分 106 | # 第一个值是100内的id,表明100内取哪一个框,第二个应该是对应了哪一个gt的id 107 | # indices is a list length is bs 108 | # indices的一个例子[(array([ 0, 51]), array([0, 1])), (array([13, 24, 54, 86]), array([0, 1, 3, 2]))] 109 | indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))] 110 | 111 | return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices] 112 | 113 | 114 | def build_matcher(args): 115 | return HungarianMatcher(cost_class=args.set_cost_class, cost_bbox=args.set_cost_bbox, cost_giou=args.set_cost_giou) 116 | -------------------------------------------------------------------------------- /datasets/coco.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | COCO dataset which returns image_id for evaluation. 4 | 5 | Mostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py 6 | """ 7 | from pathlib import Path 8 | 9 | import torch 10 | import torch.utils.data 11 | import torchvision 12 | from pycocotools import mask as coco_mask 13 | 14 | import datasets.transforms as T 15 | 16 | 17 | class CocoDetection(torchvision.datasets.CocoDetection): 18 | def __init__(self, img_folder, ann_file, transforms, return_masks): 19 | super(CocoDetection, self).__init__(img_folder, ann_file) 20 | self._transforms = transforms 21 | self.prepare = ConvertCocoPolysToMask(return_masks) 22 | 23 | def __getitem__(self, idx): 24 | img, target = super(CocoDetection, self).__getitem__(idx) 25 | image_id = self.ids[idx] 26 | target = {'image_id': image_id, 'annotations': target} 27 | img, target = self.prepare(img, target) 28 | if self._transforms is not None: 29 | img, target = self._transforms(img, target) 30 | return img, target 31 | 32 | 33 | def convert_coco_poly_to_mask(segmentations, height, width): 34 | masks = [] 35 | for polygons in segmentations: 36 | rles = coco_mask.frPyObjects(polygons, height, width) 37 | mask = coco_mask.decode(rles) 38 | if len(mask.shape) < 3: 39 | mask = mask[..., None] 40 | mask = torch.as_tensor(mask, dtype=torch.uint8) 41 | mask = mask.any(dim=2) 42 | masks.append(mask) 43 | if masks: 44 | masks = torch.stack(masks, dim=0) 45 | else: 46 | masks = torch.zeros((0, height, width), dtype=torch.uint8) 47 | return masks 48 | 49 | 50 | class ConvertCocoPolysToMask(object): 51 | def __init__(self, return_masks=False): 52 | self.return_masks = return_masks 53 | 54 | def __call__(self, image, target): 55 | w, h = image.size 56 | 57 | image_id = target["image_id"] 58 | image_id = torch.tensor([image_id]) 59 | 60 | anno = target["annotations"] 61 | 62 | anno = [obj for obj in anno if 'iscrowd' not in obj or obj['iscrowd'] == 0] 63 | 64 | boxes = [obj["bbox"] for obj in anno] 65 | # guard against no boxes via resizing 66 | boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4) 67 | boxes[:, 2:] += boxes[:, :2] 68 | boxes[:, 0::2].clamp_(min=0, max=w) 69 | boxes[:, 1::2].clamp_(min=0, max=h) 70 | 71 | classes = [obj["category_id"] for obj in anno] 72 | classes = torch.tensor(classes, dtype=torch.int64) 73 | 74 | if self.return_masks: 75 | segmentations = [obj["segmentation"] for obj in anno] 76 | masks = convert_coco_poly_to_mask(segmentations, h, w) 77 | 78 | keypoints = None 79 | if anno and "keypoints" in anno[0]: 80 | keypoints = [obj["keypoints"] for obj in anno] 81 | keypoints = torch.as_tensor(keypoints, dtype=torch.float32) 82 | num_keypoints = keypoints.shape[0] 83 | if num_keypoints: 84 | keypoints = keypoints.view(num_keypoints, -1, 3) 85 | 86 | keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0]) 87 | boxes = boxes[keep] 88 | classes = classes[keep] 89 | if self.return_masks: 90 | masks = masks[keep] 91 | if keypoints is not None: 92 | keypoints = keypoints[keep] 93 | 94 | target = {} 95 | target["boxes"] = boxes 96 | target["labels"] = classes 97 | if self.return_masks: 98 | target["masks"] = masks 99 | target["image_id"] = image_id 100 | if keypoints is not None: 101 | target["keypoints"] = keypoints 102 | 103 | # for conversion to coco api 104 | area = torch.tensor([obj["area"] for obj in anno]) 105 | iscrowd = torch.tensor([obj["iscrowd"] if "iscrowd" in obj else 0 for obj in anno]) 106 | target["area"] = area[keep] 107 | target["iscrowd"] = iscrowd[keep] 108 | 109 | target["orig_size"] = torch.as_tensor([int(h), int(w)]) 110 | target["size"] = torch.as_tensor([int(h), int(w)]) 111 | 112 | return image, target 113 | 114 | 115 | def make_coco_transforms(image_set): 116 | normalize = T.Compose([ 117 | T.ToTensor(), 118 | T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) 119 | ]) 120 | 121 | scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800] 122 | 123 | if image_set == 'train': 124 | return T.Compose([ 125 | T.RandomHorizontalFlip(), 126 | T.RandomSelect( 127 | T.RandomResize(scales, max_size=1333), 128 | T.Compose([ 129 | T.RandomResize([400, 500, 600]), 130 | T.RandomSizeCrop(384, 600), 131 | T.RandomResize(scales, max_size=1333), 132 | ]) 133 | ), 134 | normalize, 135 | ]) 136 | 137 | if image_set == 'val': 138 | return T.Compose([ 139 | T.RandomResize([800], max_size=1333), 140 | normalize, 141 | ]) 142 | 143 | raise ValueError(f'unknown {image_set}') 144 | 145 | 146 | def build(image_set, args): 147 | root = Path(args.coco_path) 148 | assert root.exists(), f'provided COCO path {root} does not exist' 149 | mode = 'instances' 150 | PATHS = { 151 | "train": (root / "train2017", root / "annotations" / f'{mode}_train2017.json'), 152 | "val": (root / "val2017", root / "annotations" / f'{mode}_val2017.json'), 153 | } 154 | 155 | img_folder, ann_file = PATHS[image_set] 156 | dataset = CocoDetection(img_folder, ann_file, transforms=make_coco_transforms(image_set), return_masks=args.masks) 157 | return dataset 158 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import torch 3 | 4 | from models.backbone import Backbone, Joiner 5 | from models.detr import DETR, PostProcess 6 | from models.position_encoding import PositionEmbeddingSine 7 | from models.segmentation import DETRsegm, PostProcessPanoptic 8 | from models.transformer import Transformer 9 | 10 | dependencies = ["torch", "torchvision"] 11 | 12 | 13 | # 创建各种backbone的detr 14 | 15 | def _make_detr(backbone_name: str, dilation=False, num_classes=91, mask=False): 16 | hidden_dim = 256 17 | backbone = Backbone(backbone_name, train_backbone=True, return_interm_layers=mask, dilation=dilation) 18 | pos_enc = PositionEmbeddingSine(hidden_dim // 2, normalize=True) 19 | backbone_with_pos_enc = Joiner(backbone, pos_enc) 20 | backbone_with_pos_enc.num_channels = backbone.num_channels 21 | transformer = Transformer(d_model=hidden_dim, return_intermediate_dec=True) 22 | detr = DETR(backbone_with_pos_enc, transformer, num_classes=num_classes, num_queries=100) 23 | if mask: 24 | return DETRsegm(detr) 25 | return detr 26 | 27 | 28 | def detr_resnet50(pretrained=False, num_classes=91, return_postprocessor=False): 29 | """ 30 | DETR R50 with 6 encoder and 6 decoder layers. 31 | 32 | Achieves 42/62.4 AP/AP50 on COCO val5k. 33 | """ 34 | model = _make_detr("resnet50", dilation=False, num_classes=num_classes) 35 | if pretrained: 36 | checkpoint = torch.hub.load_state_dict_from_url( 37 | url="https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth", map_location="cpu", check_hash=True 38 | ) 39 | model.load_state_dict(checkpoint["model"]) 40 | if return_postprocessor: 41 | return model, PostProcess() 42 | return model 43 | 44 | 45 | def detr_resnet50_dc5(pretrained=False, num_classes=91, return_postprocessor=False): 46 | """ 47 | DETR-DC5 R50 with 6 encoder and 6 decoder layers. 48 | 49 | The last block of ResNet-50 has dilation to increase 50 | output resolution. 51 | Achieves 43.3/63.1 AP/AP50 on COCO val5k. 52 | """ 53 | model = _make_detr("resnet50", dilation=True, num_classes=num_classes) 54 | if pretrained: 55 | checkpoint = torch.hub.load_state_dict_from_url( 56 | url="https://dl.fbaipublicfiles.com/detr/detr-r50-dc5-f0fb7ef5.pth", map_location="cpu", check_hash=True 57 | ) 58 | model.load_state_dict(checkpoint["model"]) 59 | if return_postprocessor: 60 | return model, PostProcess() 61 | return model 62 | 63 | 64 | def detr_resnet101(pretrained=False, num_classes=91, return_postprocessor=False): 65 | """ 66 | DETR-DC5 R101 with 6 encoder and 6 decoder layers. 67 | 68 | Achieves 43.5/63.8 AP/AP50 on COCO val5k. 69 | """ 70 | model = _make_detr("resnet101", dilation=False, num_classes=num_classes) 71 | if pretrained: 72 | checkpoint = torch.hub.load_state_dict_from_url( 73 | url="https://dl.fbaipublicfiles.com/detr/detr-r101-2c7b67e5.pth", map_location="cpu", check_hash=True 74 | ) 75 | model.load_state_dict(checkpoint["model"]) 76 | if return_postprocessor: 77 | return model, PostProcess() 78 | return model 79 | 80 | 81 | def detr_resnet101_dc5(pretrained=False, num_classes=91, return_postprocessor=False): 82 | """ 83 | DETR-DC5 R101 with 6 encoder and 6 decoder layers. 84 | 85 | The last block of ResNet-101 has dilation to increase 86 | output resolution. 87 | Achieves 44.9/64.7 AP/AP50 on COCO val5k. 88 | """ 89 | model = _make_detr("resnet101", dilation=True, num_classes=num_classes) 90 | if pretrained: 91 | checkpoint = torch.hub.load_state_dict_from_url( 92 | url="https://dl.fbaipublicfiles.com/detr/detr-r101-dc5-a2e86def.pth", map_location="cpu", check_hash=True 93 | ) 94 | model.load_state_dict(checkpoint["model"]) 95 | if return_postprocessor: 96 | return model, PostProcess() 97 | return model 98 | 99 | 100 | def detr_resnet50_panoptic( 101 | pretrained=False, num_classes=250, threshold=0.85, return_postprocessor=False 102 | ): 103 | """ 104 | DETR R50 with 6 encoder and 6 decoder layers. 105 | Achieves 43.4 PQ on COCO val5k. 106 | 107 | threshold is the minimum confidence required for keeping segments in the prediction 108 | """ 109 | model = _make_detr("resnet50", dilation=False, num_classes=num_classes, mask=True) 110 | is_thing_map = {i: i <= 90 for i in range(250)} 111 | if pretrained: 112 | checkpoint = torch.hub.load_state_dict_from_url( 113 | url="https://dl.fbaipublicfiles.com/detr/detr-r50-panoptic-00ce5173.pth", 114 | map_location="cpu", 115 | check_hash=True, 116 | ) 117 | model.load_state_dict(checkpoint["model"]) 118 | if return_postprocessor: 119 | return model, PostProcessPanoptic(is_thing_map, threshold=threshold) 120 | return model 121 | 122 | 123 | def detr_resnet50_dc5_panoptic( 124 | pretrained=False, num_classes=250, threshold=0.85, return_postprocessor=False 125 | ): 126 | """ 127 | DETR-DC5 R50 with 6 encoder and 6 decoder layers. 128 | 129 | The last block of ResNet-50 has dilation to increase 130 | output resolution. 131 | Achieves 44.6 on COCO val5k. 132 | 133 | threshold is the minimum confidence required for keeping segments in the prediction 134 | """ 135 | model = _make_detr("resnet50", dilation=True, num_classes=num_classes, mask=True) 136 | is_thing_map = {i: i <= 90 for i in range(250)} 137 | if pretrained: 138 | checkpoint = torch.hub.load_state_dict_from_url( 139 | url="https://dl.fbaipublicfiles.com/detr/detr-r50-dc5-panoptic-da08f1b1.pth", 140 | map_location="cpu", 141 | check_hash=True, 142 | ) 143 | model.load_state_dict(checkpoint["model"]) 144 | if return_postprocessor: 145 | return model, PostProcessPanoptic(is_thing_map, threshold=threshold) 146 | return model 147 | 148 | 149 | def detr_resnet101_panoptic( 150 | pretrained=False, num_classes=250, threshold=0.85, return_postprocessor=False 151 | ): 152 | """ 153 | DETR-DC5 R101 with 6 encoder and 6 decoder layers. 154 | 155 | Achieves 45.1 PQ on COCO val5k. 156 | 157 | threshold is the minimum confidence required for keeping segments in the prediction 158 | """ 159 | model = _make_detr("resnet101", dilation=False, num_classes=num_classes, mask=True) 160 | is_thing_map = {i: i <= 90 for i in range(250)} 161 | if pretrained: 162 | checkpoint = torch.hub.load_state_dict_from_url( 163 | url="https://dl.fbaipublicfiles.com/detr/detr-r101-panoptic-40021d53.pth", 164 | map_location="cpu", 165 | check_hash=True, 166 | ) 167 | model.load_state_dict(checkpoint["model"]) 168 | if return_postprocessor: 169 | return model, PostProcessPanoptic(is_thing_map, threshold=threshold) 170 | return model 171 | -------------------------------------------------------------------------------- /engine.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Train and eval functions used in main.py 4 | """ 5 | import math 6 | import os 7 | import sys 8 | from typing import Iterable 9 | 10 | import torch 11 | 12 | import util.misc as utils 13 | from datasets.coco_eval import CocoEvaluator 14 | from datasets.panoptic_eval import PanopticEvaluator 15 | 16 | 17 | # 主训练方法 18 | def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, 19 | data_loader: Iterable, optimizer: torch.optim.Optimizer, 20 | device: torch.device, epoch: int, max_norm: float = 0): 21 | """ 22 | 一个epoch内的训练方法 23 | """ 24 | model.train() 25 | criterion.train() 26 | 27 | metric_logger = utils.MetricLogger(delimiter=" ") 28 | metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) 29 | metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) 30 | header = 'Epoch: [{}]'.format(epoch) 31 | print_freq = 10 32 | 33 | for samples, targets in metric_logger.log_every(data_loader, print_freq, header): 34 | samples = samples.to(device) 35 | targets = [{k: v.to(device) for k, v in t.items()} for t in targets] 36 | 37 | # 1. 传送给网络 38 | # 3个item, pred_logits, pred_boxes, aux_outputs 39 | outputs = model(samples) 40 | # 2. 计算loss 41 | # loss 计算 42 | loss_dict = criterion(outputs, targets) 43 | # 这个是各项loss的权重 44 | # {'loss_ce': 1, 'loss_bbox': 5, 'loss_giou': 2, 45 | # 'loss_ce_0': 1, 'loss_bbox_0': 5, 'loss_giou_0': 2, 46 | # 'loss_ce_1': 1, 'loss_bbox_1': 5, 'loss_giou_1': 2, 47 | # 'loss_ce_2': 1, 'loss_bbox_2': 5, 'loss_giou_2': 2, 48 | # 'loss_ce_3': 1, 'loss_bbox_3': 5, 'loss_giou_3': 2, 49 | # 'loss_ce_4': 1, 'loss_bbox_4': 5, 'loss_giou_4': 2} 50 | weight_dict = criterion.weight_dict 51 | losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) 52 | 53 | # reduce losses over all GPUs for logging purposes 54 | loss_dict_reduced = utils.reduce_dict(loss_dict) 55 | # logger 使用的 56 | loss_dict_reduced_unscaled = {f'{k}_unscaled': v 57 | for k, v in loss_dict_reduced.items()} 58 | loss_dict_reduced_scaled = {k: v * weight_dict[k] 59 | for k, v in loss_dict_reduced.items() if k in weight_dict} 60 | losses_reduced_scaled = sum(loss_dict_reduced_scaled.values()) 61 | 62 | loss_value = losses_reduced_scaled.item() 63 | 64 | if not math.isfinite(loss_value): 65 | print("Loss is {}, stopping training".format(loss_value)) 66 | print(loss_dict_reduced) 67 | sys.exit(1) 68 | 69 | optimizer.zero_grad() 70 | losses.backward() 71 | if max_norm > 0: 72 | torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) 73 | optimizer.step() 74 | 75 | metric_logger.update(loss=loss_value, **loss_dict_reduced_scaled, **loss_dict_reduced_unscaled) 76 | metric_logger.update(class_error=loss_dict_reduced['class_error']) 77 | metric_logger.update(lr=optimizer.param_groups[0]["lr"]) 78 | # gather the stats from all processes 79 | metric_logger.synchronize_between_processes() 80 | print("Averaged stats:", metric_logger) 81 | return {k: meter.global_avg for k, meter in metric_logger.meters.items()} 82 | 83 | 84 | # ---------------------------------------------------------------------------------------------------------------------- 85 | 86 | # 主评估方法 87 | @torch.no_grad() 88 | def evaluate(model, criterion, postprocessors, data_loader, base_ds, device, output_dir): 89 | model.eval() 90 | criterion.eval() 91 | 92 | metric_logger = utils.MetricLogger(delimiter=" ") 93 | metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) 94 | header = 'Test:' 95 | 96 | iou_types = tuple(k for k in ('segm', 'bbox') if k in postprocessors.keys()) 97 | coco_evaluator = CocoEvaluator(base_ds, iou_types) 98 | # coco_evaluator.coco_eval[iou_types[0]].params.iouThrs = [0, 0.1, 0.5, 0.75] 99 | 100 | panoptic_evaluator = None 101 | if 'panoptic' in postprocessors.keys(): 102 | panoptic_evaluator = PanopticEvaluator( 103 | data_loader.dataset.ann_file, 104 | data_loader.dataset.ann_folder, 105 | output_dir=os.path.join(output_dir, "panoptic_eval"), 106 | ) 107 | 108 | for samples, targets in metric_logger.log_every(data_loader, 10, header): 109 | samples = samples.to(device) 110 | targets = [{k: v.to(device) for k, v in t.items()} for t in targets] 111 | 112 | outputs = model(samples) 113 | loss_dict = criterion(outputs, targets) 114 | weight_dict = criterion.weight_dict 115 | 116 | # reduce losses over all GPUs for logging purposes 117 | loss_dict_reduced = utils.reduce_dict(loss_dict) 118 | 119 | # 使用了权重进行缩放 120 | loss_dict_reduced_scaled = {k: v * weight_dict[k] 121 | for k, v in loss_dict_reduced.items() if k in weight_dict} 122 | 123 | # 没有使用权重进行缩放 124 | loss_dict_reduced_unscaled = {f'{k}_unscaled': v 125 | for k, v in loss_dict_reduced.items()} 126 | metric_logger.update(loss=sum(loss_dict_reduced_scaled.values()), 127 | **loss_dict_reduced_scaled, 128 | **loss_dict_reduced_unscaled) 129 | metric_logger.update(class_error=loss_dict_reduced['class_error']) 130 | # 图像的原始大小 131 | orig_target_sizes = torch.stack([t["orig_size"] for t in targets], dim=0) 132 | 133 | results = postprocessors['bbox'](outputs, orig_target_sizes) 134 | 135 | if 'segm' in postprocessors.keys(): 136 | target_sizes = torch.stack([t["size"] for t in targets], dim=0) 137 | results = postprocessors['segm'](results, outputs, orig_target_sizes, target_sizes) 138 | res = {target['image_id'].item(): output for target, output in zip(targets, results)} 139 | 140 | if coco_evaluator is not None: 141 | coco_evaluator.update(res) 142 | 143 | if panoptic_evaluator is not None: 144 | res_pano = postprocessors["panoptic"](outputs, target_sizes, orig_target_sizes) 145 | for i, target in enumerate(targets): 146 | image_id = target["image_id"].item() 147 | file_name = f"{image_id:012d}.png" 148 | res_pano[i]["image_id"] = image_id 149 | res_pano[i]["file_name"] = file_name 150 | 151 | panoptic_evaluator.update(res_pano) 152 | 153 | # gather the stats from all processes 154 | metric_logger.synchronize_between_processes() 155 | print("Averaged stats:", metric_logger) 156 | if coco_evaluator is not None: 157 | coco_evaluator.synchronize_between_processes() 158 | if panoptic_evaluator is not None: 159 | panoptic_evaluator.synchronize_between_processes() 160 | 161 | # accumulate predictions from all images 162 | if coco_evaluator is not None: 163 | coco_evaluator.accumulate() 164 | coco_evaluator.summarize() 165 | panoptic_res = None 166 | if panoptic_evaluator is not None: 167 | panoptic_res = panoptic_evaluator.summarize() 168 | stats = {k: meter.global_avg for k, meter in metric_logger.meters.items()} 169 | if coco_evaluator is not None: 170 | if 'bbox' in postprocessors.keys(): 171 | stats['coco_eval_bbox'] = coco_evaluator.coco_eval['bbox'].stats.tolist() 172 | if 'segm' in postprocessors.keys(): 173 | stats['coco_eval_masks'] = coco_evaluator.coco_eval['segm'].stats.tolist() 174 | if panoptic_res is not None: 175 | stats['PQ_all'] = panoptic_res["All"] 176 | stats['PQ_th'] = panoptic_res["Things"] 177 | stats['PQ_st'] = panoptic_res["Stuff"] 178 | return stats, coco_evaluator 179 | -------------------------------------------------------------------------------- /test_all.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import io 3 | import unittest 4 | 5 | import torch 6 | from torch import nn, Tensor 7 | from typing import List 8 | 9 | from models.matcher import HungarianMatcher 10 | from models.position_encoding import PositionEmbeddingSine, PositionEmbeddingLearned 11 | from models.backbone import Backbone, Joiner, BackboneBase 12 | from util import box_ops 13 | from util.misc import nested_tensor_from_tensor_list 14 | from hubconf import detr_resnet50, detr_resnet50_panoptic 15 | 16 | # onnxruntime requires python 3.5 or above 17 | try: 18 | import onnxruntime 19 | except ImportError: 20 | onnxruntime = None 21 | 22 | 23 | class Tester(unittest.TestCase): 24 | 25 | def test_box_cxcywh_to_xyxy(self): 26 | t = torch.rand(10, 4) 27 | r = box_ops.box_xyxy_to_cxcywh(box_ops.box_cxcywh_to_xyxy(t)) 28 | self.assertLess((t - r).abs().max(), 1e-5) 29 | 30 | @staticmethod 31 | def indices_torch2python(indices): 32 | return [(i.tolist(), j.tolist()) for i, j in indices] 33 | 34 | def test_hungarian(self): 35 | n_queries, n_targets, n_classes = 100, 15, 91 36 | logits = torch.rand(1, n_queries, n_classes + 1) 37 | boxes = torch.rand(1, n_queries, 4) 38 | tgt_labels = torch.randint(high=n_classes, size=(n_targets,)) 39 | tgt_boxes = torch.rand(n_targets, 4) 40 | matcher = HungarianMatcher() 41 | targets = [{'labels': tgt_labels, 'boxes': tgt_boxes}] 42 | indices_single = matcher({'pred_logits': logits, 'pred_boxes': boxes}, targets) 43 | indices_batched = matcher({'pred_logits': logits.repeat(2, 1, 1), 44 | 'pred_boxes': boxes.repeat(2, 1, 1)}, targets * 2) 45 | self.assertEqual(len(indices_single[0][0]), n_targets) 46 | self.assertEqual(len(indices_single[0][1]), n_targets) 47 | self.assertEqual(self.indices_torch2python(indices_single), 48 | self.indices_torch2python([indices_batched[0]])) 49 | self.assertEqual(self.indices_torch2python(indices_single), 50 | self.indices_torch2python([indices_batched[1]])) 51 | 52 | # test with empty targets 53 | tgt_labels_empty = torch.randint(high=n_classes, size=(0,)) 54 | tgt_boxes_empty = torch.rand(0, 4) 55 | targets_empty = [{'labels': tgt_labels_empty, 'boxes': tgt_boxes_empty}] 56 | indices = matcher({'pred_logits': logits.repeat(2, 1, 1), 57 | 'pred_boxes': boxes.repeat(2, 1, 1)}, targets + targets_empty) 58 | self.assertEqual(len(indices[1][0]), 0) 59 | indices = matcher({'pred_logits': logits.repeat(2, 1, 1), 60 | 'pred_boxes': boxes.repeat(2, 1, 1)}, targets_empty * 2) 61 | self.assertEqual(len(indices[0][0]), 0) 62 | 63 | def test_position_encoding_script(self): 64 | m1, m2 = PositionEmbeddingSine(), PositionEmbeddingLearned() 65 | mm1, mm2 = torch.jit.script(m1), torch.jit.script(m2) # noqa 66 | 67 | def test_backbone_script(self): 68 | backbone = Backbone('resnet50', True, False, False) 69 | torch.jit.script(backbone) # noqa 70 | 71 | def test_model_script_detection(self): 72 | model = detr_resnet50(pretrained=False).eval() 73 | scripted_model = torch.jit.script(model) 74 | x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)]) 75 | out = model(x) 76 | out_script = scripted_model(x) 77 | self.assertTrue(out["pred_logits"].equal(out_script["pred_logits"])) 78 | self.assertTrue(out["pred_boxes"].equal(out_script["pred_boxes"])) 79 | 80 | def test_model_script_panoptic(self): 81 | model = detr_resnet50_panoptic(pretrained=False).eval() 82 | scripted_model = torch.jit.script(model) 83 | x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)]) 84 | out = model(x) 85 | out_script = scripted_model(x) 86 | self.assertTrue(out["pred_logits"].equal(out_script["pred_logits"])) 87 | self.assertTrue(out["pred_boxes"].equal(out_script["pred_boxes"])) 88 | self.assertTrue(out["pred_masks"].equal(out_script["pred_masks"])) 89 | 90 | def test_model_detection_different_inputs(self): 91 | model = detr_resnet50(pretrained=False).eval() 92 | # support NestedTensor 93 | x = nested_tensor_from_tensor_list([torch.rand(3, 200, 200), torch.rand(3, 200, 250)]) 94 | out = model(x) 95 | self.assertIn('pred_logits', out) 96 | # and 4d Tensor 97 | x = torch.rand(1, 3, 200, 200) 98 | out = model(x) 99 | self.assertIn('pred_logits', out) 100 | # and List[Tensor[C, H, W]] 101 | x = torch.rand(3, 200, 200) 102 | out = model([x]) 103 | self.assertIn('pred_logits', out) 104 | 105 | def test_warpped_model_script_detection(self): 106 | class WrappedDETR(nn.Module): 107 | def __init__(self, model): 108 | super().__init__() 109 | self.model = model 110 | 111 | def forward(self, inputs: List[Tensor]): 112 | sample = nested_tensor_from_tensor_list(inputs) 113 | return self.model(sample) 114 | 115 | model = detr_resnet50(pretrained=False) 116 | wrapped_model = WrappedDETR(model) 117 | wrapped_model.eval() 118 | scripted_model = torch.jit.script(wrapped_model) 119 | x = [torch.rand(3, 200, 200), torch.rand(3, 200, 250)] 120 | out = wrapped_model(x) 121 | out_script = scripted_model(x) 122 | self.assertTrue(out["pred_logits"].equal(out_script["pred_logits"])) 123 | self.assertTrue(out["pred_boxes"].equal(out_script["pred_boxes"])) 124 | 125 | 126 | @unittest.skipIf(onnxruntime is None, 'ONNX Runtime unavailable') 127 | class ONNXExporterTester(unittest.TestCase): 128 | @classmethod 129 | def setUpClass(cls): 130 | torch.manual_seed(123) 131 | 132 | def run_model(self, model, inputs_list, tolerate_small_mismatch=False, do_constant_folding=True, dynamic_axes=None, 133 | output_names=None, input_names=None): 134 | model.eval() 135 | 136 | onnx_io = io.BytesIO() 137 | # export to onnx with the first input 138 | torch.onnx.export(model, inputs_list[0], onnx_io, 139 | do_constant_folding=do_constant_folding, opset_version=12, 140 | dynamic_axes=dynamic_axes, input_names=input_names, output_names=output_names) 141 | # validate the exported model with onnx runtime 142 | for test_inputs in inputs_list: 143 | with torch.no_grad(): 144 | if isinstance(test_inputs, torch.Tensor) or isinstance(test_inputs, list): 145 | test_inputs = (nested_tensor_from_tensor_list(test_inputs),) 146 | test_ouputs = model(*test_inputs) 147 | if isinstance(test_ouputs, torch.Tensor): 148 | test_ouputs = (test_ouputs,) 149 | self.ort_validate(onnx_io, test_inputs, test_ouputs, tolerate_small_mismatch) 150 | 151 | def ort_validate(self, onnx_io, inputs, outputs, tolerate_small_mismatch=False): 152 | 153 | inputs, _ = torch.jit._flatten(inputs) 154 | outputs, _ = torch.jit._flatten(outputs) 155 | 156 | def to_numpy(tensor): 157 | if tensor.requires_grad: 158 | return tensor.detach().cpu().numpy() 159 | else: 160 | return tensor.cpu().numpy() 161 | 162 | inputs = list(map(to_numpy, inputs)) 163 | outputs = list(map(to_numpy, outputs)) 164 | 165 | ort_session = onnxruntime.InferenceSession(onnx_io.getvalue()) 166 | # compute onnxruntime output prediction 167 | ort_inputs = dict((ort_session.get_inputs()[i].name, inpt) for i, inpt in enumerate(inputs)) 168 | ort_outs = ort_session.run(None, ort_inputs) 169 | for i, element in enumerate(outputs): 170 | try: 171 | torch.testing.assert_allclose(element, ort_outs[i], rtol=1e-03, atol=1e-05) 172 | except AssertionError as error: 173 | if tolerate_small_mismatch: 174 | self.assertIn("(0.00%)", str(error), str(error)) 175 | else: 176 | raise 177 | 178 | def test_model_onnx_detection(self): 179 | model = detr_resnet50(pretrained=False).eval() 180 | dummy_image = torch.ones(1, 3, 800, 800) * 0.3 181 | model(dummy_image) 182 | 183 | # Test exported model on images of different size, or dummy input 184 | self.run_model( 185 | model, 186 | [(torch.rand(1, 3, 750, 800),)], 187 | input_names=["inputs"], 188 | output_names=["pred_logits", "pred_boxes"], 189 | tolerate_small_mismatch=True, 190 | ) 191 | 192 | @unittest.skip("CI doesn't have enough memory") 193 | def test_model_onnx_detection_panoptic(self): 194 | model = detr_resnet50_panoptic(pretrained=False).eval() 195 | dummy_image = torch.ones(1, 3, 800, 800) * 0.3 196 | model(dummy_image) 197 | 198 | # Test exported model on images of different size, or dummy input 199 | self.run_model( 200 | model, 201 | [(torch.rand(1, 3, 750, 800),)], 202 | input_names=["inputs"], 203 | output_names=["pred_logits", "pred_boxes", "pred_masks"], 204 | tolerate_small_mismatch=True, 205 | ) 206 | 207 | 208 | if __name__ == '__main__': 209 | unittest.main() 210 | -------------------------------------------------------------------------------- /datasets/transforms.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Transforms and data augmentation for both image + bbox. 4 | """ 5 | import random 6 | 7 | import PIL 8 | import torch 9 | import torchvision.transforms as T 10 | import torchvision.transforms.functional as F 11 | 12 | from util.box_ops import box_xyxy_to_cxcywh 13 | from util.misc import interpolate 14 | 15 | 16 | def crop(image, target, region): 17 | cropped_image = F.crop(image, *region) 18 | 19 | target = target.copy() 20 | i, j, h, w = region 21 | 22 | # should we do something wrt the original size? 23 | target["size"] = torch.tensor([h, w]) 24 | 25 | fields = ["labels", "area", "iscrowd"] 26 | 27 | if "boxes" in target: 28 | boxes = target["boxes"] 29 | max_size = torch.as_tensor([w, h], dtype=torch.float32) 30 | cropped_boxes = boxes - torch.as_tensor([j, i, j, i]) 31 | cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size) 32 | cropped_boxes = cropped_boxes.clamp(min=0) 33 | area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1) 34 | target["boxes"] = cropped_boxes.reshape(-1, 4) 35 | target["area"] = area 36 | fields.append("boxes") 37 | 38 | if "masks" in target: 39 | # FIXME should we update the area here if there are no boxes? 40 | target['masks'] = target['masks'][:, i:i + h, j:j + w] 41 | fields.append("masks") 42 | 43 | # remove elements for which the boxes or masks that have zero area 44 | if "boxes" in target or "masks" in target: 45 | # favor boxes selection when defining which elements to keep 46 | # this is compatible with previous implementation 47 | if "boxes" in target: 48 | cropped_boxes = target['boxes'].reshape(-1, 2, 2) 49 | keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1) 50 | else: 51 | keep = target['masks'].flatten(1).any(1) 52 | 53 | for field in fields: 54 | target[field] = target[field][keep] 55 | 56 | return cropped_image, target 57 | 58 | 59 | def hflip(image, target): 60 | flipped_image = F.hflip(image) 61 | 62 | w, h = image.size 63 | 64 | target = target.copy() 65 | if "boxes" in target: 66 | boxes = target["boxes"] 67 | boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor([w, 0, w, 0]) 68 | target["boxes"] = boxes 69 | 70 | if "masks" in target: 71 | target['masks'] = target['masks'].flip(-1) 72 | 73 | return flipped_image, target 74 | 75 | 76 | def resize(image, target, size, max_size=None): 77 | # size can be min_size (scalar) or (w, h) tuple 78 | 79 | def get_size_with_aspect_ratio(image_size, size, max_size=None): 80 | w, h = image_size 81 | if max_size is not None: 82 | min_original_size = float(min((w, h))) 83 | max_original_size = float(max((w, h))) 84 | if max_original_size / min_original_size * size > max_size: 85 | size = int(round(max_size * min_original_size / max_original_size)) 86 | 87 | if (w <= h and w == size) or (h <= w and h == size): 88 | return (h, w) 89 | 90 | if w < h: 91 | ow = size 92 | oh = int(size * h / w) 93 | else: 94 | oh = size 95 | ow = int(size * w / h) 96 | 97 | return (oh, ow) 98 | 99 | def get_size(image_size, size, max_size=None): 100 | if isinstance(size, (list, tuple)): 101 | return size[::-1] 102 | else: 103 | return get_size_with_aspect_ratio(image_size, size, max_size) 104 | 105 | size = get_size(image.size, size, max_size) 106 | rescaled_image = F.resize(image, size) 107 | 108 | if target is None: 109 | return rescaled_image, None 110 | 111 | ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size)) 112 | ratio_width, ratio_height = ratios 113 | 114 | target = target.copy() 115 | if "boxes" in target: 116 | boxes = target["boxes"] 117 | scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height]) 118 | target["boxes"] = scaled_boxes 119 | 120 | if "area" in target: 121 | area = target["area"] 122 | scaled_area = area * (ratio_width * ratio_height) 123 | target["area"] = scaled_area 124 | 125 | h, w = size 126 | target["size"] = torch.tensor([h, w]) 127 | 128 | if "masks" in target: 129 | target['masks'] = interpolate( 130 | target['masks'][:, None].float(), size, mode="nearest")[:, 0] > 0.5 131 | 132 | return rescaled_image, target 133 | 134 | 135 | def pad(image, target, padding): 136 | # assumes that we only pad on the bottom right corners 137 | padded_image = F.pad(image, (0, 0, padding[0], padding[1])) 138 | if target is None: 139 | return padded_image, None 140 | target = target.copy() 141 | # should we do something wrt the original size? 142 | target["size"] = torch.tensor(padded_image.size[::-1]) 143 | if "masks" in target: 144 | target['masks'] = torch.nn.functional.pad(target['masks'], (0, padding[0], 0, padding[1])) 145 | return padded_image, target 146 | 147 | 148 | class RandomCrop(object): 149 | def __init__(self, size): 150 | self.size = size 151 | 152 | def __call__(self, img, target): 153 | region = T.RandomCrop.get_params(img, self.size) 154 | return crop(img, target, region) 155 | 156 | 157 | class RandomSizeCrop(object): 158 | def __init__(self, min_size: int, max_size: int): 159 | self.min_size = min_size 160 | self.max_size = max_size 161 | 162 | def __call__(self, img: PIL.Image.Image, target: dict): 163 | w = random.randint(self.min_size, min(img.width, self.max_size)) 164 | h = random.randint(self.min_size, min(img.height, self.max_size)) 165 | region = T.RandomCrop.get_params(img, [h, w]) 166 | return crop(img, target, region) 167 | 168 | 169 | class CenterCrop(object): 170 | def __init__(self, size): 171 | self.size = size 172 | 173 | def __call__(self, img, target): 174 | image_width, image_height = img.size 175 | crop_height, crop_width = self.size 176 | crop_top = int(round((image_height - crop_height) / 2.)) 177 | crop_left = int(round((image_width - crop_width) / 2.)) 178 | return crop(img, target, (crop_top, crop_left, crop_height, crop_width)) 179 | 180 | 181 | class RandomHorizontalFlip(object): 182 | def __init__(self, p=0.5): 183 | self.p = p 184 | 185 | def __call__(self, img, target): 186 | if random.random() < self.p: 187 | return hflip(img, target) 188 | return img, target 189 | 190 | 191 | class RandomResize(object): 192 | def __init__(self, sizes, max_size=None): 193 | assert isinstance(sizes, (list, tuple)) 194 | self.sizes = sizes 195 | self.max_size = max_size 196 | 197 | def __call__(self, img, target=None): 198 | size = random.choice(self.sizes) 199 | return resize(img, target, size, self.max_size) 200 | 201 | 202 | class RandomPad(object): 203 | def __init__(self, max_pad): 204 | self.max_pad = max_pad 205 | 206 | def __call__(self, img, target): 207 | pad_x = random.randint(0, self.max_pad) 208 | pad_y = random.randint(0, self.max_pad) 209 | return pad(img, target, (pad_x, pad_y)) 210 | 211 | 212 | class RandomSelect(object): 213 | """ 214 | Randomly selects between transforms1 and transforms2, 215 | with probability p for transforms1 and (1 - p) for transforms2 216 | """ 217 | def __init__(self, transforms1, transforms2, p=0.5): 218 | self.transforms1 = transforms1 219 | self.transforms2 = transforms2 220 | self.p = p 221 | 222 | def __call__(self, img, target): 223 | if random.random() < self.p: 224 | return self.transforms1(img, target) 225 | return self.transforms2(img, target) 226 | 227 | 228 | class ToTensor(object): 229 | def __call__(self, img, target): 230 | return F.to_tensor(img), target 231 | 232 | 233 | class RandomErasing(object): 234 | 235 | def __init__(self, *args, **kwargs): 236 | self.eraser = T.RandomErasing(*args, **kwargs) 237 | 238 | def __call__(self, img, target): 239 | return self.eraser(img), target 240 | 241 | 242 | class Normalize(object): 243 | def __init__(self, mean, std): 244 | self.mean = mean 245 | self.std = std 246 | 247 | def __call__(self, image, target=None): 248 | image = F.normalize(image, mean=self.mean, std=self.std) 249 | if target is None: 250 | return image, None 251 | target = target.copy() 252 | h, w = image.shape[-2:] 253 | if "boxes" in target: 254 | boxes = target["boxes"] 255 | boxes = box_xyxy_to_cxcywh(boxes) 256 | boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32) 257 | target["boxes"] = boxes 258 | return image, target 259 | 260 | 261 | class Compose(object): 262 | def __init__(self, transforms): 263 | self.transforms = transforms 264 | 265 | def __call__(self, image, target): 266 | for t in self.transforms: 267 | image, target = t(image, target) 268 | return image, target 269 | 270 | def __repr__(self): 271 | format_string = self.__class__.__name__ + "(" 272 | for t in self.transforms: 273 | format_string += "\n" 274 | format_string += " {0}".format(t) 275 | format_string += "\n)" 276 | return format_string 277 | -------------------------------------------------------------------------------- /datasets/coco_eval.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | COCO evaluator that works in distributed mode. 4 | 5 | Mostly copy-paste from https://github.com/pytorch/vision/blob/edfd5a7/references/detection/coco_eval.py 6 | The difference is that there is less copy-pasting from pycocotools 7 | in the end of the file, as python3 can suppress prints with contextlib 8 | """ 9 | import os 10 | import contextlib 11 | import copy 12 | import numpy as np 13 | import torch 14 | 15 | from pycocotools.cocoeval import COCOeval 16 | from pycocotools.coco import COCO 17 | import pycocotools.mask as mask_util 18 | 19 | from util.misc import all_gather 20 | 21 | 22 | class CocoEvaluator(object): 23 | def __init__(self, coco_gt, iou_types): 24 | assert isinstance(iou_types, (list, tuple)) 25 | coco_gt = copy.deepcopy(coco_gt) 26 | self.coco_gt = coco_gt 27 | 28 | self.iou_types = iou_types 29 | self.coco_eval = {} 30 | for iou_type in iou_types: 31 | self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type) 32 | 33 | self.img_ids = [] 34 | self.eval_imgs = {k: [] for k in iou_types} 35 | 36 | def update(self, predictions): 37 | img_ids = list(np.unique(list(predictions.keys()))) 38 | self.img_ids.extend(img_ids) 39 | 40 | for iou_type in self.iou_types: 41 | results = self.prepare(predictions, iou_type) 42 | 43 | # suppress pycocotools prints 44 | with open(os.devnull, 'w') as devnull: 45 | with contextlib.redirect_stdout(devnull): 46 | coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO() 47 | coco_eval = self.coco_eval[iou_type] 48 | 49 | coco_eval.cocoDt = coco_dt 50 | coco_eval.params.imgIds = list(img_ids) 51 | img_ids, eval_imgs = evaluate(coco_eval) 52 | 53 | self.eval_imgs[iou_type].append(eval_imgs) 54 | 55 | def synchronize_between_processes(self): 56 | for iou_type in self.iou_types: 57 | self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2) 58 | create_common_coco_eval(self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type]) 59 | 60 | def accumulate(self): 61 | for coco_eval in self.coco_eval.values(): 62 | coco_eval.accumulate() 63 | 64 | def summarize(self): 65 | for iou_type, coco_eval in self.coco_eval.items(): 66 | print("IoU metric: {}".format(iou_type)) 67 | coco_eval.summarize() 68 | 69 | def prepare(self, predictions, iou_type): 70 | if iou_type == "bbox": 71 | return self.prepare_for_coco_detection(predictions) 72 | elif iou_type == "segm": 73 | return self.prepare_for_coco_segmentation(predictions) 74 | elif iou_type == "keypoints": 75 | return self.prepare_for_coco_keypoint(predictions) 76 | else: 77 | raise ValueError("Unknown iou type {}".format(iou_type)) 78 | 79 | def prepare_for_coco_detection(self, predictions): 80 | coco_results = [] 81 | for original_id, prediction in predictions.items(): 82 | if len(prediction) == 0: 83 | continue 84 | 85 | boxes = prediction["boxes"] 86 | boxes = convert_to_xywh(boxes).tolist() 87 | scores = prediction["scores"].tolist() 88 | labels = prediction["labels"].tolist() 89 | 90 | coco_results.extend( 91 | [ 92 | { 93 | "image_id": original_id, 94 | "category_id": labels[k], 95 | "bbox": box, 96 | "score": scores[k], 97 | } 98 | for k, box in enumerate(boxes) 99 | ] 100 | ) 101 | return coco_results 102 | 103 | def prepare_for_coco_segmentation(self, predictions): 104 | coco_results = [] 105 | for original_id, prediction in predictions.items(): 106 | if len(prediction) == 0: 107 | continue 108 | 109 | scores = prediction["scores"] 110 | labels = prediction["labels"] 111 | masks = prediction["masks"] 112 | 113 | masks = masks > 0.5 114 | 115 | scores = prediction["scores"].tolist() 116 | labels = prediction["labels"].tolist() 117 | 118 | rles = [ 119 | mask_util.encode(np.array(mask[0, :, :, np.newaxis], dtype=np.uint8, order="F"))[0] 120 | for mask in masks 121 | ] 122 | for rle in rles: 123 | rle["counts"] = rle["counts"].decode("utf-8") 124 | 125 | coco_results.extend( 126 | [ 127 | { 128 | "image_id": original_id, 129 | "category_id": labels[k], 130 | "segmentation": rle, 131 | "score": scores[k], 132 | } 133 | for k, rle in enumerate(rles) 134 | ] 135 | ) 136 | return coco_results 137 | 138 | def prepare_for_coco_keypoint(self, predictions): 139 | coco_results = [] 140 | for original_id, prediction in predictions.items(): 141 | if len(prediction) == 0: 142 | continue 143 | 144 | boxes = prediction["boxes"] 145 | boxes = convert_to_xywh(boxes).tolist() 146 | scores = prediction["scores"].tolist() 147 | labels = prediction["labels"].tolist() 148 | keypoints = prediction["keypoints"] 149 | keypoints = keypoints.flatten(start_dim=1).tolist() 150 | 151 | coco_results.extend( 152 | [ 153 | { 154 | "image_id": original_id, 155 | "category_id": labels[k], 156 | 'keypoints': keypoint, 157 | "score": scores[k], 158 | } 159 | for k, keypoint in enumerate(keypoints) 160 | ] 161 | ) 162 | return coco_results 163 | 164 | 165 | def convert_to_xywh(boxes): 166 | xmin, ymin, xmax, ymax = boxes.unbind(1) 167 | return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1) 168 | 169 | 170 | def merge(img_ids, eval_imgs): 171 | all_img_ids = all_gather(img_ids) 172 | all_eval_imgs = all_gather(eval_imgs) 173 | 174 | merged_img_ids = [] 175 | for p in all_img_ids: 176 | merged_img_ids.extend(p) 177 | 178 | merged_eval_imgs = [] 179 | for p in all_eval_imgs: 180 | merged_eval_imgs.append(p) 181 | 182 | merged_img_ids = np.array(merged_img_ids) 183 | merged_eval_imgs = np.concatenate(merged_eval_imgs, 2) 184 | 185 | # keep only unique (and in sorted order) images 186 | merged_img_ids, idx = np.unique(merged_img_ids, return_index=True) 187 | merged_eval_imgs = merged_eval_imgs[..., idx] 188 | 189 | return merged_img_ids, merged_eval_imgs 190 | 191 | 192 | def create_common_coco_eval(coco_eval, img_ids, eval_imgs): 193 | img_ids, eval_imgs = merge(img_ids, eval_imgs) 194 | img_ids = list(img_ids) 195 | eval_imgs = list(eval_imgs.flatten()) 196 | 197 | coco_eval.evalImgs = eval_imgs 198 | coco_eval.params.imgIds = img_ids 199 | coco_eval._paramsEval = copy.deepcopy(coco_eval.params) 200 | 201 | 202 | ################################################################# 203 | # From pycocotools, just removed the prints and fixed 204 | # a Python3 bug about unicode not defined 205 | ################################################################# 206 | 207 | 208 | def evaluate(self): 209 | ''' 210 | Run per image evaluation on given images and store results (a list of dict) in self.evalImgs 211 | :return: None 212 | ''' 213 | # tic = time.time() 214 | # print('Running per image evaluation...') 215 | p = self.params 216 | # add backward compatibility if useSegm is specified in params 217 | if p.useSegm is not None: 218 | p.iouType = 'segm' if p.useSegm == 1 else 'bbox' 219 | print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType)) 220 | # print('Evaluate annotation type *{}*'.format(p.iouType)) 221 | p.imgIds = list(np.unique(p.imgIds)) 222 | if p.useCats: 223 | p.catIds = list(np.unique(p.catIds)) 224 | p.maxDets = sorted(p.maxDets) 225 | self.params = p 226 | 227 | self._prepare() 228 | # loop through images, area range, max detection number 229 | catIds = p.catIds if p.useCats else [-1] 230 | 231 | if p.iouType == 'segm' or p.iouType == 'bbox': 232 | computeIoU = self.computeIoU 233 | elif p.iouType == 'keypoints': 234 | computeIoU = self.computeOks 235 | self.ious = { 236 | (imgId, catId): computeIoU(imgId, catId) 237 | for imgId in p.imgIds 238 | for catId in catIds} 239 | 240 | evaluateImg = self.evaluateImg 241 | maxDet = p.maxDets[-1] 242 | evalImgs = [ 243 | evaluateImg(imgId, catId, areaRng, maxDet) 244 | for catId in catIds 245 | for areaRng in p.areaRng 246 | for imgId in p.imgIds 247 | ] 248 | # this is NOT in the pycocotools code, but could be done outside 249 | evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds)) 250 | self._paramsEval = copy.deepcopy(self.params) 251 | # toc = time.time() 252 | # print('DONE (t={:0.2f}s).'.format(toc-tic)) 253 | return p.imgIds, evalImgs 254 | 255 | ################################################################# 256 | # end of straight copy from pycocotools, just removing the prints 257 | ################################################################# 258 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 - present, Facebook, Inc 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **DE⫶TR**: End-to-End Object Detection with Transformers 2 | ======== 3 | 4 | [![Support Ukraine](https://img.shields.io/badge/Support-Ukraine-FFD500?style=flat&labelColor=005BBB)](https://opensource.fb.com/support-ukraine) 5 | 6 | PyTorch training code and pretrained models for **DETR** (**DE**tection **TR**ansformer). 7 | We replace the full complex hand-crafted object detection pipeline with a Transformer, and match Faster R-CNN with a ResNet-50, obtaining **42 AP** on COCO using half the computation power (FLOPs) and the same number of parameters. Inference in 50 lines of PyTorch. 8 | 9 | ![DETR](.github/DETR.png) 10 | 11 | **What it is**. Unlike traditional computer vision techniques, DETR approaches object detection as a direct set prediction problem. It consists of a set-based global loss, which forces unique predictions via bipartite matching, and a Transformer encoder-decoder architecture. 12 | Given a fixed small set of learned object queries, DETR reasons about the relations of the objects and the global image context to directly output the final set of predictions in parallel. Due to this parallel nature, DETR is very fast and efficient. 13 | 14 | **About the code**. We believe that object detection should not be more difficult than classification, 15 | and should not require complex libraries for training and inference. 16 | DETR is very simple to implement and experiment with, and we provide a 17 | [standalone Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/detr_demo.ipynb) 18 | showing how to do inference with DETR in only a few lines of PyTorch code. 19 | Training code follows this idea - it is not a library, 20 | but simply a [main.py](main.py) importing model and criterion 21 | definitions with standard training loops. 22 | 23 | Additionnally, we provide a Detectron2 wrapper in the d2/ folder. See the readme there for more information. 24 | 25 | For details see [End-to-End Object Detection with Transformers](https://ai.facebook.com/research/publications/end-to-end-object-detection-with-transformers) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. 26 | 27 | # Model Zoo 28 | We provide baseline DETR and DETR-DC5 models, and plan to include more in future. 29 | AP is computed on COCO 2017 val5k, and inference time is over the first 100 val5k COCO images, 30 | with torchscript transformer. 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 |
namebackbonescheduleinf_timebox APurlsize
0DETRR505000.03642.0model | logs159Mb
1DETR-DC5R505000.08343.3model | logs159Mb
2DETRR1015000.05043.5model | logs232Mb
3DETR-DC5R1015000.09744.9model | logs232Mb
88 | 89 | COCO val5k evaluation results can be found in this [gist](https://gist.github.com/szagoruyko/9c9ebb8455610958f7deaa27845d7918). 90 | 91 | The models are also available via torch hub, 92 | to load DETR R50 with pretrained weights simply do: 93 | ```python 94 | model = torch.hub.load('facebookresearch/detr:main', 'detr_resnet50', pretrained=True) 95 | ``` 96 | 97 | 98 | COCO panoptic val5k models: 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 |
namebackbonebox APsegm APPQurlsize
0DETRR5038.831.143.4download165Mb
1DETR-DC5R5040.231.944.6download165Mb
2DETRR10140.13345.1download237Mb
145 | 146 | Checkout our [panoptic colab](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/DETR_panoptic.ipynb) 147 | to see how to use and visualize DETR's panoptic segmentation prediction. 148 | 149 | # Notebooks 150 | 151 | We provide a few notebooks in colab to help you get a grasp on DETR: 152 | * [DETR's hands on Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/detr_attention.ipynb): Shows how to load a model from hub, generate predictions, then visualize the attention of the model (similar to the figures of the paper) 153 | * [Standalone Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/detr_demo.ipynb): In this notebook, we demonstrate how to implement a simplified version of DETR from the grounds up in 50 lines of Python, then visualize the predictions. It is a good starting point if you want to gain better understanding the architecture and poke around before diving in the codebase. 154 | * [Panoptic Colab Notebook](https://colab.research.google.com/github/facebookresearch/detr/blob/colab/notebooks/DETR_panoptic.ipynb): Demonstrates how to use DETR for panoptic segmentation and plot the predictions. 155 | 156 | 157 | # Usage - Object detection 158 | There are no extra compiled components in DETR and package dependencies are minimal, 159 | so the code is very simple to use. We provide instructions how to install dependencies via conda. 160 | First, clone the repository locally: 161 | ``` 162 | git clone https://github.com/facebookresearch/detr.git 163 | ``` 164 | Then, install PyTorch 1.5+ and torchvision 0.6+: 165 | ``` 166 | conda install -c pytorch pytorch torchvision 167 | ``` 168 | Install pycocotools (for evaluation on COCO) and scipy (for training): 169 | ``` 170 | conda install cython scipy 171 | pip install -U 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI' 172 | ``` 173 | That's it, should be good to train and evaluate detection models. 174 | 175 | (optional) to work with panoptic install panopticapi: 176 | ``` 177 | pip install git+https://github.com/cocodataset/panopticapi.git 178 | ``` 179 | 180 | ## Data preparation 181 | 182 | Download and extract COCO 2017 train and val images with annotations from 183 | [http://cocodataset.org](http://cocodataset.org/#download). 184 | We expect the directory structure to be the following: 185 | ``` 186 | path/to/coco/ 187 | annotations/ # annotation json files 188 | train2017/ # train images 189 | val2017/ # val images 190 | ``` 191 | 192 | ## Training 193 | To train baseline DETR on a single node with 8 gpus for 300 epochs run: 194 | ``` 195 | python -m torch.distributed.launch --nproc_per_node=8 --use_env main.py --coco_path /path/to/coco 196 | ``` 197 | A single epoch takes 28 minutes, so 300 epoch training 198 | takes around 6 days on a single machine with 8 V100 cards. 199 | To ease reproduction of our results we provide 200 | [results and training logs](https://gist.github.com/szagoruyko/b4c3b2c3627294fc369b899987385a3f) 201 | for 150 epoch schedule (3 days on a single machine), achieving 39.5/60.3 AP/AP50. 202 | 203 | We train DETR with AdamW setting learning rate in the transformer to 1e-4 and 1e-5 in the backbone. 204 | Horizontal flips, scales and crops are used for augmentation. 205 | Images are rescaled to have min size 800 and max size 1333. 206 | The transformer is trained with dropout of 0.1, and the whole model is trained with grad clip of 0.1. 207 | 208 | 209 | ## Evaluation 210 | To evaluate DETR R50 on COCO val5k with a single GPU run: 211 | ``` 212 | python main.py --batch_size 2 --no_aux_loss --eval --resume https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth --coco_path /path/to/coco 213 | ``` 214 | We provide results for all DETR detection models in this 215 | [gist](https://gist.github.com/szagoruyko/9c9ebb8455610958f7deaa27845d7918). 216 | Note that numbers vary depending on batch size (number of images) per GPU. 217 | Non-DC5 models were trained with batch size 2, and DC5 with 1, 218 | so DC5 models show a significant drop in AP if evaluated with more 219 | than 1 image per GPU. 220 | 221 | ## Multinode training 222 | Distributed training is available via Slurm and [submitit](https://github.com/facebookincubator/submitit): 223 | ``` 224 | pip install submitit 225 | ``` 226 | Train baseline DETR-6-6 model on 4 nodes for 300 epochs: 227 | ``` 228 | python run_with_submitit.py --timeout 3000 --coco_path /path/to/coco 229 | ``` 230 | 231 | # Usage - Segmentation 232 | 233 | We show that it is relatively straightforward to extend DETR to predict segmentation masks. We mainly demonstrate strong panoptic segmentation results. 234 | 235 | ## Data preparation 236 | 237 | For panoptic segmentation, you need the panoptic annotations additionally to the coco dataset (see above for the coco dataset). You need to download and extract the [annotations](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip). 238 | We expect the directory structure to be the following: 239 | ``` 240 | path/to/coco_panoptic/ 241 | annotations/ # annotation json files 242 | panoptic_train2017/ # train panoptic annotations 243 | panoptic_val2017/ # val panoptic annotations 244 | ``` 245 | 246 | ## Training 247 | 248 | We recommend training segmentation in two stages: first train DETR to detect all the boxes, and then train the segmentation head. 249 | For panoptic segmentation, DETR must learn to detect boxes for both stuff and things classes. You can train it on a single node with 8 gpus for 300 epochs with: 250 | ``` 251 | python -m torch.distributed.launch --nproc_per_node=8 --use_env main.py --coco_path /path/to/coco --coco_panoptic_path /path/to/coco_panoptic --dataset_file coco_panoptic --output_dir /output/path/box_model 252 | ``` 253 | For instance segmentation, you can simply train a normal box model (or used a pre-trained one we provide). 254 | 255 | Once you have a box model checkpoint, you need to freeze it, and train the segmentation head in isolation. 256 | For panoptic segmentation you can train on a single node with 8 gpus for 25 epochs: 257 | ``` 258 | python -m torch.distributed.launch --nproc_per_node=8 --use_env main.py --masks --epochs 25 --lr_drop 15 --coco_path /path/to/coco --coco_panoptic_path /path/to/coco_panoptic --dataset_file coco_panoptic --frozen_weights /output/path/box_model/checkpoint.pth --output_dir /output/path/segm_model 259 | ``` 260 | For instance segmentation only, simply remove the `dataset_file` and `coco_panoptic_path` arguments from the above command line. 261 | 262 | # License 263 | DETR is released under the Apache 2.0 license. Please see the [LICENSE](LICENSE) file for more information. 264 | 265 | # Contributing 266 | We actively welcome your pull requests! Please see [CONTRIBUTING.md](.github/CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](.github/CODE_OF_CONDUCT.md) for more info. 267 | -------------------------------------------------------------------------------- /d2/detr/detr.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import logging 3 | import math 4 | from typing import List 5 | 6 | import numpy as np 7 | import torch 8 | import torch.distributed as dist 9 | import torch.nn.functional as F 10 | from scipy.optimize import linear_sum_assignment 11 | from torch import nn 12 | 13 | from detectron2.layers import ShapeSpec 14 | from detectron2.modeling import META_ARCH_REGISTRY, build_backbone, detector_postprocess 15 | from detectron2.structures import Boxes, ImageList, Instances, BitMasks, PolygonMasks 16 | from detectron2.utils.logger import log_first_n 17 | from fvcore.nn import giou_loss, smooth_l1_loss 18 | from models.backbone import Joiner 19 | from models.detr import DETR, SetCriterion 20 | from models.matcher import HungarianMatcher 21 | from models.position_encoding import PositionEmbeddingSine 22 | from models.transformer import Transformer 23 | from models.segmentation import DETRsegm, PostProcessPanoptic, PostProcessSegm 24 | from util.box_ops import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh 25 | from util.misc import NestedTensor 26 | from datasets.coco import convert_coco_poly_to_mask 27 | 28 | __all__ = ["Detr"] 29 | 30 | 31 | class MaskedBackbone(nn.Module): 32 | """ This is a thin wrapper around D2's backbone to provide padding masking""" 33 | 34 | def __init__(self, cfg): 35 | super().__init__() 36 | self.backbone = build_backbone(cfg) 37 | backbone_shape = self.backbone.output_shape() 38 | self.feature_strides = [backbone_shape[f].stride for f in backbone_shape.keys()] 39 | # 最后的channel的数量 40 | self.num_channels = backbone_shape[list(backbone_shape.keys())[-1]].channels 41 | 42 | def forward(self, images): 43 | features = self.backbone(images.tensor) 44 | masks = self.mask_out_padding( 45 | [features_per_level.shape for features_per_level in features.values()], 46 | images.image_sizes, 47 | images.tensor.device, 48 | ) 49 | assert len(features) == len(masks) 50 | for i, k in enumerate(features.keys()): 51 | features[k] = NestedTensor(features[k], masks[i]) 52 | return features 53 | 54 | def mask_out_padding(self, feature_shapes, image_sizes, device): 55 | masks = [] 56 | assert len(feature_shapes) == len(self.feature_strides) 57 | for idx, shape in enumerate(feature_shapes): 58 | N, _, H, W = shape 59 | # 全1 60 | masks_per_feature_level = torch.ones((N, H, W), dtype=torch.bool, device=device) 61 | 62 | for img_idx, (h, w) in enumerate(image_sizes): 63 | masks_per_feature_level[ 64 | img_idx, 65 | : int(np.ceil(float(h) / self.feature_strides[idx])), 66 | : int(np.ceil(float(w) / self.feature_strides[idx])), 67 | ] = 0 68 | masks.append(masks_per_feature_level) 69 | return masks 70 | 71 | 72 | # 总结构,类似detectron2中的meta_arch文件夹中的内容 73 | @META_ARCH_REGISTRY.register() 74 | class Detr(nn.Module): 75 | """ 76 | Implement Detr 77 | """ 78 | 79 | def __init__(self, cfg): 80 | super().__init__() 81 | 82 | self.device = torch.device(cfg.MODEL.DEVICE) 83 | # 类别数量 84 | self.num_classes = cfg.MODEL.DETR.NUM_CLASSES 85 | self.mask_on = cfg.MODEL.MASK_ON 86 | # 256 87 | hidden_dim = cfg.MODEL.DETR.HIDDEN_DIM 88 | # 100 89 | num_queries = cfg.MODEL.DETR.NUM_OBJECT_QUERIES 90 | # Transformer parameters: 91 | # multi head 92 | nheads = cfg.MODEL.DETR.NHEADS 93 | # transformer 内的使用的dropout 94 | dropout = cfg.MODEL.DETR.DROPOUT 95 | dim_feedforward = cfg.MODEL.DETR.DIM_FEEDFORWARD 96 | enc_layers = cfg.MODEL.DETR.ENC_LAYERS 97 | dec_layers = cfg.MODEL.DETR.DEC_LAYERS 98 | pre_norm = cfg.MODEL.DETR.PRE_NORM 99 | 100 | # Loss parameters: 101 | giou_weight = cfg.MODEL.DETR.GIOU_WEIGHT 102 | l1_weight = cfg.MODEL.DETR.L1_WEIGHT 103 | # 关于辅助loss Auxiliary decoding losses 104 | # We found helpful to use auxiliary losses in decoder during training 105 | # especially to help the model output the correct number of objects of each class 106 | deep_supervision = cfg.MODEL.DETR.DEEP_SUPERVISION 107 | no_object_weight = cfg.MODEL.DETR.NO_OBJECT_WEIGHT 108 | 109 | N_steps = hidden_dim // 2 110 | # 创建backbone 111 | d2_backbone = MaskedBackbone(cfg) 112 | 113 | backbone = Joiner(d2_backbone, PositionEmbeddingSine(N_steps, normalize=True)) 114 | backbone.num_channels = d2_backbone.num_channels 115 | # 创建transformer 116 | transformer = Transformer( 117 | d_model=hidden_dim, 118 | dropout=dropout, 119 | nhead=nheads, 120 | dim_feedforward=dim_feedforward, 121 | num_encoder_layers=enc_layers, 122 | num_decoder_layers=dec_layers, 123 | normalize_before=pre_norm, 124 | return_intermediate_dec=deep_supervision, 125 | ) 126 | 127 | # 内置的,总的检测的model 128 | self.detr = DETR( 129 | backbone, transformer, num_classes=self.num_classes, num_queries=num_queries, aux_loss=deep_supervision 130 | ) 131 | 132 | if self.mask_on: 133 | frozen_weights = cfg.MODEL.DETR.FROZEN_WEIGHTS 134 | if frozen_weights != '': 135 | print("LOAD pre-trained weights") 136 | weight = torch.load(frozen_weights, map_location=lambda storage, loc: storage)['model'] 137 | new_weight = {} 138 | for k, v in weight.items(): 139 | if 'detr.' in k: 140 | new_weight[k.replace('detr.', '')] = v 141 | else: 142 | print(f"Skipping loading weight {k} from frozen model") 143 | del weight 144 | self.detr.load_state_dict(new_weight) 145 | del new_weight 146 | self.detr = DETRsegm(self.detr, freeze_detr=(frozen_weights != '')) 147 | self.seg_postprocess = PostProcessSegm 148 | 149 | self.detr.to(self.device) 150 | 151 | # building criterion 152 | matcher = HungarianMatcher(cost_class=1, cost_bbox=l1_weight, cost_giou=giou_weight) 153 | weight_dict = {"loss_ce": 1, "loss_bbox": l1_weight} 154 | weight_dict["loss_giou"] = giou_weight 155 | if deep_supervision: 156 | aux_weight_dict = {} 157 | for i in range(dec_layers - 1): 158 | aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()}) 159 | weight_dict.update(aux_weight_dict) 160 | 161 | losses = ["labels", "boxes", "cardinality"] 162 | 163 | if self.mask_on: 164 | losses += ["masks"] 165 | 166 | self.criterion = SetCriterion( 167 | self.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=no_object_weight, losses=losses, 168 | ) 169 | self.criterion.to(self.device) 170 | 171 | pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(3, 1, 1) 172 | pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(3, 1, 1) 173 | 174 | self.normalizer = lambda x: (x - pixel_mean) / pixel_std 175 | 176 | self.to(self.device) 177 | 178 | def forward(self, batched_inputs): 179 | """ 180 | Args: 181 | batched_inputs: a list, batched outputs of :class:`DatasetMapper` . 182 | Each item in the list contains the inputs for one image. 183 | For now, each item in the list is a dict that contains: 184 | 185 | * image: Tensor, image in (C, H, W) format. 186 | * instances: Instances 187 | 188 | Other information that's included in the original dicts, such as: 189 | 190 | * "height", "width" (int): the output resolution of the model, used in inference. 191 | See :meth:`postprocess` for details. 192 | Returns: 193 | dict[str: Tensor]: 194 | mapping from a named loss to a tensor storing the loss. Used during training only. 195 | """ 196 | # 图像预处理 197 | images = self.preprocess_image(batched_inputs) 198 | # 经过检测网络 199 | output = self.detr(images) 200 | 201 | if self.training: 202 | # 训练模式,最后输出是loss 203 | gt_instances = [x["instances"].to(self.device) for x in batched_inputs] 204 | # 在这之前的box的尺寸是正常的,几十,几百的数字 205 | # 经过prepare_targets之后,都变成1以内 206 | targets = self.prepare_targets(gt_instances) 207 | loss_dict = self.criterion(output, targets) 208 | 209 | # 每一项的权重 210 | weight_dict = self.criterion.weight_dict 211 | for k in loss_dict.keys(): 212 | if k in weight_dict: 213 | loss_dict[k] *= weight_dict[k] 214 | 215 | return loss_dict 216 | else: 217 | # 推理模式,最后是预测结果 218 | box_cls = output["pred_logits"] 219 | box_pred = output["pred_boxes"] 220 | mask_pred = output["pred_masks"] if self.mask_on else None 221 | results = self.inference(box_cls, box_pred, mask_pred, images.image_sizes) 222 | processed_results = [] 223 | for results_per_image, input_per_image, image_size in zip(results, batched_inputs, images.image_sizes): 224 | height = input_per_image.get("height", image_size[0]) 225 | width = input_per_image.get("width", image_size[1]) 226 | r = detector_postprocess(results_per_image, height, width) 227 | processed_results.append({"instances": r}) 228 | return processed_results 229 | 230 | def prepare_targets(self, targets): 231 | 232 | new_targets = [] 233 | for targets_per_image in targets: 234 | # 图像的宽高 235 | h, w = targets_per_image.image_size 236 | # wh wh 237 | image_size_xyxy = torch.as_tensor([w, h, w, h], dtype=torch.float, device=self.device) 238 | # gt的类别 239 | gt_classes = targets_per_image.gt_classes 240 | # 因为不需要anchor的原因么,就不在需要知道很大的尺寸,也没有不同的特征层的stride的考虑 241 | gt_boxes = targets_per_image.gt_boxes.tensor / image_size_xyxy 242 | # 变成中心点和宽高的形式 243 | gt_boxes = box_xyxy_to_cxcywh(gt_boxes) 244 | new_targets.append({"labels": gt_classes, "boxes": gt_boxes}) 245 | if self.mask_on and hasattr(targets_per_image, 'gt_masks'): 246 | gt_masks = targets_per_image.gt_masks 247 | gt_masks = convert_coco_poly_to_mask(gt_masks.polygons, h, w) 248 | new_targets[-1].update({'masks': gt_masks}) 249 | return new_targets 250 | 251 | def inference(self, box_cls, box_pred, mask_pred, image_sizes): 252 | """ 253 | 执行推理 254 | Arguments: 255 | box_cls (Tensor): tensor of shape (batch_size, num_queries, K). 256 | The tensor predicts the classification probability for each query. 257 | box_pred (Tensor): tensors of shape (batch_size, num_queries, 4). 258 | The tensor predicts 4-vector (x,y,w,h) box 259 | regression values for every queryx 260 | image_sizes (List[torch.Size]): the input image sizes 261 | 262 | Returns: 263 | results (List[Instances]): a list of #images elements. 264 | """ 265 | assert len(box_cls) == len(image_sizes) 266 | results = [] 267 | 268 | # For each box we assign the best class or the second best if the best on is `no_object`. 269 | scores, labels = F.softmax(box_cls, dim=-1)[:, :, :-1].max(-1) 270 | 271 | for i, (scores_per_image, labels_per_image, box_pred_per_image, image_size) in enumerate(zip( 272 | scores, labels, box_pred, image_sizes 273 | )): 274 | result = Instances(image_size) 275 | result.pred_boxes = Boxes(box_cxcywh_to_xyxy(box_pred_per_image)) 276 | 277 | result.pred_boxes.scale(scale_x=image_size[1], scale_y=image_size[0]) 278 | if self.mask_on: 279 | mask = F.interpolate(mask_pred[i].unsqueeze(0), size=image_size, mode='bilinear', align_corners=False) 280 | mask = mask[0].sigmoid() > 0.5 281 | B, N, H, W = mask_pred.shape 282 | mask = BitMasks(mask.cpu()).crop_and_resize(result.pred_boxes.tensor.cpu(), 32) 283 | result.pred_masks = mask.unsqueeze(1).to(mask_pred[0].device) 284 | 285 | result.scores = scores_per_image 286 | result.pred_classes = labels_per_image 287 | results.append(result) 288 | return results 289 | 290 | def preprocess_image(self, batched_inputs): 291 | """ 292 | Normalize, pad and batch the input images. 293 | """ 294 | images = [self.normalizer(x["image"].to(self.device)) for x in batched_inputs] 295 | images = ImageList.from_tensors(images) 296 | return images 297 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | import argparse 3 | import datetime 4 | import json 5 | import random 6 | import time 7 | from pathlib import Path 8 | 9 | import numpy as np 10 | import torch 11 | from torch.utils.data import DataLoader, DistributedSampler 12 | 13 | import datasets 14 | import util.misc as utils 15 | from datasets import build_dataset, get_coco_api_from_dataset 16 | from engine import evaluate, train_one_epoch 17 | from models import build_model 18 | 19 | 20 | def get_args_parser(): 21 | parser = argparse.ArgumentParser('Set transformer detector', add_help=False) 22 | # batch_size 改成了3 23 | parser.add_argument('--batch_size', default=3, type=int) 24 | parser.add_argument('--epochs', default=300, type=int) 25 | 26 | # lr 27 | parser.add_argument('--lr', default=1e-4, type=float) 28 | # backbone lr 29 | parser.add_argument('--lr_backbone', default=1e-5, type=float) 30 | 31 | parser.add_argument('--weight_decay', default=1e-4, type=float) 32 | parser.add_argument('--lr_drop', default=200, type=int) 33 | # 梯度裁剪 34 | parser.add_argument('--clip_max_norm', default=0.1, type=float, 35 | help='gradient clipping max norm') 36 | 37 | # Model parameters 38 | parser.add_argument('--frozen_weights', type=str, default=None, 39 | help="Path to the pretrained model. If set, only the mask head will be trained") 40 | # * Backbone 41 | parser.add_argument('--backbone', default='resnet50', type=str, 42 | help="Name of the convolutional backbone to use") 43 | # dc5 44 | parser.add_argument('--dilation', action='store_true', 45 | help="If true, we replace stride with dilation in the last convolutional block (DC5)") 46 | 47 | parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'), 48 | help="Type of positional embedding to use on top of the image features") 49 | 50 | # * Transformer 51 | # encoder的层数 52 | parser.add_argument('--enc_layers', default=6, type=int, 53 | help="Number of encoding layers in the transformer") 54 | # decoder的层数 55 | parser.add_argument('--dec_layers', default=6, type=int, 56 | help="Number of decoding layers in the transformer") 57 | parser.add_argument('--dim_feedforward', default=2048, type=int, 58 | help="Intermediate size of the feedforward layers in the transformer blocks") 59 | parser.add_argument('--hidden_dim', default=256, type=int, 60 | help="Size of the embeddings (dimension of the transformer)") 61 | parser.add_argument('--dropout', default=0.1, type=float, 62 | help="Dropout applied in the transformer") 63 | # 注意力头的数量 64 | parser.add_argument('--nheads', default=8, type=int, 65 | help="Number of attention heads inside the transformer's attentions") 66 | # 100个目标query 67 | parser.add_argument('--num_queries', default=100, type=int, 68 | help="Number of query slots") 69 | 70 | parser.add_argument('--pre_norm', action='store_true') 71 | 72 | # * Segmentation 73 | parser.add_argument('--masks', action='store_true', 74 | help="Train segmentation head if the flag is provided") 75 | 76 | # Loss 77 | # 不使用辅助loss 78 | parser.add_argument('--no_aux_loss', dest='aux_loss', action='store_false', 79 | help="Disables auxiliary decoding losses (loss at each layer)") 80 | # * Matcher 81 | # 分类损失的权重值 82 | parser.add_argument('--set_cost_class', default=1, type=float, 83 | help="Class coefficient in the matching cost") 84 | # L1 Loss的权重值 85 | parser.add_argument('--set_cost_bbox', default=5, type=float, 86 | help="L1 box coefficient in the matching cost") 87 | # GIoU Loss的权重值 88 | parser.add_argument('--set_cost_giou', default=2, type=float, 89 | help="giou box coefficient in the matching cost") 90 | # * Loss coefficients 91 | 92 | parser.add_argument('--mask_loss_coef', default=1, type=float) 93 | parser.add_argument('--dice_loss_coef', default=1, type=float) 94 | parser.add_argument('--bbox_loss_coef', default=5, type=float) 95 | parser.add_argument('--giou_loss_coef', default=2, type=float) 96 | # 论文中提到的0.1系数 97 | parser.add_argument('--eos_coef', default=0.1, type=float, 98 | help="Relative classification weight of the no-object class") 99 | 100 | # dataset parameters 101 | parser.add_argument('--dataset_file', default='coco') 102 | parser.add_argument('--coco_path', type=str) 103 | parser.add_argument('--coco_panoptic_path', type=str) 104 | parser.add_argument('--remove_difficult', action='store_true') 105 | 106 | parser.add_argument('--output_dir', default='', 107 | help='path where to save, empty for no saving') 108 | parser.add_argument('--device', default='cuda', 109 | help='device to use for training / testing') 110 | # 小宇宙,给我力量吧 111 | parser.add_argument('--seed', default=42, type=int) 112 | parser.add_argument('--resume', default='', help='resume from checkpoint') 113 | parser.add_argument('--start_epoch', default=0, type=int, metavar='N', 114 | help='start epoch') 115 | parser.add_argument('--eval', action='store_true') 116 | parser.add_argument('--num_workers', default=4, type=int) 117 | 118 | # distributed training parameters 119 | parser.add_argument('--world_size', default=1, type=int, 120 | help='number of distributed processes') 121 | parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') 122 | return parser 123 | 124 | 125 | # ---------------------------------------------------------------------------------------------------------------------- 126 | # ---------------------------------------------------------------------------------------------------------------------- 127 | # ---------------------------------------------------------------------------------------------------------------------- 128 | 129 | def main(args): 130 | # 分布训练初始化步骤 131 | utils.init_distributed_mode(args) 132 | print("git:\n {}\n".format(utils.get_sha())) 133 | 134 | if args.frozen_weights is not None: 135 | assert args.masks, "Frozen training is meant for segmentation only" 136 | print(args) 137 | 138 | device = torch.device(args.device) 139 | 140 | # fix the seed for reproducibility 141 | seed = args.seed + utils.get_rank() 142 | torch.manual_seed(seed) 143 | np.random.seed(seed) 144 | random.seed(seed) 145 | # postprocessors 只有在进行评估的时候会被使用 146 | model, criterion, postprocessors = build_model(args) 147 | model.to(device) 148 | 149 | print(model) 150 | 151 | model_without_ddp = model 152 | if args.distributed: 153 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) 154 | model_without_ddp = model.module 155 | 156 | # 参数量 157 | n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) 158 | print('number of params:', n_parameters) 159 | 160 | param_dicts = [ 161 | {"params": [p for n, p in model_without_ddp.named_parameters() if "backbone" not in n and p.requires_grad]}, 162 | # 第二个部分是backbone的参数以及对应的学习率 163 | { 164 | "params": [p for n, p in model_without_ddp.named_parameters() if "backbone" in n and p.requires_grad], 165 | "lr": args.lr_backbone, 166 | }, 167 | ] 168 | optimizer = torch.optim.AdamW(param_dicts, lr=args.lr, weight_decay=args.weight_decay) 169 | lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, args.lr_drop) 170 | 171 | # 数据集创建部分 ----------------------------------------------------------------------------------------------------- 172 | 173 | dataset_train = build_dataset(image_set='train', args=args) 174 | dataset_val = build_dataset(image_set='val', args=args) 175 | 176 | if args.distributed: 177 | sampler_train = DistributedSampler(dataset_train) 178 | sampler_val = DistributedSampler(dataset_val, shuffle=False) 179 | else: 180 | sampler_train = torch.utils.data.RandomSampler(dataset_train) 181 | sampler_val = torch.utils.data.SequentialSampler(dataset_val) 182 | 183 | batch_sampler_train = torch.utils.data.BatchSampler( 184 | sampler_train, args.batch_size, drop_last=True) 185 | 186 | data_loader_train = DataLoader(dataset_train, batch_sampler=batch_sampler_train, 187 | collate_fn=utils.collate_fn, num_workers=args.num_workers) 188 | data_loader_val = DataLoader(dataset_val, args.batch_size, sampler=sampler_val, 189 | drop_last=False, collate_fn=utils.collate_fn, num_workers=args.num_workers) 190 | 191 | # ----------------------------------------------------------------------------------------------------- 192 | 193 | if args.dataset_file == "coco_panoptic": 194 | # We also evaluate AP during panoptic training, on original coco DS 195 | coco_val = datasets.coco.build("val", args) 196 | base_ds = get_coco_api_from_dataset(coco_val) 197 | else: 198 | base_ds = get_coco_api_from_dataset(dataset_val) 199 | 200 | if args.frozen_weights is not None: 201 | checkpoint = torch.load(args.frozen_weights, map_location='cpu') 202 | model_without_ddp.detr.load_state_dict(checkpoint['model']) 203 | 204 | output_dir = Path(args.output_dir) 205 | 206 | # 恢复训练的一些设置 207 | if args.resume: 208 | if args.resume.startswith('https'): 209 | checkpoint = torch.hub.load_state_dict_from_url( 210 | args.resume, map_location='cpu', check_hash=True) 211 | else: 212 | checkpoint = torch.load(args.resume, map_location='cpu') 213 | model_without_ddp.load_state_dict(checkpoint['model']) 214 | if not args.eval and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint: 215 | optimizer.load_state_dict(checkpoint['optimizer']) 216 | lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) 217 | args.start_epoch = checkpoint['epoch'] + 1 218 | 219 | # 评估模式 220 | if args.eval: 221 | 222 | test_stats, coco_evaluator = evaluate(model, criterion, postprocessors, 223 | data_loader_val, base_ds, device, args.output_dir) 224 | if args.output_dir: 225 | utils.save_on_master(coco_evaluator.coco_eval["bbox"].eval, output_dir / "eval.pth") 226 | return 227 | 228 | print("Start training") 229 | start_time = time.time() 230 | for epoch in range(args.start_epoch, args.epochs): 231 | if args.distributed: 232 | sampler_train.set_epoch(epoch) 233 | # 训练方法 234 | train_stats = train_one_epoch( 235 | model, criterion, data_loader_train, optimizer, device, epoch, 236 | args.clip_max_norm) 237 | # 学习率更新 238 | lr_scheduler.step() 239 | if args.output_dir: 240 | # 在每个epoch后保存的文件都会刷新这个文件 241 | checkpoint_paths = [output_dir / 'checkpoint.pth'] 242 | # extra checkpoint before LR drop and every 100 epochs 243 | if (epoch + 1) % args.lr_drop == 0 or (epoch + 1) % 100 == 0: 244 | # 每隔100个epoch,或者在lr_drop之前,保存一个 245 | checkpoint_paths.append(output_dir / f'checkpoint{epoch:04}.pth') 246 | for checkpoint_path in checkpoint_paths: 247 | # 只有主进程保存即可 248 | utils.save_on_master({ 249 | 'model': model_without_ddp.state_dict(), 250 | 'optimizer': optimizer.state_dict(), 251 | 'lr_scheduler': lr_scheduler.state_dict(), 252 | 'epoch': epoch, 253 | 'args': args, 254 | }, checkpoint_path) 255 | 256 | # 每个epoch后进行一次评估 257 | test_stats, coco_evaluator = evaluate( 258 | model, criterion, postprocessors, data_loader_val, base_ds, device, args.output_dir 259 | ) 260 | 261 | log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 262 | **{f'test_{k}': v for k, v in test_stats.items()}, 263 | 'epoch': epoch, 264 | 'n_parameters': n_parameters} 265 | 266 | if args.output_dir and utils.is_main_process(): 267 | # 保存训练,以及评估信息 268 | with (output_dir / "log.txt").open("a") as f: 269 | f.write(json.dumps(log_stats) + "\n") 270 | 271 | # 保存评估结果 272 | # for evaluation logs 273 | if coco_evaluator is not None: 274 | (output_dir / 'eval').mkdir(exist_ok=True) 275 | 276 | if "bbox" in coco_evaluator.coco_eval: 277 | # 当前epoch 278 | filenames = ['latest.pth'] 279 | # 每隔50个epoch 280 | if epoch % 50 == 0: 281 | filenames.append(f'{epoch:03}.pth') 282 | for name in filenames: 283 | torch.save(coco_evaluator.coco_eval["bbox"].eval, 284 | output_dir / "eval" / name) 285 | 286 | total_time = time.time() - start_time 287 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 288 | print('Training time {}'.format(total_time_str)) 289 | 290 | 291 | if __name__ == '__main__': 292 | parser = argparse.ArgumentParser('DETR training and evaluation script', parents=[get_args_parser()]) 293 | args = parser.parse_args() 294 | # 创建输出文件目录 295 | if args.output_dir: 296 | Path(args.output_dir).mkdir(parents=True, exist_ok=True) 297 | main(args) 298 | -------------------------------------------------------------------------------- /models/segmentation.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | This file provides the definition of the convolutional heads used to predict masks, as well as the losses 4 | """ 5 | import io 6 | from collections import defaultdict 7 | from typing import List, Optional 8 | 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | from torch import Tensor 13 | from PIL import Image 14 | 15 | import util.box_ops as box_ops 16 | from util.misc import NestedTensor, interpolate, nested_tensor_from_tensor_list 17 | 18 | try: 19 | from panopticapi.utils import id2rgb, rgb2id 20 | except ImportError: 21 | pass 22 | 23 | 24 | class DETRsegm(nn.Module): 25 | def __init__(self, detr, freeze_detr=False): 26 | super().__init__() 27 | self.detr = detr 28 | 29 | if freeze_detr: 30 | for p in self.parameters(): 31 | p.requires_grad_(False) 32 | 33 | hidden_dim, nheads = detr.transformer.d_model, detr.transformer.nhead 34 | 35 | self.bbox_attention = MHAttentionMap(hidden_dim, hidden_dim, nheads, dropout=0.0) 36 | 37 | self.mask_head = MaskHeadSmallConv(hidden_dim + nheads, [1024, 512, 256], hidden_dim) 38 | 39 | def forward(self, samples: NestedTensor): 40 | if isinstance(samples, (list, torch.Tensor)): 41 | samples = nested_tensor_from_tensor_list(samples) 42 | 43 | 44 | features, pos = self.detr.backbone(samples) 45 | 46 | bs = features[-1].tensors.shape[0] 47 | 48 | src, mask = features[-1].decompose() 49 | assert mask is not None 50 | 51 | src_proj = self.detr.input_proj(src) 52 | 53 | hs, memory = self.detr.transformer(src_proj, mask, self.detr.query_embed.weight, pos[-1]) 54 | 55 | 56 | outputs_class = self.detr.class_embed(hs) 57 | 58 | outputs_coord = self.detr.bbox_embed(hs).sigmoid() 59 | out = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord[-1]} 60 | if self.detr.aux_loss: 61 | out['aux_outputs'] = self.detr._set_aux_loss(outputs_class, outputs_coord) 62 | 63 | 64 | # FIXME h_boxes takes the last one computed, keep this in mind 65 | bbox_mask = self.bbox_attention(hs[-1], memory, mask=mask) 66 | 67 | 68 | seg_masks = self.mask_head(src_proj, bbox_mask, [features[2].tensors, 69 | features[1].tensors, 70 | features[0].tensors]) 71 | outputs_seg_masks = seg_masks.view(bs, self.detr.num_queries, seg_masks.shape[-2], seg_masks.shape[-1]) 72 | 73 | out["pred_masks"] = outputs_seg_masks 74 | return out 75 | 76 | 77 | def _expand(tensor, length: int): 78 | 79 | return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1) 80 | 81 | 82 | class MaskHeadSmallConv(nn.Module): 83 | """ 84 | Simple convolutional head, using group norm. 85 | Upsampling is done using a FPN approach 86 | """ 87 | 88 | def __init__(self, dim, fpn_dims, context_dim): 89 | super().__init__() 90 | 91 | inter_dims = [dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64] 92 | 93 | self.lay1 = torch.nn.Conv2d(dim, dim, 3, padding=1) 94 | self.gn1 = torch.nn.GroupNorm(8, dim) 95 | self.lay2 = torch.nn.Conv2d(dim, inter_dims[1], 3, padding=1) 96 | self.gn2 = torch.nn.GroupNorm(8, inter_dims[1]) 97 | 98 | self.lay3 = torch.nn.Conv2d(inter_dims[1], inter_dims[2], 3, padding=1) 99 | self.gn3 = torch.nn.GroupNorm(8, inter_dims[2]) 100 | 101 | self.lay4 = torch.nn.Conv2d(inter_dims[2], inter_dims[3], 3, padding=1) 102 | self.gn4 = torch.nn.GroupNorm(8, inter_dims[3]) 103 | 104 | self.lay5 = torch.nn.Conv2d(inter_dims[3], inter_dims[4], 3, padding=1) 105 | self.gn5 = torch.nn.GroupNorm(8, inter_dims[4]) 106 | 107 | self.out_lay = torch.nn.Conv2d(inter_dims[4], 1, 3, padding=1) 108 | 109 | self.dim = dim 110 | 111 | 112 | self.adapter1 = torch.nn.Conv2d(fpn_dims[0], inter_dims[1], 1) 113 | self.adapter2 = torch.nn.Conv2d(fpn_dims[1], inter_dims[2], 1) 114 | self.adapter3 = torch.nn.Conv2d(fpn_dims[2], inter_dims[3], 1) 115 | 116 | for m in self.modules(): 117 | if isinstance(m, nn.Conv2d): 118 | nn.init.kaiming_uniform_(m.weight, a=1) 119 | nn.init.constant_(m.bias, 0) 120 | 121 | def forward(self, x: Tensor, bbox_mask: Tensor, fpns: List[Tensor]): 122 | 123 | x = torch.cat([_expand(x, bbox_mask.shape[1]), bbox_mask.flatten(0, 1)], 1) 124 | 125 | x = self.lay1(x) 126 | x = self.gn1(x) 127 | x = F.relu(x) 128 | x = self.lay2(x) 129 | x = self.gn2(x) 130 | x = F.relu(x) 131 | 132 | 133 | cur_fpn = self.adapter1(fpns[0]) 134 | 135 | if cur_fpn.size(0) != x.size(0): 136 | cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0)) 137 | 138 | x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest") 139 | 140 | x = self.lay3(x) 141 | 142 | x = self.gn3(x) 143 | 144 | x = F.relu(x) 145 | 146 | cur_fpn = self.adapter2(fpns[1]) 147 | if cur_fpn.size(0) != x.size(0): 148 | cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0)) 149 | 150 | x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest") 151 | 152 | x = self.lay4(x) 153 | x = self.gn4(x) 154 | x = F.relu(x) 155 | 156 | cur_fpn = self.adapter3(fpns[2]) 157 | if cur_fpn.size(0) != x.size(0): 158 | cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0)) 159 | 160 | x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest") 161 | 162 | x = self.lay5(x) 163 | x = self.gn5(x) 164 | x = F.relu(x) 165 | 166 | x = self.out_lay(x) 167 | return x 168 | 169 | 170 | class MHAttentionMap(nn.Module): 171 | 172 | """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)""" 173 | 174 | def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True): 175 | super().__init__() 176 | self.num_heads = num_heads 177 | self.hidden_dim = hidden_dim 178 | self.dropout = nn.Dropout(dropout) 179 | 180 | self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias) 181 | self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias) 182 | 183 | nn.init.zeros_(self.k_linear.bias) 184 | nn.init.zeros_(self.q_linear.bias) 185 | nn.init.xavier_uniform_(self.k_linear.weight) 186 | nn.init.xavier_uniform_(self.q_linear.weight) 187 | 188 | self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5 189 | 190 | def forward(self, q, k, mask: Optional[Tensor] = None): 191 | 192 | q = self.q_linear(q) 193 | k = F.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias) 194 | qh = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads) 195 | kh = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1]) 196 | weights = torch.einsum("bqnc,bnchw->bqnhw", qh * self.normalize_fact, kh) 197 | 198 | if mask is not None: 199 | weights.masked_fill_(mask.unsqueeze(1).unsqueeze(1), float("-inf")) 200 | weights = F.softmax(weights.flatten(2), dim=-1).view(weights.size()) 201 | weights = self.dropout(weights) 202 | return weights 203 | 204 | 205 | def dice_loss(inputs, targets, num_boxes): 206 | """ 207 | Compute the DICE loss, similar to generalized IOU for masks 208 | Args: 209 | inputs: A float tensor of arbitrary shape. 210 | The predictions for each example. 211 | targets: A float tensor with the same shape as inputs. Stores the binary 212 | classification label for each element in inputs 213 | (0 for the negative class and 1 for the positive class). 214 | """ 215 | inputs = inputs.sigmoid() 216 | inputs = inputs.flatten(1) 217 | numerator = 2 * (inputs * targets).sum(1) 218 | denominator = inputs.sum(-1) + targets.sum(-1) 219 | loss = 1 - (numerator + 1) / (denominator + 1) 220 | return loss.sum() / num_boxes 221 | 222 | 223 | def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2): 224 | """ 225 | Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. 226 | Args: 227 | inputs: A float tensor of arbitrary shape. 228 | The predictions for each example. 229 | targets: A float tensor with the same shape as inputs. Stores the binary 230 | classification label for each element in inputs 231 | (0 for the negative class and 1 for the positive class). 232 | alpha: (optional) Weighting factor in range (0,1) to balance 233 | positive vs negative examples. Default = -1 (no weighting). 234 | gamma: Exponent of the modulating factor (1 - p_t) to 235 | balance easy vs hard examples. 236 | Returns: 237 | Loss tensor 238 | """ 239 | prob = inputs.sigmoid() 240 | ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") 241 | p_t = prob * targets + (1 - prob) * (1 - targets) 242 | loss = ce_loss * ((1 - p_t) ** gamma) 243 | 244 | if alpha >= 0: 245 | alpha_t = alpha * targets + (1 - alpha) * (1 - targets) 246 | loss = alpha_t * loss 247 | 248 | return loss.mean(1).sum() / num_boxes 249 | 250 | 251 | class PostProcessSegm(nn.Module): 252 | def __init__(self, threshold=0.5): 253 | super().__init__() 254 | self.threshold = threshold 255 | 256 | @torch.no_grad() 257 | def forward(self, results, outputs, orig_target_sizes, max_target_sizes): 258 | assert len(orig_target_sizes) == len(max_target_sizes) 259 | max_h, max_w = max_target_sizes.max(0)[0].tolist() 260 | outputs_masks = outputs["pred_masks"].squeeze(2) 261 | outputs_masks = F.interpolate(outputs_masks, size=(max_h, max_w), mode="bilinear", align_corners=False) 262 | outputs_masks = (outputs_masks.sigmoid() > self.threshold).cpu() 263 | 264 | for i, (cur_mask, t, tt) in enumerate(zip(outputs_masks, max_target_sizes, orig_target_sizes)): 265 | img_h, img_w = t[0], t[1] 266 | results[i]["masks"] = cur_mask[:, :img_h, :img_w].unsqueeze(1) 267 | results[i]["masks"] = F.interpolate( 268 | results[i]["masks"].float(), size=tuple(tt.tolist()), mode="nearest" 269 | ).byte() 270 | 271 | return results 272 | 273 | 274 | class PostProcessPanoptic(nn.Module): 275 | """This class converts the output of the model to the final panoptic result, in the format expected by the 276 | coco panoptic API """ 277 | 278 | def __init__(self, is_thing_map, threshold=0.85): 279 | """ 280 | Parameters: 281 | is_thing_map: This is a whose keys are the class ids, and the values a boolean indicating whether 282 | the class is a thing (True) or a stuff (False) class 283 | threshold: confidence threshold: segments with confidence lower than this will be deleted 284 | """ 285 | super().__init__() 286 | self.threshold = threshold 287 | self.is_thing_map = is_thing_map 288 | 289 | def forward(self, outputs, processed_sizes, target_sizes=None): 290 | """ This function computes the panoptic prediction from the model's predictions. 291 | Parameters: 292 | outputs: This is a dict coming directly from the model. See the model doc for the content. 293 | processed_sizes: This is a list of tuples (or torch tensors) of sizes of the images that were passed to the 294 | model, ie the size after data augmentation but before batching. 295 | target_sizes: This is a list of tuples (or torch tensors) corresponding to the requested final size 296 | of each prediction. If left to None, it will default to the processed_sizes 297 | """ 298 | if target_sizes is None: 299 | target_sizes = processed_sizes 300 | assert len(processed_sizes) == len(target_sizes) 301 | out_logits, raw_masks, raw_boxes = outputs["pred_logits"], outputs["pred_masks"], outputs["pred_boxes"] 302 | assert len(out_logits) == len(raw_masks) == len(target_sizes) 303 | preds = [] 304 | 305 | def to_tuple(tup): 306 | if isinstance(tup, tuple): 307 | return tup 308 | return tuple(tup.cpu().tolist()) 309 | 310 | for cur_logits, cur_masks, cur_boxes, size, target_size in zip( 311 | out_logits, raw_masks, raw_boxes, processed_sizes, target_sizes 312 | ): 313 | # we filter empty queries and detection below threshold 314 | scores, labels = cur_logits.softmax(-1).max(-1) 315 | keep = labels.ne(outputs["pred_logits"].shape[-1] - 1) & (scores > self.threshold) 316 | cur_scores, cur_classes = cur_logits.softmax(-1).max(-1) 317 | cur_scores = cur_scores[keep] 318 | cur_classes = cur_classes[keep] 319 | cur_masks = cur_masks[keep] 320 | cur_masks = interpolate(cur_masks[:, None], to_tuple(size), mode="bilinear").squeeze(1) 321 | cur_boxes = box_ops.box_cxcywh_to_xyxy(cur_boxes[keep]) 322 | 323 | h, w = cur_masks.shape[-2:] 324 | assert len(cur_boxes) == len(cur_classes) 325 | 326 | # It may be that we have several predicted masks for the same stuff class. 327 | # In the following, we track the list of masks ids for each stuff class (they are merged later on) 328 | cur_masks = cur_masks.flatten(1) 329 | stuff_equiv_classes = defaultdict(lambda: []) 330 | for k, label in enumerate(cur_classes): 331 | if not self.is_thing_map[label.item()]: 332 | stuff_equiv_classes[label.item()].append(k) 333 | 334 | def get_ids_area(masks, scores, dedup=False): 335 | # This helper function creates the final panoptic segmentation image 336 | # It also returns the area of the masks that appears on the image 337 | 338 | m_id = masks.transpose(0, 1).softmax(-1) 339 | 340 | if m_id.shape[-1] == 0: 341 | # We didn't detect any mask :( 342 | m_id = torch.zeros((h, w), dtype=torch.long, device=m_id.device) 343 | else: 344 | m_id = m_id.argmax(-1).view(h, w) 345 | 346 | if dedup: 347 | # Merge the masks corresponding to the same stuff class 348 | for equiv in stuff_equiv_classes.values(): 349 | if len(equiv) > 1: 350 | for eq_id in equiv: 351 | m_id.masked_fill_(m_id.eq(eq_id), equiv[0]) 352 | 353 | final_h, final_w = to_tuple(target_size) 354 | 355 | seg_img = Image.fromarray(id2rgb(m_id.view(h, w).cpu().numpy())) 356 | seg_img = seg_img.resize(size=(final_w, final_h), resample=Image.NEAREST) 357 | 358 | np_seg_img = ( 359 | torch.ByteTensor(torch.ByteStorage.from_buffer(seg_img.tobytes())).view(final_h, final_w, 3).numpy() 360 | ) 361 | m_id = torch.from_numpy(rgb2id(np_seg_img)) 362 | 363 | area = [] 364 | for i in range(len(scores)): 365 | area.append(m_id.eq(i).sum().item()) 366 | return area, seg_img 367 | 368 | area, seg_img = get_ids_area(cur_masks, cur_scores, dedup=True) 369 | if cur_classes.numel() > 0: 370 | # We know filter empty masks as long as we find some 371 | while True: 372 | filtered_small = torch.as_tensor( 373 | [area[i] <= 4 for i, c in enumerate(cur_classes)], dtype=torch.bool, device=keep.device 374 | ) 375 | if filtered_small.any().item(): 376 | cur_scores = cur_scores[~filtered_small] 377 | cur_classes = cur_classes[~filtered_small] 378 | cur_masks = cur_masks[~filtered_small] 379 | area, seg_img = get_ids_area(cur_masks, cur_scores) 380 | else: 381 | break 382 | 383 | else: 384 | cur_classes = torch.ones(1, dtype=torch.long, device=cur_classes.device) 385 | 386 | segments_info = [] 387 | for i, a in enumerate(area): 388 | cat = cur_classes[i].item() 389 | segments_info.append({"id": i, "isthing": self.is_thing_map[cat], "category_id": cat, "area": a}) 390 | del cur_classes 391 | 392 | with io.BytesIO() as out: 393 | seg_img.save(out, format="PNG") 394 | predictions = {"png_string": out.getvalue(), "segments_info": segments_info} 395 | preds.append(predictions) 396 | return preds 397 | -------------------------------------------------------------------------------- /util/misc.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | Misc functions, including distributed helpers. 4 | 5 | Mostly copy-paste from torchvision references. 6 | """ 7 | import os 8 | import subprocess 9 | import time 10 | from collections import defaultdict, deque 11 | import datetime 12 | import pickle 13 | from packaging import version 14 | from typing import Optional, List 15 | 16 | import torch 17 | import torch.distributed as dist 18 | from torch import Tensor 19 | 20 | # needed due to empty tensor bug in pytorch and torchvision 0.5 21 | import torchvision 22 | 23 | if version.parse(torchvision.__version__) < version.parse('0.7'): 24 | from torchvision.ops import _new_empty_tensor 25 | from torchvision.ops.misc import _output_size 26 | 27 | 28 | class SmoothedValue(object): 29 | """Track a series of values and provide access to smoothed values over a 30 | window or the global series average. 31 | """ 32 | 33 | def __init__(self, window_size=20, fmt=None): 34 | if fmt is None: 35 | fmt = "{median:.4f} ({global_avg:.4f})" 36 | self.deque = deque(maxlen=window_size) 37 | self.total = 0.0 38 | self.count = 0 39 | self.fmt = fmt 40 | 41 | def update(self, value, n=1): 42 | self.deque.append(value) 43 | self.count += n 44 | self.total += value * n 45 | 46 | def synchronize_between_processes(self): 47 | """ 48 | Warning: does not synchronize the deque! 49 | """ 50 | if not is_dist_avail_and_initialized(): 51 | return 52 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') 53 | dist.barrier() 54 | dist.all_reduce(t) 55 | t = t.tolist() 56 | self.count = int(t[0]) 57 | self.total = t[1] 58 | 59 | @property 60 | def median(self): 61 | d = torch.tensor(list(self.deque)) 62 | return d.median().item() 63 | 64 | @property 65 | def avg(self): 66 | d = torch.tensor(list(self.deque), dtype=torch.float32) 67 | return d.mean().item() 68 | 69 | @property 70 | def global_avg(self): 71 | return self.total / self.count 72 | 73 | @property 74 | def max(self): 75 | return max(self.deque) 76 | 77 | @property 78 | def value(self): 79 | return self.deque[-1] 80 | 81 | def __str__(self): 82 | return self.fmt.format( 83 | median=self.median, 84 | avg=self.avg, 85 | global_avg=self.global_avg, 86 | max=self.max, 87 | value=self.value) 88 | 89 | 90 | def all_gather(data): 91 | """ 92 | Run all_gather on arbitrary picklable data (not necessarily tensors) 93 | Args: 94 | data: any picklable object 95 | Returns: 96 | list[data]: list of data gathered from each rank 97 | """ 98 | world_size = get_world_size() 99 | if world_size == 1: 100 | return [data] 101 | 102 | # serialized to a Tensor 103 | buffer = pickle.dumps(data) 104 | storage = torch.ByteStorage.from_buffer(buffer) 105 | tensor = torch.ByteTensor(storage).to("cuda") 106 | 107 | # obtain Tensor size of each rank 108 | local_size = torch.tensor([tensor.numel()], device="cuda") 109 | size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] 110 | dist.all_gather(size_list, local_size) 111 | size_list = [int(size.item()) for size in size_list] 112 | max_size = max(size_list) 113 | 114 | # receiving Tensor from all ranks 115 | # we pad the tensor because torch all_gather does not support 116 | # gathering tensors of different shapes 117 | tensor_list = [] 118 | for _ in size_list: 119 | tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) 120 | if local_size != max_size: 121 | padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") 122 | tensor = torch.cat((tensor, padding), dim=0) 123 | dist.all_gather(tensor_list, tensor) 124 | 125 | data_list = [] 126 | for size, tensor in zip(size_list, tensor_list): 127 | buffer = tensor.cpu().numpy().tobytes()[:size] 128 | data_list.append(pickle.loads(buffer)) 129 | 130 | return data_list 131 | 132 | 133 | def reduce_dict(input_dict, average=True): 134 | """ 135 | Args: 136 | input_dict (dict): all the values will be reduced 137 | average (bool): whether to do average or sum 138 | Reduce the values in the dictionary from all processes so that all processes 139 | have the averaged results. Returns a dict with the same fields as 140 | input_dict, after reduction. 141 | """ 142 | world_size = get_world_size() 143 | if world_size < 2: 144 | return input_dict 145 | with torch.no_grad(): 146 | names = [] 147 | values = [] 148 | # sort the keys so that they are consistent across processes 149 | for k in sorted(input_dict.keys()): 150 | names.append(k) 151 | values.append(input_dict[k]) 152 | values = torch.stack(values, dim=0) 153 | dist.all_reduce(values) 154 | if average: 155 | values /= world_size 156 | reduced_dict = {k: v for k, v in zip(names, values)} 157 | return reduced_dict 158 | 159 | 160 | class MetricLogger(object): 161 | def __init__(self, delimiter="\t"): 162 | self.meters = defaultdict(SmoothedValue) 163 | self.delimiter = delimiter 164 | 165 | def update(self, **kwargs): 166 | for k, v in kwargs.items(): 167 | if isinstance(v, torch.Tensor): 168 | v = v.item() 169 | assert isinstance(v, (float, int)) 170 | self.meters[k].update(v) 171 | 172 | def __getattr__(self, attr): 173 | if attr in self.meters: 174 | return self.meters[attr] 175 | if attr in self.__dict__: 176 | return self.__dict__[attr] 177 | raise AttributeError("'{}' object has no attribute '{}'".format( 178 | type(self).__name__, attr)) 179 | 180 | def __str__(self): 181 | loss_str = [] 182 | for name, meter in self.meters.items(): 183 | loss_str.append( 184 | "{}: {}".format(name, str(meter)) 185 | ) 186 | return self.delimiter.join(loss_str) 187 | 188 | def synchronize_between_processes(self): 189 | for meter in self.meters.values(): 190 | meter.synchronize_between_processes() 191 | 192 | def add_meter(self, name, meter): 193 | self.meters[name] = meter 194 | 195 | def log_every(self, iterable, print_freq, header=None): 196 | i = 0 197 | if not header: 198 | header = '' 199 | start_time = time.time() 200 | end = time.time() 201 | iter_time = SmoothedValue(fmt='{avg:.4f}') 202 | data_time = SmoothedValue(fmt='{avg:.4f}') 203 | space_fmt = ':' + str(len(str(len(iterable)))) + 'd' 204 | if torch.cuda.is_available(): 205 | log_msg = self.delimiter.join([ 206 | header, 207 | '[{0' + space_fmt + '}/{1}]', 208 | 'eta: {eta}', 209 | '{meters}', 210 | 'time: {time}', 211 | 'data: {data}', 212 | 'max mem: {memory:.0f}' 213 | ]) 214 | else: 215 | log_msg = self.delimiter.join([ 216 | header, 217 | '[{0' + space_fmt + '}/{1}]', 218 | 'eta: {eta}', 219 | '{meters}', 220 | 'time: {time}', 221 | 'data: {data}' 222 | ]) 223 | MB = 1024.0 * 1024.0 224 | for obj in iterable: 225 | data_time.update(time.time() - end) 226 | yield obj 227 | iter_time.update(time.time() - end) 228 | if i % print_freq == 0 or i == len(iterable) - 1: 229 | eta_seconds = iter_time.global_avg * (len(iterable) - i) 230 | eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) 231 | if torch.cuda.is_available(): 232 | print(log_msg.format( 233 | i, len(iterable), eta=eta_string, 234 | meters=str(self), 235 | time=str(iter_time), data=str(data_time), 236 | memory=torch.cuda.max_memory_allocated() / MB)) 237 | else: 238 | print(log_msg.format( 239 | i, len(iterable), eta=eta_string, 240 | meters=str(self), 241 | time=str(iter_time), data=str(data_time))) 242 | i += 1 243 | end = time.time() 244 | total_time = time.time() - start_time 245 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 246 | print('{} Total time: {} ({:.4f} s / it)'.format( 247 | header, total_time_str, total_time / len(iterable))) 248 | 249 | 250 | def get_sha(): 251 | cwd = os.path.dirname(os.path.abspath(__file__)) 252 | 253 | def _run(command): 254 | return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() 255 | 256 | sha = 'N/A' 257 | diff = "clean" 258 | branch = 'N/A' 259 | try: 260 | sha = _run(['git', 'rev-parse', 'HEAD']) 261 | subprocess.check_output(['git', 'diff'], cwd=cwd) 262 | diff = _run(['git', 'diff-index', 'HEAD']) 263 | diff = "has uncommited changes" if diff else "clean" 264 | branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) 265 | except Exception: 266 | pass 267 | message = f"sha: {sha}, status: {diff}, branch: {branch}" 268 | return message 269 | 270 | 271 | def collate_fn(batch): 272 | batch = list(zip(*batch)) 273 | batch[0] = nested_tensor_from_tensor_list(batch[0]) 274 | return tuple(batch) 275 | 276 | 277 | def _max_by_axis(the_list): 278 | # type: (List[List[int]]) -> List[int] 279 | maxes = the_list[0] 280 | for sublist in the_list[1:]: 281 | for index, item in enumerate(sublist): 282 | maxes[index] = max(maxes[index], item) 283 | return maxes 284 | 285 | 286 | class NestedTensor(object): 287 | def __init__(self, tensors, mask: Optional[Tensor]): 288 | self.tensors = tensors 289 | self.mask = mask 290 | 291 | def to(self, device): 292 | # type: (Device) -> NestedTensor # noqa 293 | cast_tensor = self.tensors.to(device) 294 | mask = self.mask 295 | if mask is not None: 296 | assert mask is not None 297 | cast_mask = mask.to(device) 298 | else: 299 | cast_mask = None 300 | return NestedTensor(cast_tensor, cast_mask) 301 | 302 | def decompose(self): 303 | return self.tensors, self.mask 304 | 305 | def __repr__(self): 306 | return str(self.tensors) 307 | 308 | 309 | def nested_tensor_from_tensor_list(tensor_list: List[Tensor]): 310 | # TODO make this more general 311 | if tensor_list[0].ndim == 3: 312 | if torchvision._is_tracing(): 313 | # nested_tensor_from_tensor_list() does not export well to ONNX 314 | # call _onnx_nested_tensor_from_tensor_list() instead 315 | return _onnx_nested_tensor_from_tensor_list(tensor_list) 316 | 317 | # TODO make it support different-sized images 318 | max_size = _max_by_axis([list(img.shape) for img in tensor_list]) 319 | # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list])) 320 | batch_shape = [len(tensor_list)] + max_size 321 | b, c, h, w = batch_shape 322 | dtype = tensor_list[0].dtype 323 | device = tensor_list[0].device 324 | tensor = torch.zeros(batch_shape, dtype=dtype, device=device) 325 | mask = torch.ones((b, h, w), dtype=torch.bool, device=device) 326 | for img, pad_img, m in zip(tensor_list, tensor, mask): 327 | pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) 328 | m[: img.shape[1], :img.shape[2]] = False 329 | else: 330 | raise ValueError('not supported') 331 | return NestedTensor(tensor, mask) 332 | 333 | 334 | # _onnx_nested_tensor_from_tensor_list() is an implementation of 335 | # nested_tensor_from_tensor_list() that is supported by ONNX tracing. 336 | @torch.jit.unused 337 | def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor: 338 | max_size = [] 339 | for i in range(tensor_list[0].dim()): 340 | max_size_i = torch.max(torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)).to(torch.int64) 341 | max_size.append(max_size_i) 342 | max_size = tuple(max_size) 343 | 344 | # work around for 345 | # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) 346 | # m[: img.shape[1], :img.shape[2]] = False 347 | # which is not yet supported in onnx 348 | padded_imgs = [] 349 | padded_masks = [] 350 | for img in tensor_list: 351 | padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))] 352 | padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0])) 353 | padded_imgs.append(padded_img) 354 | 355 | m = torch.zeros_like(img[0], dtype=torch.int, device=img.device) 356 | padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1) 357 | padded_masks.append(padded_mask.to(torch.bool)) 358 | 359 | tensor = torch.stack(padded_imgs) 360 | mask = torch.stack(padded_masks) 361 | 362 | return NestedTensor(tensor, mask=mask) 363 | 364 | 365 | def setup_for_distributed(is_master): 366 | """ 367 | This function disables printing when not in master process 368 | """ 369 | import builtins as __builtin__ 370 | builtin_print = __builtin__.print 371 | 372 | def print(*args, **kwargs): 373 | force = kwargs.pop('force', False) 374 | if is_master or force: 375 | builtin_print(*args, **kwargs) 376 | 377 | __builtin__.print = print 378 | 379 | 380 | # 是不是多卡运行 381 | def is_dist_avail_and_initialized(): 382 | if not dist.is_available(): 383 | return False 384 | if not dist.is_initialized(): 385 | return False 386 | return True 387 | 388 | 389 | def get_world_size(): 390 | if not is_dist_avail_and_initialized(): 391 | return 1 392 | return dist.get_world_size() 393 | 394 | 395 | def get_rank(): 396 | if not is_dist_avail_and_initialized(): 397 | return 0 398 | return dist.get_rank() 399 | 400 | 401 | def is_main_process(): 402 | return get_rank() == 0 403 | 404 | 405 | def save_on_master(*args, **kwargs): 406 | # 保存模型,只有主进程保存即可 407 | if is_main_process(): 408 | torch.save(*args, **kwargs) 409 | 410 | 411 | def init_distributed_mode(args): 412 | if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: 413 | args.rank = int(os.environ["RANK"]) 414 | args.world_size = int(os.environ['WORLD_SIZE']) 415 | args.gpu = int(os.environ['LOCAL_RANK']) 416 | elif 'SLURM_PROCID' in os.environ: 417 | args.rank = int(os.environ['SLURM_PROCID']) 418 | args.gpu = args.rank % torch.cuda.device_count() 419 | else: 420 | print('Not using distributed mode') 421 | args.distributed = False 422 | return 423 | 424 | args.distributed = True 425 | 426 | torch.cuda.set_device(args.gpu) 427 | args.dist_backend = 'nccl' 428 | print('| distributed init (rank {}): {}'.format( 429 | args.rank, args.dist_url), flush=True) 430 | torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 431 | world_size=args.world_size, rank=args.rank) 432 | torch.distributed.barrier() 433 | setup_for_distributed(args.rank == 0) 434 | 435 | 436 | @torch.no_grad() 437 | def accuracy(output, target, topk=(1,)): 438 | """Computes the precision@k for the specified values of k""" 439 | if target.numel() == 0: 440 | return [torch.zeros([], device=output.device)] 441 | maxk = max(topk) 442 | batch_size = target.size(0) 443 | 444 | _, pred = output.topk(maxk, 1, True, True) 445 | pred = pred.t() 446 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 447 | 448 | res = [] 449 | for k in topk: 450 | correct_k = correct[:k].view(-1).float().sum(0) 451 | res.append(correct_k.mul_(100.0 / batch_size)) 452 | return res 453 | 454 | 455 | def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): 456 | # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor 457 | """ 458 | Equivalent to nn.functional.interpolate, but with support for empty batch sizes. 459 | This will eventually be supported natively by PyTorch, and this 460 | class can go away. 461 | """ 462 | if version.parse(torchvision.__version__) < version.parse('0.7'): 463 | if input.numel() > 0: 464 | return torch.nn.functional.interpolate( 465 | input, size, scale_factor, mode, align_corners 466 | ) 467 | 468 | output_shape = _output_size(2, input, size, scale_factor) 469 | output_shape = list(input.shape[:-2]) + list(output_shape) 470 | return _new_empty_tensor(input, output_shape) 471 | else: 472 | return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners) 473 | -------------------------------------------------------------------------------- /models/transformer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | """ 3 | DETR Transformer class. 4 | 5 | Copy-paste from torch.nn.Transformer with modifications: 6 | * positional encodings are passed in MHattention 7 | * extra LN at the end of encoder is removed 8 | * decoder returns a stack of activations from all decoding layers 9 | """ 10 | import copy 11 | from typing import Optional, List 12 | 13 | import torch 14 | import torch.nn.functional as F 15 | from torch import nn, Tensor 16 | 17 | 18 | class Transformer(nn.Module): 19 | 20 | def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, 21 | num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, 22 | activation="relu", normalize_before=False, 23 | return_intermediate_dec=False): 24 | super().__init__() 25 | # encoder和decoder的参数基本是相同的 26 | 27 | # encoder 28 | encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, 29 | dropout, activation, normalize_before) 30 | 31 | encoder_norm = nn.LayerNorm(d_model) if normalize_before else None 32 | 33 | self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm) 34 | 35 | # decoder 36 | decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, 37 | dropout, activation, normalize_before) 38 | 39 | decoder_norm = nn.LayerNorm(d_model) 40 | 41 | # return_intermediate 就是把前5层的值也返回 42 | self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm, 43 | return_intermediate=return_intermediate_dec) 44 | 45 | self._reset_parameters() 46 | 47 | self.d_model = d_model 48 | 49 | self.nhead = nhead 50 | 51 | def _reset_parameters(self): 52 | for p in self.parameters(): 53 | if p.dim() > 1: 54 | nn.init.xavier_uniform_(p) 55 | 56 | def forward(self, src, mask, query_embed, pos_embed): 57 | """ 58 | scr: (bs 256 H W) 59 | mask: (bs H W) 60 | query_embed: (100,256) 61 | pos_embed: (bs 256 H W) 62 | """ 63 | 64 | # flatten NxCxHxW to HWxNxC 65 | bs, c, h, w = src.shape 66 | # HW 推平 -> HW,bs,256 67 | src = src.flatten(2).permute(2, 0, 1) 68 | # 变成与上面的维度相同 69 | pos_embed = pos_embed.flatten(2).permute(2, 0, 1) 70 | 71 | # 传进来的是query_embed.weight 72 | # query_embed 是给decoder使用的 73 | # 100, 256 中间加个维度,并将这个维度重复 bs 次 -> 100,bs,256 74 | # [100,256] --unsqueeze(1)--> [100,1,256] --repeat--> [100,bs,256] 75 | query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1) 76 | # hw 推平 77 | mask = mask.flatten(1) 78 | 79 | # [100,bs,256] 80 | tgt = torch.zeros_like(query_embed) 81 | 82 | # feature和位置编码 进入encoder网络 输出 memory: HW,bs,256 83 | memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed) 84 | # tgt, encoder的输出,位置编码,以及query输入到decoder 85 | # hs [6(decoder layer number),100,bs,256] 86 | hs = self.decoder(tgt, memory, memory_key_padding_mask=mask, 87 | pos=pos_embed, query_pos=query_embed) 88 | 89 | # memory 变换成 bs,c,h,w的形式 90 | # memory 是encoder的输出 91 | # hs 是decoder的输出 92 | # hs [6,100,bs,256] --transpose--> [6,bs,100,256] 93 | # memory [hw,bs,256] --permute--> [bs,256,hw] --view--> [bs,256,h,w] 94 | return hs.transpose(1, 2), memory.permute(1, 2, 0).view(bs, c, h, w) 95 | 96 | 97 | # ---------------------------------------------------------------------------------------------------------------------- 98 | 99 | class TransformerEncoder(nn.Module): 100 | 101 | def __init__(self, encoder_layer, num_layers, norm=None): 102 | super().__init__() 103 | # 复制几层 104 | self.layers = _get_clones(encoder_layer, num_layers) 105 | self.num_layers = num_layers 106 | self.norm = norm 107 | 108 | def forward(self, src, 109 | mask: Optional[Tensor] = None, 110 | src_key_padding_mask: Optional[Tensor] = None, 111 | pos: Optional[Tensor] = None): 112 | output = src 113 | 114 | # 6层 115 | for layer in self.layers: 116 | output = layer(output, src_mask=mask, 117 | src_key_padding_mask=src_key_padding_mask, pos=pos) 118 | # 最后经过norm 119 | if self.norm is not None: 120 | output = self.norm(output) 121 | 122 | return output 123 | 124 | 125 | # encoder 126 | class TransformerEncoderLayer(nn.Module): 127 | 128 | def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, 129 | activation="relu", normalize_before=False): 130 | """ 131 | d_model: 512 是encoder中的宽度 132 | 2048 FNN的宽度 133 | """ 134 | super().__init__() 135 | # 修改一下顺序,在print的时候会好看些 136 | 137 | # torch内置,直接使用 138 | self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) 139 | 140 | self.dropout1 = nn.Dropout(dropout) 141 | 142 | self.norm1 = nn.LayerNorm(d_model) 143 | 144 | # Implementation of Feedforward model 145 | self.linear1 = nn.Linear(d_model, dim_feedforward) 146 | self.dropout = nn.Dropout(dropout) 147 | self.linear2 = nn.Linear(dim_feedforward, d_model) 148 | 149 | self.dropout2 = nn.Dropout(dropout) 150 | 151 | self.norm2 = nn.LayerNorm(d_model) 152 | 153 | # self.norm1 = nn.LayerNorm(d_model) 154 | # self.norm2 = nn.LayerNorm(d_model) 155 | # self.dropout1 = nn.Dropout(dropout) 156 | # self.dropout2 = nn.Dropout(dropout) 157 | 158 | self.activation = _get_activation_fn(activation) 159 | self.normalize_before = normalize_before 160 | 161 | def with_pos_embed(self, tensor, pos: Optional[Tensor]): 162 | return tensor if pos is None else tensor + pos 163 | 164 | def forward_post(self, 165 | src, 166 | src_mask: Optional[Tensor] = None, 167 | src_key_padding_mask: Optional[Tensor] = None, 168 | pos: Optional[Tensor] = None): 169 | """ 170 | norm在attention和mlp之后 171 | src: (hw,3,256) 172 | """ 173 | # q k 融合位置编码,value不使用位置编码 174 | q = k = self.with_pos_embed(src, pos) 175 | src2 = self.self_attn(q, k, value=src, attn_mask=src_mask, 176 | key_padding_mask=src_key_padding_mask)[0] 177 | src = src + self.dropout1(src2) 178 | src = self.norm1(src) 179 | # FFN 180 | src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) 181 | # 残差的就直接加进去了 182 | src = src + self.dropout2(src2) 183 | src = self.norm2(src) 184 | return src 185 | 186 | def forward_pre(self, src, 187 | src_mask: Optional[Tensor] = None, 188 | src_key_padding_mask: Optional[Tensor] = None, 189 | pos: Optional[Tensor] = None): 190 | """ 191 | norm在attention和mlp之前 192 | """ 193 | src2 = self.norm1(src) 194 | q = k = self.with_pos_embed(src2, pos) 195 | src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask, 196 | key_padding_mask=src_key_padding_mask)[0] 197 | src = src + self.dropout1(src2) 198 | src2 = self.norm2(src) 199 | src2 = self.linear2(self.dropout(self.activation(self.linear1(src2)))) 200 | src = src + self.dropout2(src2) 201 | return src 202 | 203 | def forward(self, src, 204 | src_mask: Optional[Tensor] = None, 205 | src_key_padding_mask: Optional[Tensor] = None, 206 | pos: Optional[Tensor] = None): 207 | if self.normalize_before: 208 | return self.forward_pre(src, src_mask, src_key_padding_mask, pos) 209 | return self.forward_post(src, src_mask, src_key_padding_mask, pos) 210 | 211 | 212 | # ---------------------------------------------------------------------------------------------------------------------- 213 | 214 | class TransformerDecoder(nn.Module): 215 | 216 | def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): 217 | super().__init__() 218 | # 复制几层 219 | self.layers = _get_clones(decoder_layer, num_layers) 220 | self.num_layers = num_layers 221 | self.norm = norm 222 | self.return_intermediate = return_intermediate 223 | 224 | def forward(self, 225 | # tgt = torch.zeros_like(query_embed) 226 | # 初始时是全是0,与query_embed大小相同 227 | tgt, 228 | # memory 是 encoder的输出 229 | memory, 230 | # 分割任务使用的 231 | tgt_mask: Optional[Tensor] = None, 232 | # 分割任务使用的 233 | memory_mask: Optional[Tensor] = None, 234 | # 分割任务使用的 235 | tgt_key_padding_mask: Optional[Tensor] = None, 236 | # 检测任务会提供这个 237 | memory_key_padding_mask: Optional[Tensor] = None, 238 | pos: Optional[Tensor] = None, 239 | query_pos: Optional[Tensor] = None): 240 | 241 | """ 242 | tgt: [100,bs,256] 243 | memory: [hw,bs,256] 244 | pos: [hw,bs,256] 245 | query_pos: [100,bs,256[ 246 | """ 247 | 248 | # 对于第一层的decoder, 它的输入object query是[100,bs,256]的zero tensor 249 | # 但是对于第二层及以后的decoder,他的输入上是上一次的decoder的输出结果 250 | # 但是不管第几层的decoder,它们使用的memory(encoder结构的输出) 是相同的,都是最后一层encoder的输出 251 | output = tgt 252 | # 保留中间层的输出 253 | intermediate = [] 254 | 255 | for layer in self.layers: 256 | # [100,bs,256] 257 | output = layer(output, memory, tgt_mask=tgt_mask, 258 | memory_mask=memory_mask, 259 | tgt_key_padding_mask=tgt_key_padding_mask, 260 | memory_key_padding_mask=memory_key_padding_mask, 261 | pos=pos, query_pos=query_pos) 262 | # 每一个中间层计算的结果需要返回 263 | if self.return_intermediate: 264 | intermediate.append(self.norm(output)) 265 | 266 | # 最后经过norm 267 | if self.norm is not None: 268 | output = self.norm(output) 269 | if self.return_intermediate: 270 | # 弹出最后一个,加上上面经过norm的 271 | intermediate.pop() 272 | intermediate.append(output) 273 | 274 | if self.return_intermediate: 275 | return torch.stack(intermediate) 276 | 277 | return output.unsqueeze(0) 278 | 279 | 280 | class TransformerDecoderLayer(nn.Module): 281 | 282 | def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, 283 | activation="relu", normalize_before=False): 284 | # decoder encoder的初始化参数相同 285 | super().__init__() 286 | 287 | # 调整了顺序 288 | 289 | # 这是论文中decoder中下面那个 290 | self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) 291 | 292 | self.dropout1 = nn.Dropout(dropout) 293 | self.norm1 = nn.LayerNorm(d_model) 294 | 295 | # 这是论文中decoder中上面那个 296 | self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) 297 | self.dropout2 = nn.Dropout(dropout) 298 | self.norm2 = nn.LayerNorm(d_model) 299 | 300 | # Implementation of Feedforward model 301 | self.linear1 = nn.Linear(d_model, dim_feedforward) 302 | self.dropout = nn.Dropout(dropout) 303 | self.linear2 = nn.Linear(dim_feedforward, d_model) 304 | 305 | self.dropout3 = nn.Dropout(dropout) 306 | self.norm3 = nn.LayerNorm(d_model) 307 | 308 | self.activation = _get_activation_fn(activation) 309 | self.normalize_before = normalize_before 310 | 311 | def with_pos_embed(self, tensor, pos: Optional[Tensor]): 312 | # 就是两个tensor相加 313 | return tensor if pos is None else tensor + pos 314 | 315 | # norm在操作后 316 | def forward_post(self, 317 | # 第一层的tgt是 tgt = torch.zeros_like(query_embed) 318 | tgt, 319 | # encoder的输出 320 | memory, 321 | # 检测任务没有 322 | tgt_mask: Optional[Tensor] = None, 323 | # 检测任务没有 324 | memory_mask: Optional[Tensor] = None, 325 | # 检测任务没有 326 | tgt_key_padding_mask: Optional[Tensor] = None, 327 | # 检测任务只有这个 328 | memory_key_padding_mask: Optional[Tensor] = None, 329 | # 位置嵌入 330 | pos: Optional[Tensor] = None, 331 | # 100的那个query, 就是query_embed 332 | query_pos: Optional[Tensor] = None): 333 | """ 334 | tgt: [100,bs,256] 335 | memory: [hw,bs,256] 336 | pos: [hw,bs,256] 337 | query_pos: [100,bs,256] 338 | """ 339 | 340 | # 这两个attention跟论文上的图中画的路线是一样的 341 | # query_pos 就是 query_embed 342 | q = k = self.with_pos_embed(tgt, query_pos) 343 | tgt2 = self.self_attn(q, 344 | k, 345 | value=tgt, 346 | attn_mask=tgt_mask, 347 | key_padding_mask=tgt_key_padding_mask)[0] 348 | # 第一个dropout 349 | tgt = tgt + self.dropout1(tgt2) 350 | tgt = self.norm1(tgt) 351 | 352 | # 各项值的组合方式与论文中的图像是一致的 353 | tgt2 = self.multihead_attn( 354 | # 第二个attention的query是第一个attention的输出 355 | query=self.with_pos_embed(tgt, query_pos), 356 | # 两个参数,跟上面的都不同 357 | # 使用了encoder的输出memory,以及位置编码 358 | key=self.with_pos_embed(memory, pos), 359 | # 上面是tgt,这个是memory 360 | # encoder的输出memory是decoder中第二个attention的value 361 | value=memory, 362 | attn_mask=memory_mask, 363 | key_padding_mask=memory_key_padding_mask)[0] 364 | 365 | # 第二个dropout 366 | # 这里的tgt是第一个attention的输出 加上 第二个attention的输出 367 | tgt = tgt + self.dropout2(tgt2) 368 | tgt = self.norm2(tgt) 369 | # FFN 370 | tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) 371 | # 第三个dropout 372 | tgt = tgt + self.dropout3(tgt2) 373 | tgt = self.norm3(tgt) 374 | return tgt 375 | 376 | # norm在操作前 377 | def forward_pre(self, tgt, memory, 378 | tgt_mask: Optional[Tensor] = None, 379 | memory_mask: Optional[Tensor] = None, 380 | tgt_key_padding_mask: Optional[Tensor] = None, 381 | memory_key_padding_mask: Optional[Tensor] = None, 382 | pos: Optional[Tensor] = None, 383 | query_pos: Optional[Tensor] = None): 384 | tgt2 = self.norm1(tgt) 385 | q = k = self.with_pos_embed(tgt2, query_pos) 386 | tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, 387 | key_padding_mask=tgt_key_padding_mask)[0] 388 | tgt = tgt + self.dropout1(tgt2) 389 | tgt2 = self.norm2(tgt) 390 | tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos), 391 | key=self.with_pos_embed(memory, pos), 392 | value=memory, attn_mask=memory_mask, 393 | key_padding_mask=memory_key_padding_mask)[0] 394 | tgt = tgt + self.dropout2(tgt2) 395 | tgt2 = self.norm3(tgt) 396 | tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) 397 | tgt = tgt + self.dropout3(tgt2) 398 | return tgt 399 | 400 | def forward(self, tgt, memory, 401 | tgt_mask: Optional[Tensor] = None, 402 | memory_mask: Optional[Tensor] = None, 403 | tgt_key_padding_mask: Optional[Tensor] = None, 404 | memory_key_padding_mask: Optional[Tensor] = None, 405 | pos: Optional[Tensor] = None, 406 | query_pos: Optional[Tensor] = None): 407 | if self.normalize_before: 408 | # norm在sa之前 409 | return self.forward_pre(tgt, memory, tgt_mask, memory_mask, 410 | tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) 411 | # norm在sa之后 412 | return self.forward_post(tgt, memory, tgt_mask, memory_mask, 413 | tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) 414 | 415 | 416 | # ---------------------------------------------------------------------------------------------------------------------- 417 | 418 | def _get_clones(module, N): 419 | # encoder,decoder内部的那几层结构都是相同的 420 | return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) 421 | 422 | 423 | def build_transformer(args): 424 | return Transformer( 425 | d_model=args.hidden_dim, 426 | dropout=args.dropout, 427 | nhead=args.nheads, 428 | dim_feedforward=args.dim_feedforward, 429 | num_encoder_layers=args.enc_layers, 430 | num_decoder_layers=args.dec_layers, 431 | normalize_before=args.pre_norm, 432 | # 返回decoder的中间层结果 433 | return_intermediate_dec=True, 434 | ) 435 | 436 | 437 | def _get_activation_fn(activation): 438 | # 三种激活函数 439 | """Return an activation function given a string""" 440 | if activation == "relu": 441 | return F.relu 442 | if activation == "gelu": 443 | return F.gelu 444 | if activation == "glu": 445 | return F.glu 446 | raise RuntimeError(F"activation should be relu/gelu, not {activation}.") 447 | --------------------------------------------------------------------------------