ZTWHHH commited on
Commit
4a7d033
·
verified ·
1 Parent(s): 4da50b5

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/__init__.cpython-310.pyc +0 -0
  2. minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/_internally_replaced_utils.cpython-310.pyc +0 -0
  3. minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/_meta_registrations.cpython-310.pyc +0 -0
  4. minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/_utils.cpython-310.pyc +0 -0
  5. minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/extension.cpython-310.pyc +0 -0
  6. minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/utils.cpython-310.pyc +0 -0
  7. minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/version.cpython-310.pyc +0 -0
  8. minigpt2/lib/python3.10/site-packages/torchvision/datasets/celeba.py +194 -0
  9. minigpt2/lib/python3.10/site-packages/torchvision/datasets/folder.py +337 -0
  10. minigpt2/lib/python3.10/site-packages/torchvision/datasets/food101.py +93 -0
  11. minigpt2/lib/python3.10/site-packages/torchvision/datasets/lfw.py +256 -0
  12. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/__init__.cpython-310.pyc +0 -0
  13. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/_api.cpython-310.pyc +0 -0
  14. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/_meta.cpython-310.pyc +0 -0
  15. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/_utils.cpython-310.pyc +0 -0
  16. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/convnext.cpython-310.pyc +0 -0
  17. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/densenet.cpython-310.pyc +0 -0
  18. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/efficientnet.cpython-310.pyc +0 -0
  19. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/inception.cpython-310.pyc +0 -0
  20. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/mobilenet.cpython-310.pyc +0 -0
  21. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/mobilenetv2.cpython-310.pyc +0 -0
  22. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/regnet.cpython-310.pyc +0 -0
  23. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/squeezenet.cpython-310.pyc +0 -0
  24. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/swin_transformer.cpython-310.pyc +0 -0
  25. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/vgg.cpython-310.pyc +0 -0
  26. minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/vision_transformer.cpython-310.pyc +0 -0
  27. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__init__.py +7 -0
  28. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/__init__.cpython-310.pyc +0 -0
  29. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/_utils.cpython-310.pyc +0 -0
  30. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/anchor_utils.cpython-310.pyc +0 -0
  31. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/backbone_utils.cpython-310.pyc +0 -0
  32. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/faster_rcnn.cpython-310.pyc +0 -0
  33. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/fcos.cpython-310.pyc +0 -0
  34. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/generalized_rcnn.cpython-310.pyc +0 -0
  35. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/image_list.cpython-310.pyc +0 -0
  36. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/keypoint_rcnn.cpython-310.pyc +0 -0
  37. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/mask_rcnn.cpython-310.pyc +0 -0
  38. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/retinanet.cpython-310.pyc +0 -0
  39. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/roi_heads.cpython-310.pyc +0 -0
  40. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/rpn.cpython-310.pyc +0 -0
  41. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/ssd.cpython-310.pyc +0 -0
  42. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/ssdlite.cpython-310.pyc +0 -0
  43. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/transform.cpython-310.pyc +0 -0
  44. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/_utils.py +540 -0
  45. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/anchor_utils.py +268 -0
  46. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/backbone_utils.py +244 -0
  47. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/faster_rcnn.py +846 -0
  48. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/fcos.py +775 -0
  49. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/generalized_rcnn.py +118 -0
  50. minigpt2/lib/python3.10/site-packages/torchvision/models/detection/image_list.py +25 -0
minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.48 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/_internally_replaced_utils.cpython-310.pyc ADDED
Binary file (1.51 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/_meta_registrations.cpython-310.pyc ADDED
Binary file (6.79 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/extension.cpython-310.pyc ADDED
Binary file (2.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/utils.cpython-310.pyc ADDED
Binary file (22.1 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/__pycache__/version.cpython-310.pyc ADDED
Binary file (355 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/datasets/celeba.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import os
3
+ from collections import namedtuple
4
+ from pathlib import Path
5
+ from typing import Any, Callable, List, Optional, Tuple, Union
6
+
7
+ import PIL
8
+ import torch
9
+
10
+ from .utils import check_integrity, download_file_from_google_drive, extract_archive, verify_str_arg
11
+ from .vision import VisionDataset
12
+
13
+ CSV = namedtuple("CSV", ["header", "index", "data"])
14
+
15
+
16
+ class CelebA(VisionDataset):
17
+ """`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset.
18
+
19
+ Args:
20
+ root (str or ``pathlib.Path``): Root directory where images are downloaded to.
21
+ split (string): One of {'train', 'valid', 'test', 'all'}.
22
+ Accordingly dataset is selected.
23
+ target_type (string or list, optional): Type of target to use, ``attr``, ``identity``, ``bbox``,
24
+ or ``landmarks``. Can also be a list to output a tuple with all specified target types.
25
+ The targets represent:
26
+
27
+ - ``attr`` (Tensor shape=(40,) dtype=int): binary (0, 1) labels for attributes
28
+ - ``identity`` (int): label for each person (data points with the same identity are the same person)
29
+ - ``bbox`` (Tensor shape=(4,) dtype=int): bounding box (x, y, width, height)
30
+ - ``landmarks`` (Tensor shape=(10,) dtype=int): landmark points (lefteye_x, lefteye_y, righteye_x,
31
+ righteye_y, nose_x, nose_y, leftmouth_x, leftmouth_y, rightmouth_x, rightmouth_y)
32
+
33
+ Defaults to ``attr``. If empty, ``None`` will be returned as target.
34
+
35
+ transform (callable, optional): A function/transform that takes in a PIL image
36
+ and returns a transformed version. E.g, ``transforms.PILToTensor``
37
+ target_transform (callable, optional): A function/transform that takes in the
38
+ target and transforms it.
39
+ download (bool, optional): If true, downloads the dataset from the internet and
40
+ puts it in root directory. If dataset is already downloaded, it is not
41
+ downloaded again.
42
+
43
+ .. warning::
44
+
45
+ To download the dataset `gdown <https://github.com/wkentaro/gdown>`_ is required.
46
+ """
47
+
48
+ base_folder = "celeba"
49
+ # There currently does not appear to be an easy way to extract 7z in python (without introducing additional
50
+ # dependencies). The "in-the-wild" (not aligned+cropped) images are only in 7z, so they are not available
51
+ # right now.
52
+ file_list = [
53
+ # File ID MD5 Hash Filename
54
+ ("0B7EVK8r0v71pZjFTYXZWM3FlRnM", "00d2c5bc6d35e252742224ab0c1e8fcb", "img_align_celeba.zip"),
55
+ # ("0B7EVK8r0v71pbWNEUjJKdDQ3dGc","b6cd7e93bc7a96c2dc33f819aa3ac651", "img_align_celeba_png.7z"),
56
+ # ("0B7EVK8r0v71peklHb0pGdDl6R28", "b6cd7e93bc7a96c2dc33f819aa3ac651", "img_celeba.7z"),
57
+ ("0B7EVK8r0v71pblRyaVFSWGxPY0U", "75e246fa4810816ffd6ee81facbd244c", "list_attr_celeba.txt"),
58
+ ("1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS", "32bd1bd63d3c78cd57e08160ec5ed1e2", "identity_CelebA.txt"),
59
+ ("0B7EVK8r0v71pbThiMVRxWXZ4dU0", "00566efa6fedff7a56946cd1c10f1c16", "list_bbox_celeba.txt"),
60
+ ("0B7EVK8r0v71pd0FJY3Blby1HUTQ", "cc24ecafdb5b50baae59b03474781f8c", "list_landmarks_align_celeba.txt"),
61
+ # ("0B7EVK8r0v71pTzJIdlJWdHczRlU", "063ee6ddb681f96bc9ca28c6febb9d1a", "list_landmarks_celeba.txt"),
62
+ ("0B7EVK8r0v71pY0NSMzRuSXJEVkk", "d32c9cbf5e040fd4025c592c306e6668", "list_eval_partition.txt"),
63
+ ]
64
+
65
+ def __init__(
66
+ self,
67
+ root: Union[str, Path],
68
+ split: str = "train",
69
+ target_type: Union[List[str], str] = "attr",
70
+ transform: Optional[Callable] = None,
71
+ target_transform: Optional[Callable] = None,
72
+ download: bool = False,
73
+ ) -> None:
74
+ super().__init__(root, transform=transform, target_transform=target_transform)
75
+ self.split = split
76
+ if isinstance(target_type, list):
77
+ self.target_type = target_type
78
+ else:
79
+ self.target_type = [target_type]
80
+
81
+ if not self.target_type and self.target_transform is not None:
82
+ raise RuntimeError("target_transform is specified but target_type is empty")
83
+
84
+ if download:
85
+ self.download()
86
+
87
+ if not self._check_integrity():
88
+ raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
89
+
90
+ split_map = {
91
+ "train": 0,
92
+ "valid": 1,
93
+ "test": 2,
94
+ "all": None,
95
+ }
96
+ split_ = split_map[verify_str_arg(split.lower(), "split", ("train", "valid", "test", "all"))]
97
+ splits = self._load_csv("list_eval_partition.txt")
98
+ identity = self._load_csv("identity_CelebA.txt")
99
+ bbox = self._load_csv("list_bbox_celeba.txt", header=1)
100
+ landmarks_align = self._load_csv("list_landmarks_align_celeba.txt", header=1)
101
+ attr = self._load_csv("list_attr_celeba.txt", header=1)
102
+
103
+ mask = slice(None) if split_ is None else (splits.data == split_).squeeze()
104
+
105
+ if mask == slice(None): # if split == "all"
106
+ self.filename = splits.index
107
+ else:
108
+ self.filename = [splits.index[i] for i in torch.squeeze(torch.nonzero(mask))]
109
+ self.identity = identity.data[mask]
110
+ self.bbox = bbox.data[mask]
111
+ self.landmarks_align = landmarks_align.data[mask]
112
+ self.attr = attr.data[mask]
113
+ # map from {-1, 1} to {0, 1}
114
+ self.attr = torch.div(self.attr + 1, 2, rounding_mode="floor")
115
+ self.attr_names = attr.header
116
+
117
+ def _load_csv(
118
+ self,
119
+ filename: str,
120
+ header: Optional[int] = None,
121
+ ) -> CSV:
122
+ with open(os.path.join(self.root, self.base_folder, filename)) as csv_file:
123
+ data = list(csv.reader(csv_file, delimiter=" ", skipinitialspace=True))
124
+
125
+ if header is not None:
126
+ headers = data[header]
127
+ data = data[header + 1 :]
128
+ else:
129
+ headers = []
130
+
131
+ indices = [row[0] for row in data]
132
+ data = [row[1:] for row in data]
133
+ data_int = [list(map(int, i)) for i in data]
134
+
135
+ return CSV(headers, indices, torch.tensor(data_int))
136
+
137
+ def _check_integrity(self) -> bool:
138
+ for (_, md5, filename) in self.file_list:
139
+ fpath = os.path.join(self.root, self.base_folder, filename)
140
+ _, ext = os.path.splitext(filename)
141
+ # Allow original archive to be deleted (zip and 7z)
142
+ # Only need the extracted images
143
+ if ext not in [".zip", ".7z"] and not check_integrity(fpath, md5):
144
+ return False
145
+
146
+ # Should check a hash of the images
147
+ return os.path.isdir(os.path.join(self.root, self.base_folder, "img_align_celeba"))
148
+
149
+ def download(self) -> None:
150
+ if self._check_integrity():
151
+ print("Files already downloaded and verified")
152
+ return
153
+
154
+ for (file_id, md5, filename) in self.file_list:
155
+ download_file_from_google_drive(file_id, os.path.join(self.root, self.base_folder), filename, md5)
156
+
157
+ extract_archive(os.path.join(self.root, self.base_folder, "img_align_celeba.zip"))
158
+
159
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
160
+ X = PIL.Image.open(os.path.join(self.root, self.base_folder, "img_align_celeba", self.filename[index]))
161
+
162
+ target: Any = []
163
+ for t in self.target_type:
164
+ if t == "attr":
165
+ target.append(self.attr[index, :])
166
+ elif t == "identity":
167
+ target.append(self.identity[index, 0])
168
+ elif t == "bbox":
169
+ target.append(self.bbox[index, :])
170
+ elif t == "landmarks":
171
+ target.append(self.landmarks_align[index, :])
172
+ else:
173
+ # TODO: refactor with utils.verify_str_arg
174
+ raise ValueError(f'Target type "{t}" is not recognized.')
175
+
176
+ if self.transform is not None:
177
+ X = self.transform(X)
178
+
179
+ if target:
180
+ target = tuple(target) if len(target) > 1 else target[0]
181
+
182
+ if self.target_transform is not None:
183
+ target = self.target_transform(target)
184
+ else:
185
+ target = None
186
+
187
+ return X, target
188
+
189
+ def __len__(self) -> int:
190
+ return len(self.attr)
191
+
192
+ def extra_repr(self) -> str:
193
+ lines = ["Target type: {target_type}", "Split: {split}"]
194
+ return "\n".join(lines).format(**self.__dict__)
minigpt2/lib/python3.10/site-packages/torchvision/datasets/folder.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path
3
+ from pathlib import Path
4
+ from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
5
+
6
+ from PIL import Image
7
+
8
+ from .vision import VisionDataset
9
+
10
+
11
+ def has_file_allowed_extension(filename: str, extensions: Union[str, Tuple[str, ...]]) -> bool:
12
+ """Checks if a file is an allowed extension.
13
+
14
+ Args:
15
+ filename (string): path to a file
16
+ extensions (tuple of strings): extensions to consider (lowercase)
17
+
18
+ Returns:
19
+ bool: True if the filename ends with one of given extensions
20
+ """
21
+ return filename.lower().endswith(extensions if isinstance(extensions, str) else tuple(extensions))
22
+
23
+
24
+ def is_image_file(filename: str) -> bool:
25
+ """Checks if a file is an allowed image extension.
26
+
27
+ Args:
28
+ filename (string): path to a file
29
+
30
+ Returns:
31
+ bool: True if the filename ends with a known image extension
32
+ """
33
+ return has_file_allowed_extension(filename, IMG_EXTENSIONS)
34
+
35
+
36
+ def find_classes(directory: Union[str, Path]) -> Tuple[List[str], Dict[str, int]]:
37
+ """Finds the class folders in a dataset.
38
+
39
+ See :class:`DatasetFolder` for details.
40
+ """
41
+ classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())
42
+ if not classes:
43
+ raise FileNotFoundError(f"Couldn't find any class folder in {directory}.")
44
+
45
+ class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}
46
+ return classes, class_to_idx
47
+
48
+
49
+ def make_dataset(
50
+ directory: Union[str, Path],
51
+ class_to_idx: Optional[Dict[str, int]] = None,
52
+ extensions: Optional[Union[str, Tuple[str, ...]]] = None,
53
+ is_valid_file: Optional[Callable[[str], bool]] = None,
54
+ allow_empty: bool = False,
55
+ ) -> List[Tuple[str, int]]:
56
+ """Generates a list of samples of a form (path_to_sample, class).
57
+
58
+ See :class:`DatasetFolder` for details.
59
+
60
+ Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function
61
+ by default.
62
+ """
63
+ directory = os.path.expanduser(directory)
64
+
65
+ if class_to_idx is None:
66
+ _, class_to_idx = find_classes(directory)
67
+ elif not class_to_idx:
68
+ raise ValueError("'class_to_index' must have at least one entry to collect any samples.")
69
+
70
+ both_none = extensions is None and is_valid_file is None
71
+ both_something = extensions is not None and is_valid_file is not None
72
+ if both_none or both_something:
73
+ raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time")
74
+
75
+ if extensions is not None:
76
+
77
+ def is_valid_file(x: str) -> bool:
78
+ return has_file_allowed_extension(x, extensions) # type: ignore[arg-type]
79
+
80
+ is_valid_file = cast(Callable[[str], bool], is_valid_file)
81
+
82
+ instances = []
83
+ available_classes = set()
84
+ for target_class in sorted(class_to_idx.keys()):
85
+ class_index = class_to_idx[target_class]
86
+ target_dir = os.path.join(directory, target_class)
87
+ if not os.path.isdir(target_dir):
88
+ continue
89
+ for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):
90
+ for fname in sorted(fnames):
91
+ path = os.path.join(root, fname)
92
+ if is_valid_file(path):
93
+ item = path, class_index
94
+ instances.append(item)
95
+
96
+ if target_class not in available_classes:
97
+ available_classes.add(target_class)
98
+
99
+ empty_classes = set(class_to_idx.keys()) - available_classes
100
+ if empty_classes and not allow_empty:
101
+ msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. "
102
+ if extensions is not None:
103
+ msg += f"Supported extensions are: {extensions if isinstance(extensions, str) else ', '.join(extensions)}"
104
+ raise FileNotFoundError(msg)
105
+
106
+ return instances
107
+
108
+
109
+ class DatasetFolder(VisionDataset):
110
+ """A generic data loader.
111
+
112
+ This default directory structure can be customized by overriding the
113
+ :meth:`find_classes` method.
114
+
115
+ Args:
116
+ root (str or ``pathlib.Path``): Root directory path.
117
+ loader (callable): A function to load a sample given its path.
118
+ extensions (tuple[string]): A list of allowed extensions.
119
+ both extensions and is_valid_file should not be passed.
120
+ transform (callable, optional): A function/transform that takes in
121
+ a sample and returns a transformed version.
122
+ E.g, ``transforms.RandomCrop`` for images.
123
+ target_transform (callable, optional): A function/transform that takes
124
+ in the target and transforms it.
125
+ is_valid_file (callable, optional): A function that takes path of a file
126
+ and check if the file is a valid file (used to check of corrupt files)
127
+ both extensions and is_valid_file should not be passed.
128
+ allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
129
+ An error is raised on empty folders if False (default).
130
+
131
+ Attributes:
132
+ classes (list): List of the class names sorted alphabetically.
133
+ class_to_idx (dict): Dict with items (class_name, class_index).
134
+ samples (list): List of (sample path, class_index) tuples
135
+ targets (list): The class_index value for each image in the dataset
136
+ """
137
+
138
+ def __init__(
139
+ self,
140
+ root: Union[str, Path],
141
+ loader: Callable[[str], Any],
142
+ extensions: Optional[Tuple[str, ...]] = None,
143
+ transform: Optional[Callable] = None,
144
+ target_transform: Optional[Callable] = None,
145
+ is_valid_file: Optional[Callable[[str], bool]] = None,
146
+ allow_empty: bool = False,
147
+ ) -> None:
148
+ super().__init__(root, transform=transform, target_transform=target_transform)
149
+ classes, class_to_idx = self.find_classes(self.root)
150
+ samples = self.make_dataset(
151
+ self.root,
152
+ class_to_idx=class_to_idx,
153
+ extensions=extensions,
154
+ is_valid_file=is_valid_file,
155
+ allow_empty=allow_empty,
156
+ )
157
+
158
+ self.loader = loader
159
+ self.extensions = extensions
160
+
161
+ self.classes = classes
162
+ self.class_to_idx = class_to_idx
163
+ self.samples = samples
164
+ self.targets = [s[1] for s in samples]
165
+
166
+ @staticmethod
167
+ def make_dataset(
168
+ directory: Union[str, Path],
169
+ class_to_idx: Dict[str, int],
170
+ extensions: Optional[Tuple[str, ...]] = None,
171
+ is_valid_file: Optional[Callable[[str], bool]] = None,
172
+ allow_empty: bool = False,
173
+ ) -> List[Tuple[str, int]]:
174
+ """Generates a list of samples of a form (path_to_sample, class).
175
+
176
+ This can be overridden to e.g. read files from a compressed zip file instead of from the disk.
177
+
178
+ Args:
179
+ directory (str): root dataset directory, corresponding to ``self.root``.
180
+ class_to_idx (Dict[str, int]): Dictionary mapping class name to class index.
181
+ extensions (optional): A list of allowed extensions.
182
+ Either extensions or is_valid_file should be passed. Defaults to None.
183
+ is_valid_file (optional): A function that takes path of a file
184
+ and checks if the file is a valid file
185
+ (used to check of corrupt files) both extensions and
186
+ is_valid_file should not be passed. Defaults to None.
187
+ allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
188
+ An error is raised on empty folders if False (default).
189
+
190
+ Raises:
191
+ ValueError: In case ``class_to_idx`` is empty.
192
+ ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.
193
+ FileNotFoundError: In case no valid file was found for any class.
194
+
195
+ Returns:
196
+ List[Tuple[str, int]]: samples of a form (path_to_sample, class)
197
+ """
198
+ if class_to_idx is None:
199
+ # prevent potential bug since make_dataset() would use the class_to_idx logic of the
200
+ # find_classes() function, instead of using that of the find_classes() method, which
201
+ # is potentially overridden and thus could have a different logic.
202
+ raise ValueError("The class_to_idx parameter cannot be None.")
203
+ return make_dataset(
204
+ directory, class_to_idx, extensions=extensions, is_valid_file=is_valid_file, allow_empty=allow_empty
205
+ )
206
+
207
+ def find_classes(self, directory: Union[str, Path]) -> Tuple[List[str], Dict[str, int]]:
208
+ """Find the class folders in a dataset structured as follows::
209
+
210
+ directory/
211
+ ├── class_x
212
+ │ ├── xxx.ext
213
+ │ ├── xxy.ext
214
+ │ └── ...
215
+ │ └── xxz.ext
216
+ └── class_y
217
+ ├── 123.ext
218
+ ├── nsdf3.ext
219
+ └── ...
220
+ └── asd932_.ext
221
+
222
+ This method can be overridden to only consider
223
+ a subset of classes, or to adapt to a different dataset directory structure.
224
+
225
+ Args:
226
+ directory(str): Root directory path, corresponding to ``self.root``
227
+
228
+ Raises:
229
+ FileNotFoundError: If ``dir`` has no class folders.
230
+
231
+ Returns:
232
+ (Tuple[List[str], Dict[str, int]]): List of all classes and dictionary mapping each class to an index.
233
+ """
234
+ return find_classes(directory)
235
+
236
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
237
+ """
238
+ Args:
239
+ index (int): Index
240
+
241
+ Returns:
242
+ tuple: (sample, target) where target is class_index of the target class.
243
+ """
244
+ path, target = self.samples[index]
245
+ sample = self.loader(path)
246
+ if self.transform is not None:
247
+ sample = self.transform(sample)
248
+ if self.target_transform is not None:
249
+ target = self.target_transform(target)
250
+
251
+ return sample, target
252
+
253
+ def __len__(self) -> int:
254
+ return len(self.samples)
255
+
256
+
257
+ IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp")
258
+
259
+
260
+ def pil_loader(path: str) -> Image.Image:
261
+ # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
262
+ with open(path, "rb") as f:
263
+ img = Image.open(f)
264
+ return img.convert("RGB")
265
+
266
+
267
+ # TODO: specify the return type
268
+ def accimage_loader(path: str) -> Any:
269
+ import accimage
270
+
271
+ try:
272
+ return accimage.Image(path)
273
+ except OSError:
274
+ # Potentially a decoding problem, fall back to PIL.Image
275
+ return pil_loader(path)
276
+
277
+
278
+ def default_loader(path: str) -> Any:
279
+ from torchvision import get_image_backend
280
+
281
+ if get_image_backend() == "accimage":
282
+ return accimage_loader(path)
283
+ else:
284
+ return pil_loader(path)
285
+
286
+
287
+ class ImageFolder(DatasetFolder):
288
+ """A generic data loader where the images are arranged in this way by default: ::
289
+
290
+ root/dog/xxx.png
291
+ root/dog/xxy.png
292
+ root/dog/[...]/xxz.png
293
+
294
+ root/cat/123.png
295
+ root/cat/nsdf3.png
296
+ root/cat/[...]/asd932_.png
297
+
298
+ This class inherits from :class:`~torchvision.datasets.DatasetFolder` so
299
+ the same methods can be overridden to customize the dataset.
300
+
301
+ Args:
302
+ root (str or ``pathlib.Path``): Root directory path.
303
+ transform (callable, optional): A function/transform that takes in a PIL image
304
+ and returns a transformed version. E.g, ``transforms.RandomCrop``
305
+ target_transform (callable, optional): A function/transform that takes in the
306
+ target and transforms it.
307
+ loader (callable, optional): A function to load an image given its path.
308
+ is_valid_file (callable, optional): A function that takes path of an Image file
309
+ and check if the file is a valid file (used to check of corrupt files)
310
+ allow_empty(bool, optional): If True, empty folders are considered to be valid classes.
311
+ An error is raised on empty folders if False (default).
312
+
313
+ Attributes:
314
+ classes (list): List of the class names sorted alphabetically.
315
+ class_to_idx (dict): Dict with items (class_name, class_index).
316
+ imgs (list): List of (image path, class_index) tuples
317
+ """
318
+
319
+ def __init__(
320
+ self,
321
+ root: Union[str, Path],
322
+ transform: Optional[Callable] = None,
323
+ target_transform: Optional[Callable] = None,
324
+ loader: Callable[[str], Any] = default_loader,
325
+ is_valid_file: Optional[Callable[[str], bool]] = None,
326
+ allow_empty: bool = False,
327
+ ):
328
+ super().__init__(
329
+ root,
330
+ loader,
331
+ IMG_EXTENSIONS if is_valid_file is None else None,
332
+ transform=transform,
333
+ target_transform=target_transform,
334
+ is_valid_file=is_valid_file,
335
+ allow_empty=allow_empty,
336
+ )
337
+ self.imgs = self.samples
minigpt2/lib/python3.10/site-packages/torchvision/datasets/food101.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any, Callable, Optional, Tuple, Union
4
+
5
+ import PIL.Image
6
+
7
+ from .utils import download_and_extract_archive, verify_str_arg
8
+ from .vision import VisionDataset
9
+
10
+
11
+ class Food101(VisionDataset):
12
+ """`The Food-101 Data Set <https://data.vision.ee.ethz.ch/cvl/datasets_extra/food-101/>`_.
13
+
14
+ The Food-101 is a challenging data set of 101 food categories with 101,000 images.
15
+ For each class, 250 manually reviewed test images are provided as well as 750 training images.
16
+ On purpose, the training images were not cleaned, and thus still contain some amount of noise.
17
+ This comes mostly in the form of intense colors and sometimes wrong labels. All images were
18
+ rescaled to have a maximum side length of 512 pixels.
19
+
20
+
21
+ Args:
22
+ root (str or ``pathlib.Path``): Root directory of the dataset.
23
+ split (string, optional): The dataset split, supports ``"train"`` (default) and ``"test"``.
24
+ transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed
25
+ version. E.g, ``transforms.RandomCrop``.
26
+ target_transform (callable, optional): A function/transform that takes in the target and transforms it.
27
+ download (bool, optional): If True, downloads the dataset from the internet and
28
+ puts it in root directory. If dataset is already downloaded, it is not
29
+ downloaded again. Default is False.
30
+ """
31
+
32
+ _URL = "http://data.vision.ee.ethz.ch/cvl/food-101.tar.gz"
33
+ _MD5 = "85eeb15f3717b99a5da872d97d918f87"
34
+
35
+ def __init__(
36
+ self,
37
+ root: Union[str, Path],
38
+ split: str = "train",
39
+ transform: Optional[Callable] = None,
40
+ target_transform: Optional[Callable] = None,
41
+ download: bool = False,
42
+ ) -> None:
43
+ super().__init__(root, transform=transform, target_transform=target_transform)
44
+ self._split = verify_str_arg(split, "split", ("train", "test"))
45
+ self._base_folder = Path(self.root) / "food-101"
46
+ self._meta_folder = self._base_folder / "meta"
47
+ self._images_folder = self._base_folder / "images"
48
+
49
+ if download:
50
+ self._download()
51
+
52
+ if not self._check_exists():
53
+ raise RuntimeError("Dataset not found. You can use download=True to download it")
54
+
55
+ self._labels = []
56
+ self._image_files = []
57
+ with open(self._meta_folder / f"{split}.json") as f:
58
+ metadata = json.loads(f.read())
59
+
60
+ self.classes = sorted(metadata.keys())
61
+ self.class_to_idx = dict(zip(self.classes, range(len(self.classes))))
62
+
63
+ for class_label, im_rel_paths in metadata.items():
64
+ self._labels += [self.class_to_idx[class_label]] * len(im_rel_paths)
65
+ self._image_files += [
66
+ self._images_folder.joinpath(*f"{im_rel_path}.jpg".split("/")) for im_rel_path in im_rel_paths
67
+ ]
68
+
69
+ def __len__(self) -> int:
70
+ return len(self._image_files)
71
+
72
+ def __getitem__(self, idx: int) -> Tuple[Any, Any]:
73
+ image_file, label = self._image_files[idx], self._labels[idx]
74
+ image = PIL.Image.open(image_file).convert("RGB")
75
+
76
+ if self.transform:
77
+ image = self.transform(image)
78
+
79
+ if self.target_transform:
80
+ label = self.target_transform(label)
81
+
82
+ return image, label
83
+
84
+ def extra_repr(self) -> str:
85
+ return f"split={self._split}"
86
+
87
+ def _check_exists(self) -> bool:
88
+ return all(folder.exists() and folder.is_dir() for folder in (self._meta_folder, self._images_folder))
89
+
90
+ def _download(self) -> None:
91
+ if self._check_exists():
92
+ return
93
+ download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5)
minigpt2/lib/python3.10/site-packages/torchvision/datasets/lfw.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
4
+
5
+ from PIL import Image
6
+
7
+ from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg
8
+ from .vision import VisionDataset
9
+
10
+
11
+ class _LFW(VisionDataset):
12
+
13
+ base_folder = "lfw-py"
14
+ download_url_prefix = "http://vis-www.cs.umass.edu/lfw/"
15
+
16
+ file_dict = {
17
+ "original": ("lfw", "lfw.tgz", "a17d05bd522c52d84eca14327a23d494"),
18
+ "funneled": ("lfw_funneled", "lfw-funneled.tgz", "1b42dfed7d15c9b2dd63d5e5840c86ad"),
19
+ "deepfunneled": ("lfw-deepfunneled", "lfw-deepfunneled.tgz", "68331da3eb755a505a502b5aacb3c201"),
20
+ }
21
+ checksums = {
22
+ "pairs.txt": "9f1ba174e4e1c508ff7cdf10ac338a7d",
23
+ "pairsDevTest.txt": "5132f7440eb68cf58910c8a45a2ac10b",
24
+ "pairsDevTrain.txt": "4f27cbf15b2da4a85c1907eb4181ad21",
25
+ "people.txt": "450f0863dd89e85e73936a6d71a3474b",
26
+ "peopleDevTest.txt": "e4bf5be0a43b5dcd9dc5ccfcb8fb19c5",
27
+ "peopleDevTrain.txt": "54eaac34beb6d042ed3a7d883e247a21",
28
+ "lfw-names.txt": "a6d0a479bd074669f656265a6e693f6d",
29
+ }
30
+ annot_file = {"10fold": "", "train": "DevTrain", "test": "DevTest"}
31
+ names = "lfw-names.txt"
32
+
33
+ def __init__(
34
+ self,
35
+ root: Union[str, Path],
36
+ split: str,
37
+ image_set: str,
38
+ view: str,
39
+ transform: Optional[Callable] = None,
40
+ target_transform: Optional[Callable] = None,
41
+ download: bool = False,
42
+ ) -> None:
43
+ super().__init__(os.path.join(root, self.base_folder), transform=transform, target_transform=target_transform)
44
+
45
+ self.image_set = verify_str_arg(image_set.lower(), "image_set", self.file_dict.keys())
46
+ images_dir, self.filename, self.md5 = self.file_dict[self.image_set]
47
+
48
+ self.view = verify_str_arg(view.lower(), "view", ["people", "pairs"])
49
+ self.split = verify_str_arg(split.lower(), "split", ["10fold", "train", "test"])
50
+ self.labels_file = f"{self.view}{self.annot_file[self.split]}.txt"
51
+ self.data: List[Any] = []
52
+
53
+ if download:
54
+ self.download()
55
+
56
+ if not self._check_integrity():
57
+ raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
58
+
59
+ self.images_dir = os.path.join(self.root, images_dir)
60
+
61
+ def _loader(self, path: str) -> Image.Image:
62
+ with open(path, "rb") as f:
63
+ img = Image.open(f)
64
+ return img.convert("RGB")
65
+
66
+ def _check_integrity(self) -> bool:
67
+ st1 = check_integrity(os.path.join(self.root, self.filename), self.md5)
68
+ st2 = check_integrity(os.path.join(self.root, self.labels_file), self.checksums[self.labels_file])
69
+ if not st1 or not st2:
70
+ return False
71
+ if self.view == "people":
72
+ return check_integrity(os.path.join(self.root, self.names), self.checksums[self.names])
73
+ return True
74
+
75
+ def download(self) -> None:
76
+ if self._check_integrity():
77
+ print("Files already downloaded and verified")
78
+ return
79
+ url = f"{self.download_url_prefix}{self.filename}"
80
+ download_and_extract_archive(url, self.root, filename=self.filename, md5=self.md5)
81
+ download_url(f"{self.download_url_prefix}{self.labels_file}", self.root)
82
+ if self.view == "people":
83
+ download_url(f"{self.download_url_prefix}{self.names}", self.root)
84
+
85
+ def _get_path(self, identity: str, no: Union[int, str]) -> str:
86
+ return os.path.join(self.images_dir, identity, f"{identity}_{int(no):04d}.jpg")
87
+
88
+ def extra_repr(self) -> str:
89
+ return f"Alignment: {self.image_set}\nSplit: {self.split}"
90
+
91
+ def __len__(self) -> int:
92
+ return len(self.data)
93
+
94
+
95
+ class LFWPeople(_LFW):
96
+ """`LFW <http://vis-www.cs.umass.edu/lfw/>`_ Dataset.
97
+
98
+ Args:
99
+ root (str or ``pathlib.Path``): Root directory of dataset where directory
100
+ ``lfw-py`` exists or will be saved to if download is set to True.
101
+ split (string, optional): The image split to use. Can be one of ``train``, ``test``,
102
+ ``10fold`` (default).
103
+ image_set (str, optional): Type of image funneling to use, ``original``, ``funneled`` or
104
+ ``deepfunneled``. Defaults to ``funneled``.
105
+ transform (callable, optional): A function/transform that takes in a PIL image
106
+ and returns a transformed version. E.g, ``transforms.RandomRotation``
107
+ target_transform (callable, optional): A function/transform that takes in the
108
+ target and transforms it.
109
+ download (bool, optional): If true, downloads the dataset from the internet and
110
+ puts it in root directory. If dataset is already downloaded, it is not
111
+ downloaded again.
112
+
113
+ """
114
+
115
+ def __init__(
116
+ self,
117
+ root: str,
118
+ split: str = "10fold",
119
+ image_set: str = "funneled",
120
+ transform: Optional[Callable] = None,
121
+ target_transform: Optional[Callable] = None,
122
+ download: bool = False,
123
+ ) -> None:
124
+ super().__init__(root, split, image_set, "people", transform, target_transform, download)
125
+
126
+ self.class_to_idx = self._get_classes()
127
+ self.data, self.targets = self._get_people()
128
+
129
+ def _get_people(self) -> Tuple[List[str], List[int]]:
130
+ data, targets = [], []
131
+ with open(os.path.join(self.root, self.labels_file)) as f:
132
+ lines = f.readlines()
133
+ n_folds, s = (int(lines[0]), 1) if self.split == "10fold" else (1, 0)
134
+
135
+ for fold in range(n_folds):
136
+ n_lines = int(lines[s])
137
+ people = [line.strip().split("\t") for line in lines[s + 1 : s + n_lines + 1]]
138
+ s += n_lines + 1
139
+ for i, (identity, num_imgs) in enumerate(people):
140
+ for num in range(1, int(num_imgs) + 1):
141
+ img = self._get_path(identity, num)
142
+ data.append(img)
143
+ targets.append(self.class_to_idx[identity])
144
+
145
+ return data, targets
146
+
147
+ def _get_classes(self) -> Dict[str, int]:
148
+ with open(os.path.join(self.root, self.names)) as f:
149
+ lines = f.readlines()
150
+ names = [line.strip().split()[0] for line in lines]
151
+ class_to_idx = {name: i for i, name in enumerate(names)}
152
+ return class_to_idx
153
+
154
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
155
+ """
156
+ Args:
157
+ index (int): Index
158
+
159
+ Returns:
160
+ tuple: Tuple (image, target) where target is the identity of the person.
161
+ """
162
+ img = self._loader(self.data[index])
163
+ target = self.targets[index]
164
+
165
+ if self.transform is not None:
166
+ img = self.transform(img)
167
+
168
+ if self.target_transform is not None:
169
+ target = self.target_transform(target)
170
+
171
+ return img, target
172
+
173
+ def extra_repr(self) -> str:
174
+ return super().extra_repr() + f"\nClasses (identities): {len(self.class_to_idx)}"
175
+
176
+
177
+ class LFWPairs(_LFW):
178
+ """`LFW <http://vis-www.cs.umass.edu/lfw/>`_ Dataset.
179
+
180
+ Args:
181
+ root (str or ``pathlib.Path``): Root directory of dataset where directory
182
+ ``lfw-py`` exists or will be saved to if download is set to True.
183
+ split (string, optional): The image split to use. Can be one of ``train``, ``test``,
184
+ ``10fold``. Defaults to ``10fold``.
185
+ image_set (str, optional): Type of image funneling to use, ``original``, ``funneled`` or
186
+ ``deepfunneled``. Defaults to ``funneled``.
187
+ transform (callable, optional): A function/transform that takes in a PIL image
188
+ and returns a transformed version. E.g, ``transforms.RandomRotation``
189
+ target_transform (callable, optional): A function/transform that takes in the
190
+ target and transforms it.
191
+ download (bool, optional): If true, downloads the dataset from the internet and
192
+ puts it in root directory. If dataset is already downloaded, it is not
193
+ downloaded again.
194
+
195
+ """
196
+
197
+ def __init__(
198
+ self,
199
+ root: str,
200
+ split: str = "10fold",
201
+ image_set: str = "funneled",
202
+ transform: Optional[Callable] = None,
203
+ target_transform: Optional[Callable] = None,
204
+ download: bool = False,
205
+ ) -> None:
206
+ super().__init__(root, split, image_set, "pairs", transform, target_transform, download)
207
+
208
+ self.pair_names, self.data, self.targets = self._get_pairs(self.images_dir)
209
+
210
+ def _get_pairs(self, images_dir: str) -> Tuple[List[Tuple[str, str]], List[Tuple[str, str]], List[int]]:
211
+ pair_names, data, targets = [], [], []
212
+ with open(os.path.join(self.root, self.labels_file)) as f:
213
+ lines = f.readlines()
214
+ if self.split == "10fold":
215
+ n_folds, n_pairs = lines[0].split("\t")
216
+ n_folds, n_pairs = int(n_folds), int(n_pairs)
217
+ else:
218
+ n_folds, n_pairs = 1, int(lines[0])
219
+ s = 1
220
+
221
+ for fold in range(n_folds):
222
+ matched_pairs = [line.strip().split("\t") for line in lines[s : s + n_pairs]]
223
+ unmatched_pairs = [line.strip().split("\t") for line in lines[s + n_pairs : s + (2 * n_pairs)]]
224
+ s += 2 * n_pairs
225
+ for pair in matched_pairs:
226
+ img1, img2, same = self._get_path(pair[0], pair[1]), self._get_path(pair[0], pair[2]), 1
227
+ pair_names.append((pair[0], pair[0]))
228
+ data.append((img1, img2))
229
+ targets.append(same)
230
+ for pair in unmatched_pairs:
231
+ img1, img2, same = self._get_path(pair[0], pair[1]), self._get_path(pair[2], pair[3]), 0
232
+ pair_names.append((pair[0], pair[2]))
233
+ data.append((img1, img2))
234
+ targets.append(same)
235
+
236
+ return pair_names, data, targets
237
+
238
+ def __getitem__(self, index: int) -> Tuple[Any, Any, int]:
239
+ """
240
+ Args:
241
+ index (int): Index
242
+
243
+ Returns:
244
+ tuple: (image1, image2, target) where target is `0` for different indentities and `1` for same identities.
245
+ """
246
+ img1, img2 = self.data[index]
247
+ img1, img2 = self._loader(img1), self._loader(img2)
248
+ target = self.targets[index]
249
+
250
+ if self.transform is not None:
251
+ img1, img2 = self.transform(img1), self.transform(img2)
252
+
253
+ if self.target_transform is not None:
254
+ target = self.target_transform(target)
255
+
256
+ return img1, img2, target
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (811 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/_api.cpython-310.pyc ADDED
Binary file (9.55 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/_meta.cpython-310.pyc ADDED
Binary file (19.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (9.67 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/convnext.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/densenet.cpython-310.pyc ADDED
Binary file (14.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/efficientnet.cpython-310.pyc ADDED
Binary file (29.2 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/inception.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/mobilenet.cpython-310.pyc ADDED
Binary file (296 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/mobilenetv2.cpython-310.pyc ADDED
Binary file (7.78 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/regnet.cpython-310.pyc ADDED
Binary file (37.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/squeezenet.cpython-310.pyc ADDED
Binary file (7.37 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/swin_transformer.cpython-310.pyc ADDED
Binary file (28.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/vgg.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/__pycache__/vision_transformer.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .faster_rcnn import *
2
+ from .fcos import *
3
+ from .keypoint_rcnn import *
4
+ from .mask_rcnn import *
5
+ from .retinanet import *
6
+ from .ssd import *
7
+ from .ssdlite import *
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (327 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (18.3 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/anchor_utils.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/backbone_utils.cpython-310.pyc ADDED
Binary file (9.33 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/faster_rcnn.cpython-310.pyc ADDED
Binary file (30.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/fcos.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/generalized_rcnn.cpython-310.pyc ADDED
Binary file (3.79 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/image_list.cpython-310.pyc ADDED
Binary file (1.25 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/keypoint_rcnn.cpython-310.pyc ADDED
Binary file (19.7 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/mask_rcnn.cpython-310.pyc ADDED
Binary file (22.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/retinanet.cpython-310.pyc ADDED
Binary file (27.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/roi_heads.cpython-310.pyc ADDED
Binary file (22.1 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/rpn.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/ssd.cpython-310.pyc ADDED
Binary file (22.1 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/ssdlite.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/transform.cpython-310.pyc ADDED
Binary file (9.99 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/_utils.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections import OrderedDict
3
+ from typing import Dict, List, Optional, Tuple
4
+
5
+ import torch
6
+ from torch import nn, Tensor
7
+ from torch.nn import functional as F
8
+ from torchvision.ops import complete_box_iou_loss, distance_box_iou_loss, FrozenBatchNorm2d, generalized_box_iou_loss
9
+
10
+
11
+ class BalancedPositiveNegativeSampler:
12
+ """
13
+ This class samples batches, ensuring that they contain a fixed proportion of positives
14
+ """
15
+
16
+ def __init__(self, batch_size_per_image: int, positive_fraction: float) -> None:
17
+ """
18
+ Args:
19
+ batch_size_per_image (int): number of elements to be selected per image
20
+ positive_fraction (float): percentage of positive elements per batch
21
+ """
22
+ self.batch_size_per_image = batch_size_per_image
23
+ self.positive_fraction = positive_fraction
24
+
25
+ def __call__(self, matched_idxs: List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]:
26
+ """
27
+ Args:
28
+ matched_idxs: list of tensors containing -1, 0 or positive values.
29
+ Each tensor corresponds to a specific image.
30
+ -1 values are ignored, 0 are considered as negatives and > 0 as
31
+ positives.
32
+
33
+ Returns:
34
+ pos_idx (list[tensor])
35
+ neg_idx (list[tensor])
36
+
37
+ Returns two lists of binary masks for each image.
38
+ The first list contains the positive elements that were selected,
39
+ and the second list the negative example.
40
+ """
41
+ pos_idx = []
42
+ neg_idx = []
43
+ for matched_idxs_per_image in matched_idxs:
44
+ positive = torch.where(matched_idxs_per_image >= 1)[0]
45
+ negative = torch.where(matched_idxs_per_image == 0)[0]
46
+
47
+ num_pos = int(self.batch_size_per_image * self.positive_fraction)
48
+ # protect against not enough positive examples
49
+ num_pos = min(positive.numel(), num_pos)
50
+ num_neg = self.batch_size_per_image - num_pos
51
+ # protect against not enough negative examples
52
+ num_neg = min(negative.numel(), num_neg)
53
+
54
+ # randomly select positive and negative examples
55
+ perm1 = torch.randperm(positive.numel(), device=positive.device)[:num_pos]
56
+ perm2 = torch.randperm(negative.numel(), device=negative.device)[:num_neg]
57
+
58
+ pos_idx_per_image = positive[perm1]
59
+ neg_idx_per_image = negative[perm2]
60
+
61
+ # create binary mask from indices
62
+ pos_idx_per_image_mask = torch.zeros_like(matched_idxs_per_image, dtype=torch.uint8)
63
+ neg_idx_per_image_mask = torch.zeros_like(matched_idxs_per_image, dtype=torch.uint8)
64
+
65
+ pos_idx_per_image_mask[pos_idx_per_image] = 1
66
+ neg_idx_per_image_mask[neg_idx_per_image] = 1
67
+
68
+ pos_idx.append(pos_idx_per_image_mask)
69
+ neg_idx.append(neg_idx_per_image_mask)
70
+
71
+ return pos_idx, neg_idx
72
+
73
+
74
+ @torch.jit._script_if_tracing
75
+ def encode_boxes(reference_boxes: Tensor, proposals: Tensor, weights: Tensor) -> Tensor:
76
+ """
77
+ Encode a set of proposals with respect to some
78
+ reference boxes
79
+
80
+ Args:
81
+ reference_boxes (Tensor): reference boxes
82
+ proposals (Tensor): boxes to be encoded
83
+ weights (Tensor[4]): the weights for ``(x, y, w, h)``
84
+ """
85
+
86
+ # perform some unpacking to make it JIT-fusion friendly
87
+ wx = weights[0]
88
+ wy = weights[1]
89
+ ww = weights[2]
90
+ wh = weights[3]
91
+
92
+ proposals_x1 = proposals[:, 0].unsqueeze(1)
93
+ proposals_y1 = proposals[:, 1].unsqueeze(1)
94
+ proposals_x2 = proposals[:, 2].unsqueeze(1)
95
+ proposals_y2 = proposals[:, 3].unsqueeze(1)
96
+
97
+ reference_boxes_x1 = reference_boxes[:, 0].unsqueeze(1)
98
+ reference_boxes_y1 = reference_boxes[:, 1].unsqueeze(1)
99
+ reference_boxes_x2 = reference_boxes[:, 2].unsqueeze(1)
100
+ reference_boxes_y2 = reference_boxes[:, 3].unsqueeze(1)
101
+
102
+ # implementation starts here
103
+ ex_widths = proposals_x2 - proposals_x1
104
+ ex_heights = proposals_y2 - proposals_y1
105
+ ex_ctr_x = proposals_x1 + 0.5 * ex_widths
106
+ ex_ctr_y = proposals_y1 + 0.5 * ex_heights
107
+
108
+ gt_widths = reference_boxes_x2 - reference_boxes_x1
109
+ gt_heights = reference_boxes_y2 - reference_boxes_y1
110
+ gt_ctr_x = reference_boxes_x1 + 0.5 * gt_widths
111
+ gt_ctr_y = reference_boxes_y1 + 0.5 * gt_heights
112
+
113
+ targets_dx = wx * (gt_ctr_x - ex_ctr_x) / ex_widths
114
+ targets_dy = wy * (gt_ctr_y - ex_ctr_y) / ex_heights
115
+ targets_dw = ww * torch.log(gt_widths / ex_widths)
116
+ targets_dh = wh * torch.log(gt_heights / ex_heights)
117
+
118
+ targets = torch.cat((targets_dx, targets_dy, targets_dw, targets_dh), dim=1)
119
+ return targets
120
+
121
+
122
+ class BoxCoder:
123
+ """
124
+ This class encodes and decodes a set of bounding boxes into
125
+ the representation used for training the regressors.
126
+ """
127
+
128
+ def __init__(
129
+ self, weights: Tuple[float, float, float, float], bbox_xform_clip: float = math.log(1000.0 / 16)
130
+ ) -> None:
131
+ """
132
+ Args:
133
+ weights (4-element tuple)
134
+ bbox_xform_clip (float)
135
+ """
136
+ self.weights = weights
137
+ self.bbox_xform_clip = bbox_xform_clip
138
+
139
+ def encode(self, reference_boxes: List[Tensor], proposals: List[Tensor]) -> List[Tensor]:
140
+ boxes_per_image = [len(b) for b in reference_boxes]
141
+ reference_boxes = torch.cat(reference_boxes, dim=0)
142
+ proposals = torch.cat(proposals, dim=0)
143
+ targets = self.encode_single(reference_boxes, proposals)
144
+ return targets.split(boxes_per_image, 0)
145
+
146
+ def encode_single(self, reference_boxes: Tensor, proposals: Tensor) -> Tensor:
147
+ """
148
+ Encode a set of proposals with respect to some
149
+ reference boxes
150
+
151
+ Args:
152
+ reference_boxes (Tensor): reference boxes
153
+ proposals (Tensor): boxes to be encoded
154
+ """
155
+ dtype = reference_boxes.dtype
156
+ device = reference_boxes.device
157
+ weights = torch.as_tensor(self.weights, dtype=dtype, device=device)
158
+ targets = encode_boxes(reference_boxes, proposals, weights)
159
+
160
+ return targets
161
+
162
+ def decode(self, rel_codes: Tensor, boxes: List[Tensor]) -> Tensor:
163
+ torch._assert(
164
+ isinstance(boxes, (list, tuple)),
165
+ "This function expects boxes of type list or tuple.",
166
+ )
167
+ torch._assert(
168
+ isinstance(rel_codes, torch.Tensor),
169
+ "This function expects rel_codes of type torch.Tensor.",
170
+ )
171
+ boxes_per_image = [b.size(0) for b in boxes]
172
+ concat_boxes = torch.cat(boxes, dim=0)
173
+ box_sum = 0
174
+ for val in boxes_per_image:
175
+ box_sum += val
176
+ if box_sum > 0:
177
+ rel_codes = rel_codes.reshape(box_sum, -1)
178
+ pred_boxes = self.decode_single(rel_codes, concat_boxes)
179
+ if box_sum > 0:
180
+ pred_boxes = pred_boxes.reshape(box_sum, -1, 4)
181
+ return pred_boxes
182
+
183
+ def decode_single(self, rel_codes: Tensor, boxes: Tensor) -> Tensor:
184
+ """
185
+ From a set of original boxes and encoded relative box offsets,
186
+ get the decoded boxes.
187
+
188
+ Args:
189
+ rel_codes (Tensor): encoded boxes
190
+ boxes (Tensor): reference boxes.
191
+ """
192
+
193
+ boxes = boxes.to(rel_codes.dtype)
194
+
195
+ widths = boxes[:, 2] - boxes[:, 0]
196
+ heights = boxes[:, 3] - boxes[:, 1]
197
+ ctr_x = boxes[:, 0] + 0.5 * widths
198
+ ctr_y = boxes[:, 1] + 0.5 * heights
199
+
200
+ wx, wy, ww, wh = self.weights
201
+ dx = rel_codes[:, 0::4] / wx
202
+ dy = rel_codes[:, 1::4] / wy
203
+ dw = rel_codes[:, 2::4] / ww
204
+ dh = rel_codes[:, 3::4] / wh
205
+
206
+ # Prevent sending too large values into torch.exp()
207
+ dw = torch.clamp(dw, max=self.bbox_xform_clip)
208
+ dh = torch.clamp(dh, max=self.bbox_xform_clip)
209
+
210
+ pred_ctr_x = dx * widths[:, None] + ctr_x[:, None]
211
+ pred_ctr_y = dy * heights[:, None] + ctr_y[:, None]
212
+ pred_w = torch.exp(dw) * widths[:, None]
213
+ pred_h = torch.exp(dh) * heights[:, None]
214
+
215
+ # Distance from center to box's corner.
216
+ c_to_c_h = torch.tensor(0.5, dtype=pred_ctr_y.dtype, device=pred_h.device) * pred_h
217
+ c_to_c_w = torch.tensor(0.5, dtype=pred_ctr_x.dtype, device=pred_w.device) * pred_w
218
+
219
+ pred_boxes1 = pred_ctr_x - c_to_c_w
220
+ pred_boxes2 = pred_ctr_y - c_to_c_h
221
+ pred_boxes3 = pred_ctr_x + c_to_c_w
222
+ pred_boxes4 = pred_ctr_y + c_to_c_h
223
+ pred_boxes = torch.stack((pred_boxes1, pred_boxes2, pred_boxes3, pred_boxes4), dim=2).flatten(1)
224
+ return pred_boxes
225
+
226
+
227
+ class BoxLinearCoder:
228
+ """
229
+ The linear box-to-box transform defined in FCOS. The transformation is parameterized
230
+ by the distance from the center of (square) src box to 4 edges of the target box.
231
+ """
232
+
233
+ def __init__(self, normalize_by_size: bool = True) -> None:
234
+ """
235
+ Args:
236
+ normalize_by_size (bool): normalize deltas by the size of src (anchor) boxes.
237
+ """
238
+ self.normalize_by_size = normalize_by_size
239
+
240
+ def encode(self, reference_boxes: Tensor, proposals: Tensor) -> Tensor:
241
+ """
242
+ Encode a set of proposals with respect to some reference boxes
243
+
244
+ Args:
245
+ reference_boxes (Tensor): reference boxes
246
+ proposals (Tensor): boxes to be encoded
247
+
248
+ Returns:
249
+ Tensor: the encoded relative box offsets that can be used to
250
+ decode the boxes.
251
+
252
+ """
253
+
254
+ # get the center of reference_boxes
255
+ reference_boxes_ctr_x = 0.5 * (reference_boxes[..., 0] + reference_boxes[..., 2])
256
+ reference_boxes_ctr_y = 0.5 * (reference_boxes[..., 1] + reference_boxes[..., 3])
257
+
258
+ # get box regression transformation deltas
259
+ target_l = reference_boxes_ctr_x - proposals[..., 0]
260
+ target_t = reference_boxes_ctr_y - proposals[..., 1]
261
+ target_r = proposals[..., 2] - reference_boxes_ctr_x
262
+ target_b = proposals[..., 3] - reference_boxes_ctr_y
263
+
264
+ targets = torch.stack((target_l, target_t, target_r, target_b), dim=-1)
265
+
266
+ if self.normalize_by_size:
267
+ reference_boxes_w = reference_boxes[..., 2] - reference_boxes[..., 0]
268
+ reference_boxes_h = reference_boxes[..., 3] - reference_boxes[..., 1]
269
+ reference_boxes_size = torch.stack(
270
+ (reference_boxes_w, reference_boxes_h, reference_boxes_w, reference_boxes_h), dim=-1
271
+ )
272
+ targets = targets / reference_boxes_size
273
+ return targets
274
+
275
+ def decode(self, rel_codes: Tensor, boxes: Tensor) -> Tensor:
276
+
277
+ """
278
+ From a set of original boxes and encoded relative box offsets,
279
+ get the decoded boxes.
280
+
281
+ Args:
282
+ rel_codes (Tensor): encoded boxes
283
+ boxes (Tensor): reference boxes.
284
+
285
+ Returns:
286
+ Tensor: the predicted boxes with the encoded relative box offsets.
287
+
288
+ .. note::
289
+ This method assumes that ``rel_codes`` and ``boxes`` have same size for 0th dimension. i.e. ``len(rel_codes) == len(boxes)``.
290
+
291
+ """
292
+
293
+ boxes = boxes.to(dtype=rel_codes.dtype)
294
+
295
+ ctr_x = 0.5 * (boxes[..., 0] + boxes[..., 2])
296
+ ctr_y = 0.5 * (boxes[..., 1] + boxes[..., 3])
297
+
298
+ if self.normalize_by_size:
299
+ boxes_w = boxes[..., 2] - boxes[..., 0]
300
+ boxes_h = boxes[..., 3] - boxes[..., 1]
301
+
302
+ list_box_size = torch.stack((boxes_w, boxes_h, boxes_w, boxes_h), dim=-1)
303
+ rel_codes = rel_codes * list_box_size
304
+
305
+ pred_boxes1 = ctr_x - rel_codes[..., 0]
306
+ pred_boxes2 = ctr_y - rel_codes[..., 1]
307
+ pred_boxes3 = ctr_x + rel_codes[..., 2]
308
+ pred_boxes4 = ctr_y + rel_codes[..., 3]
309
+
310
+ pred_boxes = torch.stack((pred_boxes1, pred_boxes2, pred_boxes3, pred_boxes4), dim=-1)
311
+ return pred_boxes
312
+
313
+
314
+ class Matcher:
315
+ """
316
+ This class assigns to each predicted "element" (e.g., a box) a ground-truth
317
+ element. Each predicted element will have exactly zero or one matches; each
318
+ ground-truth element may be assigned to zero or more predicted elements.
319
+
320
+ Matching is based on the MxN match_quality_matrix, that characterizes how well
321
+ each (ground-truth, predicted)-pair match. For example, if the elements are
322
+ boxes, the matrix may contain box IoU overlap values.
323
+
324
+ The matcher returns a tensor of size N containing the index of the ground-truth
325
+ element m that matches to prediction n. If there is no match, a negative value
326
+ is returned.
327
+ """
328
+
329
+ BELOW_LOW_THRESHOLD = -1
330
+ BETWEEN_THRESHOLDS = -2
331
+
332
+ __annotations__ = {
333
+ "BELOW_LOW_THRESHOLD": int,
334
+ "BETWEEN_THRESHOLDS": int,
335
+ }
336
+
337
+ def __init__(self, high_threshold: float, low_threshold: float, allow_low_quality_matches: bool = False) -> None:
338
+ """
339
+ Args:
340
+ high_threshold (float): quality values greater than or equal to
341
+ this value are candidate matches.
342
+ low_threshold (float): a lower quality threshold used to stratify
343
+ matches into three levels:
344
+ 1) matches >= high_threshold
345
+ 2) BETWEEN_THRESHOLDS matches in [low_threshold, high_threshold)
346
+ 3) BELOW_LOW_THRESHOLD matches in [0, low_threshold)
347
+ allow_low_quality_matches (bool): if True, produce additional matches
348
+ for predictions that have only low-quality match candidates. See
349
+ set_low_quality_matches_ for more details.
350
+ """
351
+ self.BELOW_LOW_THRESHOLD = -1
352
+ self.BETWEEN_THRESHOLDS = -2
353
+ torch._assert(low_threshold <= high_threshold, "low_threshold should be <= high_threshold")
354
+ self.high_threshold = high_threshold
355
+ self.low_threshold = low_threshold
356
+ self.allow_low_quality_matches = allow_low_quality_matches
357
+
358
+ def __call__(self, match_quality_matrix: Tensor) -> Tensor:
359
+ """
360
+ Args:
361
+ match_quality_matrix (Tensor[float]): an MxN tensor, containing the
362
+ pairwise quality between M ground-truth elements and N predicted elements.
363
+
364
+ Returns:
365
+ matches (Tensor[int64]): an N tensor where N[i] is a matched gt in
366
+ [0, M - 1] or a negative value indicating that prediction i could not
367
+ be matched.
368
+ """
369
+ if match_quality_matrix.numel() == 0:
370
+ # empty targets or proposals not supported during training
371
+ if match_quality_matrix.shape[0] == 0:
372
+ raise ValueError("No ground-truth boxes available for one of the images during training")
373
+ else:
374
+ raise ValueError("No proposal boxes available for one of the images during training")
375
+
376
+ # match_quality_matrix is M (gt) x N (predicted)
377
+ # Max over gt elements (dim 0) to find best gt candidate for each prediction
378
+ matched_vals, matches = match_quality_matrix.max(dim=0)
379
+ if self.allow_low_quality_matches:
380
+ all_matches = matches.clone()
381
+ else:
382
+ all_matches = None # type: ignore[assignment]
383
+
384
+ # Assign candidate matches with low quality to negative (unassigned) values
385
+ below_low_threshold = matched_vals < self.low_threshold
386
+ between_thresholds = (matched_vals >= self.low_threshold) & (matched_vals < self.high_threshold)
387
+ matches[below_low_threshold] = self.BELOW_LOW_THRESHOLD
388
+ matches[between_thresholds] = self.BETWEEN_THRESHOLDS
389
+
390
+ if self.allow_low_quality_matches:
391
+ if all_matches is None:
392
+ torch._assert(False, "all_matches should not be None")
393
+ else:
394
+ self.set_low_quality_matches_(matches, all_matches, match_quality_matrix)
395
+
396
+ return matches
397
+
398
+ def set_low_quality_matches_(self, matches: Tensor, all_matches: Tensor, match_quality_matrix: Tensor) -> None:
399
+ """
400
+ Produce additional matches for predictions that have only low-quality matches.
401
+ Specifically, for each ground-truth find the set of predictions that have
402
+ maximum overlap with it (including ties); for each prediction in that set, if
403
+ it is unmatched, then match it to the ground-truth with which it has the highest
404
+ quality value.
405
+ """
406
+ # For each gt, find the prediction with which it has the highest quality
407
+ highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1)
408
+ # Find the highest quality match available, even if it is low, including ties
409
+ gt_pred_pairs_of_highest_quality = torch.where(match_quality_matrix == highest_quality_foreach_gt[:, None])
410
+ # Example gt_pred_pairs_of_highest_quality:
411
+ # (tensor([0, 1, 1, 2, 2, 3, 3, 4, 5, 5]),
412
+ # tensor([39796, 32055, 32070, 39190, 40255, 40390, 41455, 45470, 45325, 46390]))
413
+ # Each element in the first tensor is a gt index, and each element in second tensor is a prediction index
414
+ # Note how gt items 1, 2, 3, and 5 each have two ties
415
+
416
+ pred_inds_to_update = gt_pred_pairs_of_highest_quality[1]
417
+ matches[pred_inds_to_update] = all_matches[pred_inds_to_update]
418
+
419
+
420
+ class SSDMatcher(Matcher):
421
+ def __init__(self, threshold: float) -> None:
422
+ super().__init__(threshold, threshold, allow_low_quality_matches=False)
423
+
424
+ def __call__(self, match_quality_matrix: Tensor) -> Tensor:
425
+ matches = super().__call__(match_quality_matrix)
426
+
427
+ # For each gt, find the prediction with which it has the highest quality
428
+ _, highest_quality_pred_foreach_gt = match_quality_matrix.max(dim=1)
429
+ matches[highest_quality_pred_foreach_gt] = torch.arange(
430
+ highest_quality_pred_foreach_gt.size(0), dtype=torch.int64, device=highest_quality_pred_foreach_gt.device
431
+ )
432
+
433
+ return matches
434
+
435
+
436
+ def overwrite_eps(model: nn.Module, eps: float) -> None:
437
+ """
438
+ This method overwrites the default eps values of all the
439
+ FrozenBatchNorm2d layers of the model with the provided value.
440
+ This is necessary to address the BC-breaking change introduced
441
+ by the bug-fix at pytorch/vision#2933. The overwrite is applied
442
+ only when the pretrained weights are loaded to maintain compatibility
443
+ with previous versions.
444
+
445
+ Args:
446
+ model (nn.Module): The model on which we perform the overwrite.
447
+ eps (float): The new value of eps.
448
+ """
449
+ for module in model.modules():
450
+ if isinstance(module, FrozenBatchNorm2d):
451
+ module.eps = eps
452
+
453
+
454
+ def retrieve_out_channels(model: nn.Module, size: Tuple[int, int]) -> List[int]:
455
+ """
456
+ This method retrieves the number of output channels of a specific model.
457
+
458
+ Args:
459
+ model (nn.Module): The model for which we estimate the out_channels.
460
+ It should return a single Tensor or an OrderedDict[Tensor].
461
+ size (Tuple[int, int]): The size (wxh) of the input.
462
+
463
+ Returns:
464
+ out_channels (List[int]): A list of the output channels of the model.
465
+ """
466
+ in_training = model.training
467
+ model.eval()
468
+
469
+ with torch.no_grad():
470
+ # Use dummy data to retrieve the feature map sizes to avoid hard-coding their values
471
+ device = next(model.parameters()).device
472
+ tmp_img = torch.zeros((1, 3, size[1], size[0]), device=device)
473
+ features = model(tmp_img)
474
+ if isinstance(features, torch.Tensor):
475
+ features = OrderedDict([("0", features)])
476
+ out_channels = [x.size(1) for x in features.values()]
477
+
478
+ if in_training:
479
+ model.train()
480
+
481
+ return out_channels
482
+
483
+
484
+ @torch.jit.unused
485
+ def _fake_cast_onnx(v: Tensor) -> int:
486
+ return v # type: ignore[return-value]
487
+
488
+
489
+ def _topk_min(input: Tensor, orig_kval: int, axis: int) -> int:
490
+ """
491
+ ONNX spec requires the k-value to be less than or equal to the number of inputs along
492
+ provided dim. Certain models use the number of elements along a particular axis instead of K
493
+ if K exceeds the number of elements along that axis. Previously, python's min() function was
494
+ used to determine whether to use the provided k-value or the specified dim axis value.
495
+
496
+ However, in cases where the model is being exported in tracing mode, python min() is
497
+ static causing the model to be traced incorrectly and eventually fail at the topk node.
498
+ In order to avoid this situation, in tracing mode, torch.min() is used instead.
499
+
500
+ Args:
501
+ input (Tensor): The original input tensor.
502
+ orig_kval (int): The provided k-value.
503
+ axis(int): Axis along which we retrieve the input size.
504
+
505
+ Returns:
506
+ min_kval (int): Appropriately selected k-value.
507
+ """
508
+ if not torch.jit.is_tracing():
509
+ return min(orig_kval, input.size(axis))
510
+ axis_dim_val = torch._shape_as_tensor(input)[axis].unsqueeze(0)
511
+ min_kval = torch.min(torch.cat((torch.tensor([orig_kval], dtype=axis_dim_val.dtype), axis_dim_val), 0))
512
+ return _fake_cast_onnx(min_kval)
513
+
514
+
515
+ def _box_loss(
516
+ type: str,
517
+ box_coder: BoxCoder,
518
+ anchors_per_image: Tensor,
519
+ matched_gt_boxes_per_image: Tensor,
520
+ bbox_regression_per_image: Tensor,
521
+ cnf: Optional[Dict[str, float]] = None,
522
+ ) -> Tensor:
523
+ torch._assert(type in ["l1", "smooth_l1", "ciou", "diou", "giou"], f"Unsupported loss: {type}")
524
+
525
+ if type == "l1":
526
+ target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image)
527
+ return F.l1_loss(bbox_regression_per_image, target_regression, reduction="sum")
528
+ elif type == "smooth_l1":
529
+ target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image)
530
+ beta = cnf["beta"] if cnf is not None and "beta" in cnf else 1.0
531
+ return F.smooth_l1_loss(bbox_regression_per_image, target_regression, reduction="sum", beta=beta)
532
+ else:
533
+ bbox_per_image = box_coder.decode_single(bbox_regression_per_image, anchors_per_image)
534
+ eps = cnf["eps"] if cnf is not None and "eps" in cnf else 1e-7
535
+ if type == "ciou":
536
+ return complete_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps)
537
+ if type == "diou":
538
+ return distance_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps)
539
+ # otherwise giou
540
+ return generalized_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps)
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/anchor_utils.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional
3
+
4
+ import torch
5
+ from torch import nn, Tensor
6
+
7
+ from .image_list import ImageList
8
+
9
+
10
+ class AnchorGenerator(nn.Module):
11
+ """
12
+ Module that generates anchors for a set of feature maps and
13
+ image sizes.
14
+
15
+ The module support computing anchors at multiple sizes and aspect ratios
16
+ per feature map. This module assumes aspect ratio = height / width for
17
+ each anchor.
18
+
19
+ sizes and aspect_ratios should have the same number of elements, and it should
20
+ correspond to the number of feature maps.
21
+
22
+ sizes[i] and aspect_ratios[i] can have an arbitrary number of elements,
23
+ and AnchorGenerator will output a set of sizes[i] * aspect_ratios[i] anchors
24
+ per spatial location for feature map i.
25
+
26
+ Args:
27
+ sizes (Tuple[Tuple[int]]):
28
+ aspect_ratios (Tuple[Tuple[float]]):
29
+ """
30
+
31
+ __annotations__ = {
32
+ "cell_anchors": List[torch.Tensor],
33
+ }
34
+
35
+ def __init__(
36
+ self,
37
+ sizes=((128, 256, 512),),
38
+ aspect_ratios=((0.5, 1.0, 2.0),),
39
+ ):
40
+ super().__init__()
41
+
42
+ if not isinstance(sizes[0], (list, tuple)):
43
+ # TODO change this
44
+ sizes = tuple((s,) for s in sizes)
45
+ if not isinstance(aspect_ratios[0], (list, tuple)):
46
+ aspect_ratios = (aspect_ratios,) * len(sizes)
47
+
48
+ self.sizes = sizes
49
+ self.aspect_ratios = aspect_ratios
50
+ self.cell_anchors = [
51
+ self.generate_anchors(size, aspect_ratio) for size, aspect_ratio in zip(sizes, aspect_ratios)
52
+ ]
53
+
54
+ # TODO: https://github.com/pytorch/pytorch/issues/26792
55
+ # For every (aspect_ratios, scales) combination, output a zero-centered anchor with those values.
56
+ # (scales, aspect_ratios) are usually an element of zip(self.scales, self.aspect_ratios)
57
+ # This method assumes aspect ratio = height / width for an anchor.
58
+ def generate_anchors(
59
+ self,
60
+ scales: List[int],
61
+ aspect_ratios: List[float],
62
+ dtype: torch.dtype = torch.float32,
63
+ device: torch.device = torch.device("cpu"),
64
+ ) -> Tensor:
65
+ scales = torch.as_tensor(scales, dtype=dtype, device=device)
66
+ aspect_ratios = torch.as_tensor(aspect_ratios, dtype=dtype, device=device)
67
+ h_ratios = torch.sqrt(aspect_ratios)
68
+ w_ratios = 1 / h_ratios
69
+
70
+ ws = (w_ratios[:, None] * scales[None, :]).view(-1)
71
+ hs = (h_ratios[:, None] * scales[None, :]).view(-1)
72
+
73
+ base_anchors = torch.stack([-ws, -hs, ws, hs], dim=1) / 2
74
+ return base_anchors.round()
75
+
76
+ def set_cell_anchors(self, dtype: torch.dtype, device: torch.device):
77
+ self.cell_anchors = [cell_anchor.to(dtype=dtype, device=device) for cell_anchor in self.cell_anchors]
78
+
79
+ def num_anchors_per_location(self) -> List[int]:
80
+ return [len(s) * len(a) for s, a in zip(self.sizes, self.aspect_ratios)]
81
+
82
+ # For every combination of (a, (g, s), i) in (self.cell_anchors, zip(grid_sizes, strides), 0:2),
83
+ # output g[i] anchors that are s[i] distance apart in direction i, with the same dimensions as a.
84
+ def grid_anchors(self, grid_sizes: List[List[int]], strides: List[List[Tensor]]) -> List[Tensor]:
85
+ anchors = []
86
+ cell_anchors = self.cell_anchors
87
+ torch._assert(cell_anchors is not None, "cell_anchors should not be None")
88
+ torch._assert(
89
+ len(grid_sizes) == len(strides) == len(cell_anchors),
90
+ "Anchors should be Tuple[Tuple[int]] because each feature "
91
+ "map could potentially have different sizes and aspect ratios. "
92
+ "There needs to be a match between the number of "
93
+ "feature maps passed and the number of sizes / aspect ratios specified.",
94
+ )
95
+
96
+ for size, stride, base_anchors in zip(grid_sizes, strides, cell_anchors):
97
+ grid_height, grid_width = size
98
+ stride_height, stride_width = stride
99
+ device = base_anchors.device
100
+
101
+ # For output anchor, compute [x_center, y_center, x_center, y_center]
102
+ shifts_x = torch.arange(0, grid_width, dtype=torch.int32, device=device) * stride_width
103
+ shifts_y = torch.arange(0, grid_height, dtype=torch.int32, device=device) * stride_height
104
+ shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x, indexing="ij")
105
+ shift_x = shift_x.reshape(-1)
106
+ shift_y = shift_y.reshape(-1)
107
+ shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1)
108
+
109
+ # For every (base anchor, output anchor) pair,
110
+ # offset each zero-centered base anchor by the center of the output anchor.
111
+ anchors.append((shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4))
112
+
113
+ return anchors
114
+
115
+ def forward(self, image_list: ImageList, feature_maps: List[Tensor]) -> List[Tensor]:
116
+ grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps]
117
+ image_size = image_list.tensors.shape[-2:]
118
+ dtype, device = feature_maps[0].dtype, feature_maps[0].device
119
+ strides = [
120
+ [
121
+ torch.empty((), dtype=torch.int64, device=device).fill_(image_size[0] // g[0]),
122
+ torch.empty((), dtype=torch.int64, device=device).fill_(image_size[1] // g[1]),
123
+ ]
124
+ for g in grid_sizes
125
+ ]
126
+ self.set_cell_anchors(dtype, device)
127
+ anchors_over_all_feature_maps = self.grid_anchors(grid_sizes, strides)
128
+ anchors: List[List[torch.Tensor]] = []
129
+ for _ in range(len(image_list.image_sizes)):
130
+ anchors_in_image = [anchors_per_feature_map for anchors_per_feature_map in anchors_over_all_feature_maps]
131
+ anchors.append(anchors_in_image)
132
+ anchors = [torch.cat(anchors_per_image) for anchors_per_image in anchors]
133
+ return anchors
134
+
135
+
136
+ class DefaultBoxGenerator(nn.Module):
137
+ """
138
+ This module generates the default boxes of SSD for a set of feature maps and image sizes.
139
+
140
+ Args:
141
+ aspect_ratios (List[List[int]]): A list with all the aspect ratios used in each feature map.
142
+ min_ratio (float): The minimum scale :math:`\text{s}_{\text{min}}` of the default boxes used in the estimation
143
+ of the scales of each feature map. It is used only if the ``scales`` parameter is not provided.
144
+ max_ratio (float): The maximum scale :math:`\text{s}_{\text{max}}` of the default boxes used in the estimation
145
+ of the scales of each feature map. It is used only if the ``scales`` parameter is not provided.
146
+ scales (List[float]], optional): The scales of the default boxes. If not provided it will be estimated using
147
+ the ``min_ratio`` and ``max_ratio`` parameters.
148
+ steps (List[int]], optional): It's a hyper-parameter that affects the tiling of default boxes. If not provided
149
+ it will be estimated from the data.
150
+ clip (bool): Whether the standardized values of default boxes should be clipped between 0 and 1. The clipping
151
+ is applied while the boxes are encoded in format ``(cx, cy, w, h)``.
152
+ """
153
+
154
+ def __init__(
155
+ self,
156
+ aspect_ratios: List[List[int]],
157
+ min_ratio: float = 0.15,
158
+ max_ratio: float = 0.9,
159
+ scales: Optional[List[float]] = None,
160
+ steps: Optional[List[int]] = None,
161
+ clip: bool = True,
162
+ ):
163
+ super().__init__()
164
+ if steps is not None and len(aspect_ratios) != len(steps):
165
+ raise ValueError("aspect_ratios and steps should have the same length")
166
+ self.aspect_ratios = aspect_ratios
167
+ self.steps = steps
168
+ self.clip = clip
169
+ num_outputs = len(aspect_ratios)
170
+
171
+ # Estimation of default boxes scales
172
+ if scales is None:
173
+ if num_outputs > 1:
174
+ range_ratio = max_ratio - min_ratio
175
+ self.scales = [min_ratio + range_ratio * k / (num_outputs - 1.0) for k in range(num_outputs)]
176
+ self.scales.append(1.0)
177
+ else:
178
+ self.scales = [min_ratio, max_ratio]
179
+ else:
180
+ self.scales = scales
181
+
182
+ self._wh_pairs = self._generate_wh_pairs(num_outputs)
183
+
184
+ def _generate_wh_pairs(
185
+ self, num_outputs: int, dtype: torch.dtype = torch.float32, device: torch.device = torch.device("cpu")
186
+ ) -> List[Tensor]:
187
+ _wh_pairs: List[Tensor] = []
188
+ for k in range(num_outputs):
189
+ # Adding the 2 default width-height pairs for aspect ratio 1 and scale s'k
190
+ s_k = self.scales[k]
191
+ s_prime_k = math.sqrt(self.scales[k] * self.scales[k + 1])
192
+ wh_pairs = [[s_k, s_k], [s_prime_k, s_prime_k]]
193
+
194
+ # Adding 2 pairs for each aspect ratio of the feature map k
195
+ for ar in self.aspect_ratios[k]:
196
+ sq_ar = math.sqrt(ar)
197
+ w = self.scales[k] * sq_ar
198
+ h = self.scales[k] / sq_ar
199
+ wh_pairs.extend([[w, h], [h, w]])
200
+
201
+ _wh_pairs.append(torch.as_tensor(wh_pairs, dtype=dtype, device=device))
202
+ return _wh_pairs
203
+
204
+ def num_anchors_per_location(self) -> List[int]:
205
+ # Estimate num of anchors based on aspect ratios: 2 default boxes + 2 * ratios of feaure map.
206
+ return [2 + 2 * len(r) for r in self.aspect_ratios]
207
+
208
+ # Default Boxes calculation based on page 6 of SSD paper
209
+ def _grid_default_boxes(
210
+ self, grid_sizes: List[List[int]], image_size: List[int], dtype: torch.dtype = torch.float32
211
+ ) -> Tensor:
212
+ default_boxes = []
213
+ for k, f_k in enumerate(grid_sizes):
214
+ # Now add the default boxes for each width-height pair
215
+ if self.steps is not None:
216
+ x_f_k = image_size[1] / self.steps[k]
217
+ y_f_k = image_size[0] / self.steps[k]
218
+ else:
219
+ y_f_k, x_f_k = f_k
220
+
221
+ shifts_x = ((torch.arange(0, f_k[1]) + 0.5) / x_f_k).to(dtype=dtype)
222
+ shifts_y = ((torch.arange(0, f_k[0]) + 0.5) / y_f_k).to(dtype=dtype)
223
+ shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x, indexing="ij")
224
+ shift_x = shift_x.reshape(-1)
225
+ shift_y = shift_y.reshape(-1)
226
+
227
+ shifts = torch.stack((shift_x, shift_y) * len(self._wh_pairs[k]), dim=-1).reshape(-1, 2)
228
+ # Clipping the default boxes while the boxes are encoded in format (cx, cy, w, h)
229
+ _wh_pair = self._wh_pairs[k].clamp(min=0, max=1) if self.clip else self._wh_pairs[k]
230
+ wh_pairs = _wh_pair.repeat((f_k[0] * f_k[1]), 1)
231
+
232
+ default_box = torch.cat((shifts, wh_pairs), dim=1)
233
+
234
+ default_boxes.append(default_box)
235
+
236
+ return torch.cat(default_boxes, dim=0)
237
+
238
+ def __repr__(self) -> str:
239
+ s = (
240
+ f"{self.__class__.__name__}("
241
+ f"aspect_ratios={self.aspect_ratios}"
242
+ f", clip={self.clip}"
243
+ f", scales={self.scales}"
244
+ f", steps={self.steps}"
245
+ ")"
246
+ )
247
+ return s
248
+
249
+ def forward(self, image_list: ImageList, feature_maps: List[Tensor]) -> List[Tensor]:
250
+ grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps]
251
+ image_size = image_list.tensors.shape[-2:]
252
+ dtype, device = feature_maps[0].dtype, feature_maps[0].device
253
+ default_boxes = self._grid_default_boxes(grid_sizes, image_size, dtype=dtype)
254
+ default_boxes = default_boxes.to(device)
255
+
256
+ dboxes = []
257
+ x_y_size = torch.tensor([image_size[1], image_size[0]], device=default_boxes.device)
258
+ for _ in image_list.image_sizes:
259
+ dboxes_in_image = default_boxes
260
+ dboxes_in_image = torch.cat(
261
+ [
262
+ (dboxes_in_image[:, :2] - 0.5 * dboxes_in_image[:, 2:]) * x_y_size,
263
+ (dboxes_in_image[:, :2] + 0.5 * dboxes_in_image[:, 2:]) * x_y_size,
264
+ ],
265
+ -1,
266
+ )
267
+ dboxes.append(dboxes_in_image)
268
+ return dboxes
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/backbone_utils.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import Callable, Dict, List, Optional, Union
3
+
4
+ from torch import nn, Tensor
5
+ from torchvision.ops import misc as misc_nn_ops
6
+ from torchvision.ops.feature_pyramid_network import ExtraFPNBlock, FeaturePyramidNetwork, LastLevelMaxPool
7
+
8
+ from .. import mobilenet, resnet
9
+ from .._api import _get_enum_from_fn, WeightsEnum
10
+ from .._utils import handle_legacy_interface, IntermediateLayerGetter
11
+
12
+
13
+ class BackboneWithFPN(nn.Module):
14
+ """
15
+ Adds a FPN on top of a model.
16
+ Internally, it uses torchvision.models._utils.IntermediateLayerGetter to
17
+ extract a submodel that returns the feature maps specified in return_layers.
18
+ The same limitations of IntermediateLayerGetter apply here.
19
+ Args:
20
+ backbone (nn.Module)
21
+ return_layers (Dict[name, new_name]): a dict containing the names
22
+ of the modules for which the activations will be returned as
23
+ the key of the dict, and the value of the dict is the name
24
+ of the returned activation (which the user can specify).
25
+ in_channels_list (List[int]): number of channels for each feature map
26
+ that is returned, in the order they are present in the OrderedDict
27
+ out_channels (int): number of channels in the FPN.
28
+ norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
29
+ Attributes:
30
+ out_channels (int): the number of channels in the FPN
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ backbone: nn.Module,
36
+ return_layers: Dict[str, str],
37
+ in_channels_list: List[int],
38
+ out_channels: int,
39
+ extra_blocks: Optional[ExtraFPNBlock] = None,
40
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
41
+ ) -> None:
42
+ super().__init__()
43
+
44
+ if extra_blocks is None:
45
+ extra_blocks = LastLevelMaxPool()
46
+
47
+ self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
48
+ self.fpn = FeaturePyramidNetwork(
49
+ in_channels_list=in_channels_list,
50
+ out_channels=out_channels,
51
+ extra_blocks=extra_blocks,
52
+ norm_layer=norm_layer,
53
+ )
54
+ self.out_channels = out_channels
55
+
56
+ def forward(self, x: Tensor) -> Dict[str, Tensor]:
57
+ x = self.body(x)
58
+ x = self.fpn(x)
59
+ return x
60
+
61
+
62
+ @handle_legacy_interface(
63
+ weights=(
64
+ "pretrained",
65
+ lambda kwargs: _get_enum_from_fn(resnet.__dict__[kwargs["backbone_name"]])["IMAGENET1K_V1"],
66
+ ),
67
+ )
68
+ def resnet_fpn_backbone(
69
+ *,
70
+ backbone_name: str,
71
+ weights: Optional[WeightsEnum],
72
+ norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
73
+ trainable_layers: int = 3,
74
+ returned_layers: Optional[List[int]] = None,
75
+ extra_blocks: Optional[ExtraFPNBlock] = None,
76
+ ) -> BackboneWithFPN:
77
+ """
78
+ Constructs a specified ResNet backbone with FPN on top. Freezes the specified number of layers in the backbone.
79
+
80
+ Examples::
81
+
82
+ >>> import torch
83
+ >>> from torchvision.models import ResNet50_Weights
84
+ >>> from torchvision.models.detection.backbone_utils import resnet_fpn_backbone
85
+ >>> backbone = resnet_fpn_backbone(backbone_name='resnet50', weights=ResNet50_Weights.DEFAULT, trainable_layers=3)
86
+ >>> # get some dummy image
87
+ >>> x = torch.rand(1,3,64,64)
88
+ >>> # compute the output
89
+ >>> output = backbone(x)
90
+ >>> print([(k, v.shape) for k, v in output.items()])
91
+ >>> # returns
92
+ >>> [('0', torch.Size([1, 256, 16, 16])),
93
+ >>> ('1', torch.Size([1, 256, 8, 8])),
94
+ >>> ('2', torch.Size([1, 256, 4, 4])),
95
+ >>> ('3', torch.Size([1, 256, 2, 2])),
96
+ >>> ('pool', torch.Size([1, 256, 1, 1]))]
97
+
98
+ Args:
99
+ backbone_name (string): resnet architecture. Possible values are 'resnet18', 'resnet34', 'resnet50',
100
+ 'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2'
101
+ weights (WeightsEnum, optional): The pretrained weights for the model
102
+ norm_layer (callable): it is recommended to use the default value. For details visit:
103
+ (https://github.com/facebookresearch/maskrcnn-benchmark/issues/267)
104
+ trainable_layers (int): number of trainable (not frozen) layers starting from final block.
105
+ Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable.
106
+ returned_layers (list of int): The layers of the network to return. Each entry must be in ``[1, 4]``.
107
+ By default, all layers are returned.
108
+ extra_blocks (ExtraFPNBlock or None): if provided, extra operations will
109
+ be performed. It is expected to take the fpn features, the original
110
+ features and the names of the original features as input, and returns
111
+ a new list of feature maps and their corresponding names. By
112
+ default, a ``LastLevelMaxPool`` is used.
113
+ """
114
+ backbone = resnet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer)
115
+ return _resnet_fpn_extractor(backbone, trainable_layers, returned_layers, extra_blocks)
116
+
117
+
118
+ def _resnet_fpn_extractor(
119
+ backbone: resnet.ResNet,
120
+ trainable_layers: int,
121
+ returned_layers: Optional[List[int]] = None,
122
+ extra_blocks: Optional[ExtraFPNBlock] = None,
123
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
124
+ ) -> BackboneWithFPN:
125
+
126
+ # select layers that won't be frozen
127
+ if trainable_layers < 0 or trainable_layers > 5:
128
+ raise ValueError(f"Trainable layers should be in the range [0,5], got {trainable_layers}")
129
+ layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers]
130
+ if trainable_layers == 5:
131
+ layers_to_train.append("bn1")
132
+ for name, parameter in backbone.named_parameters():
133
+ if all([not name.startswith(layer) for layer in layers_to_train]):
134
+ parameter.requires_grad_(False)
135
+
136
+ if extra_blocks is None:
137
+ extra_blocks = LastLevelMaxPool()
138
+
139
+ if returned_layers is None:
140
+ returned_layers = [1, 2, 3, 4]
141
+ if min(returned_layers) <= 0 or max(returned_layers) >= 5:
142
+ raise ValueError(f"Each returned layer should be in the range [1,4]. Got {returned_layers}")
143
+ return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)}
144
+
145
+ in_channels_stage2 = backbone.inplanes // 8
146
+ in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers]
147
+ out_channels = 256
148
+ return BackboneWithFPN(
149
+ backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer
150
+ )
151
+
152
+
153
+ def _validate_trainable_layers(
154
+ is_trained: bool,
155
+ trainable_backbone_layers: Optional[int],
156
+ max_value: int,
157
+ default_value: int,
158
+ ) -> int:
159
+ # don't freeze any layers if pretrained model or backbone is not used
160
+ if not is_trained:
161
+ if trainable_backbone_layers is not None:
162
+ warnings.warn(
163
+ "Changing trainable_backbone_layers has no effect if "
164
+ "neither pretrained nor pretrained_backbone have been set to True, "
165
+ f"falling back to trainable_backbone_layers={max_value} so that all layers are trainable"
166
+ )
167
+ trainable_backbone_layers = max_value
168
+
169
+ # by default freeze first blocks
170
+ if trainable_backbone_layers is None:
171
+ trainable_backbone_layers = default_value
172
+ if trainable_backbone_layers < 0 or trainable_backbone_layers > max_value:
173
+ raise ValueError(
174
+ f"Trainable backbone layers should be in the range [0,{max_value}], got {trainable_backbone_layers} "
175
+ )
176
+ return trainable_backbone_layers
177
+
178
+
179
+ @handle_legacy_interface(
180
+ weights=(
181
+ "pretrained",
182
+ lambda kwargs: _get_enum_from_fn(mobilenet.__dict__[kwargs["backbone_name"]])["IMAGENET1K_V1"],
183
+ ),
184
+ )
185
+ def mobilenet_backbone(
186
+ *,
187
+ backbone_name: str,
188
+ weights: Optional[WeightsEnum],
189
+ fpn: bool,
190
+ norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
191
+ trainable_layers: int = 2,
192
+ returned_layers: Optional[List[int]] = None,
193
+ extra_blocks: Optional[ExtraFPNBlock] = None,
194
+ ) -> nn.Module:
195
+ backbone = mobilenet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer)
196
+ return _mobilenet_extractor(backbone, fpn, trainable_layers, returned_layers, extra_blocks)
197
+
198
+
199
+ def _mobilenet_extractor(
200
+ backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3],
201
+ fpn: bool,
202
+ trainable_layers: int,
203
+ returned_layers: Optional[List[int]] = None,
204
+ extra_blocks: Optional[ExtraFPNBlock] = None,
205
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
206
+ ) -> nn.Module:
207
+ backbone = backbone.features
208
+ # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks.
209
+ # The first and last blocks are always included because they are the C0 (conv1) and Cn.
210
+ stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1]
211
+ num_stages = len(stage_indices)
212
+
213
+ # find the index of the layer from which we won't freeze
214
+ if trainable_layers < 0 or trainable_layers > num_stages:
215
+ raise ValueError(f"Trainable layers should be in the range [0,{num_stages}], got {trainable_layers} ")
216
+ freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers]
217
+
218
+ for b in backbone[:freeze_before]:
219
+ for parameter in b.parameters():
220
+ parameter.requires_grad_(False)
221
+
222
+ out_channels = 256
223
+ if fpn:
224
+ if extra_blocks is None:
225
+ extra_blocks = LastLevelMaxPool()
226
+
227
+ if returned_layers is None:
228
+ returned_layers = [num_stages - 2, num_stages - 1]
229
+ if min(returned_layers) < 0 or max(returned_layers) >= num_stages:
230
+ raise ValueError(f"Each returned layer should be in the range [0,{num_stages - 1}], got {returned_layers} ")
231
+ return_layers = {f"{stage_indices[k]}": str(v) for v, k in enumerate(returned_layers)}
232
+
233
+ in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers]
234
+ return BackboneWithFPN(
235
+ backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer
236
+ )
237
+ else:
238
+ m = nn.Sequential(
239
+ backbone,
240
+ # depthwise linear combination of channels to reduce their size
241
+ nn.Conv2d(backbone[-1].out_channels, out_channels, 1),
242
+ )
243
+ m.out_channels = out_channels # type: ignore[assignment]
244
+ return m
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/faster_rcnn.py ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+ from torchvision.ops import MultiScaleRoIAlign
7
+
8
+ from ...ops import misc as misc_nn_ops
9
+ from ...transforms._presets import ObjectDetection
10
+ from .._api import register_model, Weights, WeightsEnum
11
+ from .._meta import _COCO_CATEGORIES
12
+ from .._utils import _ovewrite_value_param, handle_legacy_interface
13
+ from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights
14
+ from ..resnet import resnet50, ResNet50_Weights
15
+ from ._utils import overwrite_eps
16
+ from .anchor_utils import AnchorGenerator
17
+ from .backbone_utils import _mobilenet_extractor, _resnet_fpn_extractor, _validate_trainable_layers
18
+ from .generalized_rcnn import GeneralizedRCNN
19
+ from .roi_heads import RoIHeads
20
+ from .rpn import RegionProposalNetwork, RPNHead
21
+ from .transform import GeneralizedRCNNTransform
22
+
23
+
24
+ __all__ = [
25
+ "FasterRCNN",
26
+ "FasterRCNN_ResNet50_FPN_Weights",
27
+ "FasterRCNN_ResNet50_FPN_V2_Weights",
28
+ "FasterRCNN_MobileNet_V3_Large_FPN_Weights",
29
+ "FasterRCNN_MobileNet_V3_Large_320_FPN_Weights",
30
+ "fasterrcnn_resnet50_fpn",
31
+ "fasterrcnn_resnet50_fpn_v2",
32
+ "fasterrcnn_mobilenet_v3_large_fpn",
33
+ "fasterrcnn_mobilenet_v3_large_320_fpn",
34
+ ]
35
+
36
+
37
+ def _default_anchorgen():
38
+ anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
39
+ aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
40
+ return AnchorGenerator(anchor_sizes, aspect_ratios)
41
+
42
+
43
+ class FasterRCNN(GeneralizedRCNN):
44
+ """
45
+ Implements Faster R-CNN.
46
+
47
+ The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
48
+ image, and should be in 0-1 range. Different images can have different sizes.
49
+
50
+ The behavior of the model changes depending on if it is in training or evaluation mode.
51
+
52
+ During training, the model expects both the input tensors and targets (list of dictionary),
53
+ containing:
54
+ - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
55
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
56
+ - labels (Int64Tensor[N]): the class label for each ground-truth box
57
+
58
+ The model returns a Dict[Tensor] during training, containing the classification and regression
59
+ losses for both the RPN and the R-CNN.
60
+
61
+ During inference, the model requires only the input tensors, and returns the post-processed
62
+ predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
63
+ follows:
64
+ - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
65
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
66
+ - labels (Int64Tensor[N]): the predicted labels for each image
67
+ - scores (Tensor[N]): the scores or each prediction
68
+
69
+ Args:
70
+ backbone (nn.Module): the network used to compute the features for the model.
71
+ It should contain an out_channels attribute, which indicates the number of output
72
+ channels that each feature map has (and it should be the same for all feature maps).
73
+ The backbone should return a single Tensor or and OrderedDict[Tensor].
74
+ num_classes (int): number of output classes of the model (including the background).
75
+ If box_predictor is specified, num_classes should be None.
76
+ min_size (int): Images are rescaled before feeding them to the backbone:
77
+ we attempt to preserve the aspect ratio and scale the shorter edge
78
+ to ``min_size``. If the resulting longer edge exceeds ``max_size``,
79
+ then downscale so that the longer edge does not exceed ``max_size``.
80
+ This may result in the shorter edge beeing lower than ``min_size``.
81
+ max_size (int): See ``min_size``.
82
+ image_mean (Tuple[float, float, float]): mean values used for input normalization.
83
+ They are generally the mean values of the dataset on which the backbone has been trained
84
+ on
85
+ image_std (Tuple[float, float, float]): std values used for input normalization.
86
+ They are generally the std values of the dataset on which the backbone has been trained on
87
+ rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
88
+ maps.
89
+ rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
90
+ rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
91
+ rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
92
+ rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
93
+ rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
94
+ rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
95
+ rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
96
+ considered as positive during training of the RPN.
97
+ rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
98
+ considered as negative during training of the RPN.
99
+ rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
100
+ for computing the loss
101
+ rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
102
+ of the RPN
103
+ rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh
104
+ box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
105
+ the locations indicated by the bounding boxes
106
+ box_head (nn.Module): module that takes the cropped feature maps as input
107
+ box_predictor (nn.Module): module that takes the output of box_head and returns the
108
+ classification logits and box regression deltas.
109
+ box_score_thresh (float): during inference, only return proposals with a classification score
110
+ greater than box_score_thresh
111
+ box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
112
+ box_detections_per_img (int): maximum number of detections per image, for all classes.
113
+ box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
114
+ considered as positive during training of the classification head
115
+ box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
116
+ considered as negative during training of the classification head
117
+ box_batch_size_per_image (int): number of proposals that are sampled during training of the
118
+ classification head
119
+ box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
120
+ of the classification head
121
+ bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
122
+ bounding boxes
123
+
124
+ Example::
125
+
126
+ >>> import torch
127
+ >>> import torchvision
128
+ >>> from torchvision.models.detection import FasterRCNN
129
+ >>> from torchvision.models.detection.rpn import AnchorGenerator
130
+ >>> # load a pre-trained model for classification and return
131
+ >>> # only the features
132
+ >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features
133
+ >>> # FasterRCNN needs to know the number of
134
+ >>> # output channels in a backbone. For mobilenet_v2, it's 1280,
135
+ >>> # so we need to add it here
136
+ >>> backbone.out_channels = 1280
137
+ >>>
138
+ >>> # let's make the RPN generate 5 x 3 anchors per spatial
139
+ >>> # location, with 5 different sizes and 3 different aspect
140
+ >>> # ratios. We have a Tuple[Tuple[int]] because each feature
141
+ >>> # map could potentially have different sizes and
142
+ >>> # aspect ratios
143
+ >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
144
+ >>> aspect_ratios=((0.5, 1.0, 2.0),))
145
+ >>>
146
+ >>> # let's define what are the feature maps that we will
147
+ >>> # use to perform the region of interest cropping, as well as
148
+ >>> # the size of the crop after rescaling.
149
+ >>> # if your backbone returns a Tensor, featmap_names is expected to
150
+ >>> # be ['0']. More generally, the backbone should return an
151
+ >>> # OrderedDict[Tensor], and in featmap_names you can choose which
152
+ >>> # feature maps to use.
153
+ >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
154
+ >>> output_size=7,
155
+ >>> sampling_ratio=2)
156
+ >>>
157
+ >>> # put the pieces together inside a FasterRCNN model
158
+ >>> model = FasterRCNN(backbone,
159
+ >>> num_classes=2,
160
+ >>> rpn_anchor_generator=anchor_generator,
161
+ >>> box_roi_pool=roi_pooler)
162
+ >>> model.eval()
163
+ >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
164
+ >>> predictions = model(x)
165
+ """
166
+
167
+ def __init__(
168
+ self,
169
+ backbone,
170
+ num_classes=None,
171
+ # transform parameters
172
+ min_size=800,
173
+ max_size=1333,
174
+ image_mean=None,
175
+ image_std=None,
176
+ # RPN parameters
177
+ rpn_anchor_generator=None,
178
+ rpn_head=None,
179
+ rpn_pre_nms_top_n_train=2000,
180
+ rpn_pre_nms_top_n_test=1000,
181
+ rpn_post_nms_top_n_train=2000,
182
+ rpn_post_nms_top_n_test=1000,
183
+ rpn_nms_thresh=0.7,
184
+ rpn_fg_iou_thresh=0.7,
185
+ rpn_bg_iou_thresh=0.3,
186
+ rpn_batch_size_per_image=256,
187
+ rpn_positive_fraction=0.5,
188
+ rpn_score_thresh=0.0,
189
+ # Box parameters
190
+ box_roi_pool=None,
191
+ box_head=None,
192
+ box_predictor=None,
193
+ box_score_thresh=0.05,
194
+ box_nms_thresh=0.5,
195
+ box_detections_per_img=100,
196
+ box_fg_iou_thresh=0.5,
197
+ box_bg_iou_thresh=0.5,
198
+ box_batch_size_per_image=512,
199
+ box_positive_fraction=0.25,
200
+ bbox_reg_weights=None,
201
+ **kwargs,
202
+ ):
203
+
204
+ if not hasattr(backbone, "out_channels"):
205
+ raise ValueError(
206
+ "backbone should contain an attribute out_channels "
207
+ "specifying the number of output channels (assumed to be the "
208
+ "same for all the levels)"
209
+ )
210
+
211
+ if not isinstance(rpn_anchor_generator, (AnchorGenerator, type(None))):
212
+ raise TypeError(
213
+ f"rpn_anchor_generator should be of type AnchorGenerator or None instead of {type(rpn_anchor_generator)}"
214
+ )
215
+ if not isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None))):
216
+ raise TypeError(
217
+ f"box_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(box_roi_pool)}"
218
+ )
219
+
220
+ if num_classes is not None:
221
+ if box_predictor is not None:
222
+ raise ValueError("num_classes should be None when box_predictor is specified")
223
+ else:
224
+ if box_predictor is None:
225
+ raise ValueError("num_classes should not be None when box_predictor is not specified")
226
+
227
+ out_channels = backbone.out_channels
228
+
229
+ if rpn_anchor_generator is None:
230
+ rpn_anchor_generator = _default_anchorgen()
231
+ if rpn_head is None:
232
+ rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0])
233
+
234
+ rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)
235
+ rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)
236
+
237
+ rpn = RegionProposalNetwork(
238
+ rpn_anchor_generator,
239
+ rpn_head,
240
+ rpn_fg_iou_thresh,
241
+ rpn_bg_iou_thresh,
242
+ rpn_batch_size_per_image,
243
+ rpn_positive_fraction,
244
+ rpn_pre_nms_top_n,
245
+ rpn_post_nms_top_n,
246
+ rpn_nms_thresh,
247
+ score_thresh=rpn_score_thresh,
248
+ )
249
+
250
+ if box_roi_pool is None:
251
+ box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=7, sampling_ratio=2)
252
+
253
+ if box_head is None:
254
+ resolution = box_roi_pool.output_size[0]
255
+ representation_size = 1024
256
+ box_head = TwoMLPHead(out_channels * resolution**2, representation_size)
257
+
258
+ if box_predictor is None:
259
+ representation_size = 1024
260
+ box_predictor = FastRCNNPredictor(representation_size, num_classes)
261
+
262
+ roi_heads = RoIHeads(
263
+ # Box
264
+ box_roi_pool,
265
+ box_head,
266
+ box_predictor,
267
+ box_fg_iou_thresh,
268
+ box_bg_iou_thresh,
269
+ box_batch_size_per_image,
270
+ box_positive_fraction,
271
+ bbox_reg_weights,
272
+ box_score_thresh,
273
+ box_nms_thresh,
274
+ box_detections_per_img,
275
+ )
276
+
277
+ if image_mean is None:
278
+ image_mean = [0.485, 0.456, 0.406]
279
+ if image_std is None:
280
+ image_std = [0.229, 0.224, 0.225]
281
+ transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs)
282
+
283
+ super().__init__(backbone, rpn, roi_heads, transform)
284
+
285
+
286
+ class TwoMLPHead(nn.Module):
287
+ """
288
+ Standard heads for FPN-based models
289
+
290
+ Args:
291
+ in_channels (int): number of input channels
292
+ representation_size (int): size of the intermediate representation
293
+ """
294
+
295
+ def __init__(self, in_channels, representation_size):
296
+ super().__init__()
297
+
298
+ self.fc6 = nn.Linear(in_channels, representation_size)
299
+ self.fc7 = nn.Linear(representation_size, representation_size)
300
+
301
+ def forward(self, x):
302
+ x = x.flatten(start_dim=1)
303
+
304
+ x = F.relu(self.fc6(x))
305
+ x = F.relu(self.fc7(x))
306
+
307
+ return x
308
+
309
+
310
+ class FastRCNNConvFCHead(nn.Sequential):
311
+ def __init__(
312
+ self,
313
+ input_size: Tuple[int, int, int],
314
+ conv_layers: List[int],
315
+ fc_layers: List[int],
316
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
317
+ ):
318
+ """
319
+ Args:
320
+ input_size (Tuple[int, int, int]): the input size in CHW format.
321
+ conv_layers (list): feature dimensions of each Convolution layer
322
+ fc_layers (list): feature dimensions of each FCN layer
323
+ norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
324
+ """
325
+ in_channels, in_height, in_width = input_size
326
+
327
+ blocks = []
328
+ previous_channels = in_channels
329
+ for current_channels in conv_layers:
330
+ blocks.append(misc_nn_ops.Conv2dNormActivation(previous_channels, current_channels, norm_layer=norm_layer))
331
+ previous_channels = current_channels
332
+ blocks.append(nn.Flatten())
333
+ previous_channels = previous_channels * in_height * in_width
334
+ for current_channels in fc_layers:
335
+ blocks.append(nn.Linear(previous_channels, current_channels))
336
+ blocks.append(nn.ReLU(inplace=True))
337
+ previous_channels = current_channels
338
+
339
+ super().__init__(*blocks)
340
+ for layer in self.modules():
341
+ if isinstance(layer, nn.Conv2d):
342
+ nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu")
343
+ if layer.bias is not None:
344
+ nn.init.zeros_(layer.bias)
345
+
346
+
347
+ class FastRCNNPredictor(nn.Module):
348
+ """
349
+ Standard classification + bounding box regression layers
350
+ for Fast R-CNN.
351
+
352
+ Args:
353
+ in_channels (int): number of input channels
354
+ num_classes (int): number of output classes (including background)
355
+ """
356
+
357
+ def __init__(self, in_channels, num_classes):
358
+ super().__init__()
359
+ self.cls_score = nn.Linear(in_channels, num_classes)
360
+ self.bbox_pred = nn.Linear(in_channels, num_classes * 4)
361
+
362
+ def forward(self, x):
363
+ if x.dim() == 4:
364
+ torch._assert(
365
+ list(x.shape[2:]) == [1, 1],
366
+ f"x has the wrong shape, expecting the last two dimensions to be [1,1] instead of {list(x.shape[2:])}",
367
+ )
368
+ x = x.flatten(start_dim=1)
369
+ scores = self.cls_score(x)
370
+ bbox_deltas = self.bbox_pred(x)
371
+
372
+ return scores, bbox_deltas
373
+
374
+
375
+ _COMMON_META = {
376
+ "categories": _COCO_CATEGORIES,
377
+ "min_size": (1, 1),
378
+ }
379
+
380
+
381
+ class FasterRCNN_ResNet50_FPN_Weights(WeightsEnum):
382
+ COCO_V1 = Weights(
383
+ url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth",
384
+ transforms=ObjectDetection,
385
+ meta={
386
+ **_COMMON_META,
387
+ "num_params": 41755286,
388
+ "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-resnet-50-fpn",
389
+ "_metrics": {
390
+ "COCO-val2017": {
391
+ "box_map": 37.0,
392
+ }
393
+ },
394
+ "_ops": 134.38,
395
+ "_file_size": 159.743,
396
+ "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
397
+ },
398
+ )
399
+ DEFAULT = COCO_V1
400
+
401
+
402
+ class FasterRCNN_ResNet50_FPN_V2_Weights(WeightsEnum):
403
+ COCO_V1 = Weights(
404
+ url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_v2_coco-dd69338a.pth",
405
+ transforms=ObjectDetection,
406
+ meta={
407
+ **_COMMON_META,
408
+ "num_params": 43712278,
409
+ "recipe": "https://github.com/pytorch/vision/pull/5763",
410
+ "_metrics": {
411
+ "COCO-val2017": {
412
+ "box_map": 46.7,
413
+ }
414
+ },
415
+ "_ops": 280.371,
416
+ "_file_size": 167.104,
417
+ "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""",
418
+ },
419
+ )
420
+ DEFAULT = COCO_V1
421
+
422
+
423
+ class FasterRCNN_MobileNet_V3_Large_FPN_Weights(WeightsEnum):
424
+ COCO_V1 = Weights(
425
+ url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_fpn-fb6a3cc7.pth",
426
+ transforms=ObjectDetection,
427
+ meta={
428
+ **_COMMON_META,
429
+ "num_params": 19386354,
430
+ "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-fpn",
431
+ "_metrics": {
432
+ "COCO-val2017": {
433
+ "box_map": 32.8,
434
+ }
435
+ },
436
+ "_ops": 4.494,
437
+ "_file_size": 74.239,
438
+ "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
439
+ },
440
+ )
441
+ DEFAULT = COCO_V1
442
+
443
+
444
+ class FasterRCNN_MobileNet_V3_Large_320_FPN_Weights(WeightsEnum):
445
+ COCO_V1 = Weights(
446
+ url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth",
447
+ transforms=ObjectDetection,
448
+ meta={
449
+ **_COMMON_META,
450
+ "num_params": 19386354,
451
+ "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-320-fpn",
452
+ "_metrics": {
453
+ "COCO-val2017": {
454
+ "box_map": 22.8,
455
+ }
456
+ },
457
+ "_ops": 0.719,
458
+ "_file_size": 74.239,
459
+ "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
460
+ },
461
+ )
462
+ DEFAULT = COCO_V1
463
+
464
+
465
+ @register_model()
466
+ @handle_legacy_interface(
467
+ weights=("pretrained", FasterRCNN_ResNet50_FPN_Weights.COCO_V1),
468
+ weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
469
+ )
470
+ def fasterrcnn_resnet50_fpn(
471
+ *,
472
+ weights: Optional[FasterRCNN_ResNet50_FPN_Weights] = None,
473
+ progress: bool = True,
474
+ num_classes: Optional[int] = None,
475
+ weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
476
+ trainable_backbone_layers: Optional[int] = None,
477
+ **kwargs: Any,
478
+ ) -> FasterRCNN:
479
+ """
480
+ Faster R-CNN model with a ResNet-50-FPN backbone from the `Faster R-CNN: Towards Real-Time Object
481
+ Detection with Region Proposal Networks <https://arxiv.org/abs/1506.01497>`__
482
+ paper.
483
+
484
+ .. betastatus:: detection module
485
+
486
+ The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
487
+ image, and should be in ``0-1`` range. Different images can have different sizes.
488
+
489
+ The behavior of the model changes depending on if it is in training or evaluation mode.
490
+
491
+ During training, the model expects both the input tensors and a targets (list of dictionary),
492
+ containing:
493
+
494
+ - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
495
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
496
+ - labels (``Int64Tensor[N]``): the class label for each ground-truth box
497
+
498
+ The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
499
+ losses for both the RPN and the R-CNN.
500
+
501
+ During inference, the model requires only the input tensors, and returns the post-processed
502
+ predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
503
+ follows, where ``N`` is the number of detections:
504
+
505
+ - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
506
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
507
+ - labels (``Int64Tensor[N]``): the predicted labels for each detection
508
+ - scores (``Tensor[N]``): the scores of each detection
509
+
510
+ For more details on the output, you may refer to :ref:`instance_seg_output`.
511
+
512
+ Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
513
+
514
+ Example::
515
+
516
+ >>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT)
517
+ >>> # For training
518
+ >>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4)
519
+ >>> boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4]
520
+ >>> labels = torch.randint(1, 91, (4, 11))
521
+ >>> images = list(image for image in images)
522
+ >>> targets = []
523
+ >>> for i in range(len(images)):
524
+ >>> d = {}
525
+ >>> d['boxes'] = boxes[i]
526
+ >>> d['labels'] = labels[i]
527
+ >>> targets.append(d)
528
+ >>> output = model(images, targets)
529
+ >>> # For inference
530
+ >>> model.eval()
531
+ >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
532
+ >>> predictions = model(x)
533
+ >>>
534
+ >>> # optionally, if you want to export the model to ONNX:
535
+ >>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11)
536
+
537
+ Args:
538
+ weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights`, optional): The
539
+ pretrained weights to use. See
540
+ :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights` below for
541
+ more details, and possible values. By default, no pre-trained
542
+ weights are used.
543
+ progress (bool, optional): If True, displays a progress bar of the
544
+ download to stderr. Default is True.
545
+ num_classes (int, optional): number of output classes of the model (including the background)
546
+ weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
547
+ pretrained weights for the backbone.
548
+ trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
549
+ final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
550
+ trainable. If ``None`` is passed (the default) this value is set to 3.
551
+ **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
552
+ base class. Please refer to the `source code
553
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
554
+ for more details about this class.
555
+
556
+ .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights
557
+ :members:
558
+ """
559
+ weights = FasterRCNN_ResNet50_FPN_Weights.verify(weights)
560
+ weights_backbone = ResNet50_Weights.verify(weights_backbone)
561
+
562
+ if weights is not None:
563
+ weights_backbone = None
564
+ num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
565
+ elif num_classes is None:
566
+ num_classes = 91
567
+
568
+ is_trained = weights is not None or weights_backbone is not None
569
+ trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
570
+ norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
571
+
572
+ backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
573
+ backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
574
+ model = FasterRCNN(backbone, num_classes=num_classes, **kwargs)
575
+
576
+ if weights is not None:
577
+ model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
578
+ if weights == FasterRCNN_ResNet50_FPN_Weights.COCO_V1:
579
+ overwrite_eps(model, 0.0)
580
+
581
+ return model
582
+
583
+
584
+ @register_model()
585
+ @handle_legacy_interface(
586
+ weights=("pretrained", FasterRCNN_ResNet50_FPN_V2_Weights.COCO_V1),
587
+ weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
588
+ )
589
+ def fasterrcnn_resnet50_fpn_v2(
590
+ *,
591
+ weights: Optional[FasterRCNN_ResNet50_FPN_V2_Weights] = None,
592
+ progress: bool = True,
593
+ num_classes: Optional[int] = None,
594
+ weights_backbone: Optional[ResNet50_Weights] = None,
595
+ trainable_backbone_layers: Optional[int] = None,
596
+ **kwargs: Any,
597
+ ) -> FasterRCNN:
598
+ """
599
+ Constructs an improved Faster R-CNN model with a ResNet-50-FPN backbone from `Benchmarking Detection
600
+ Transfer Learning with Vision Transformers <https://arxiv.org/abs/2111.11429>`__ paper.
601
+
602
+ .. betastatus:: detection module
603
+
604
+ It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
605
+ :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
606
+ details.
607
+
608
+ Args:
609
+ weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights`, optional): The
610
+ pretrained weights to use. See
611
+ :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights` below for
612
+ more details, and possible values. By default, no pre-trained
613
+ weights are used.
614
+ progress (bool, optional): If True, displays a progress bar of the
615
+ download to stderr. Default is True.
616
+ num_classes (int, optional): number of output classes of the model (including the background)
617
+ weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
618
+ pretrained weights for the backbone.
619
+ trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
620
+ final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
621
+ trainable. If ``None`` is passed (the default) this value is set to 3.
622
+ **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
623
+ base class. Please refer to the `source code
624
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
625
+ for more details about this class.
626
+
627
+ .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights
628
+ :members:
629
+ """
630
+ weights = FasterRCNN_ResNet50_FPN_V2_Weights.verify(weights)
631
+ weights_backbone = ResNet50_Weights.verify(weights_backbone)
632
+
633
+ if weights is not None:
634
+ weights_backbone = None
635
+ num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
636
+ elif num_classes is None:
637
+ num_classes = 91
638
+
639
+ is_trained = weights is not None or weights_backbone is not None
640
+ trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
641
+
642
+ backbone = resnet50(weights=weights_backbone, progress=progress)
643
+ backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d)
644
+ rpn_anchor_generator = _default_anchorgen()
645
+ rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2)
646
+ box_head = FastRCNNConvFCHead(
647
+ (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d
648
+ )
649
+ model = FasterRCNN(
650
+ backbone,
651
+ num_classes=num_classes,
652
+ rpn_anchor_generator=rpn_anchor_generator,
653
+ rpn_head=rpn_head,
654
+ box_head=box_head,
655
+ **kwargs,
656
+ )
657
+
658
+ if weights is not None:
659
+ model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
660
+
661
+ return model
662
+
663
+
664
+ def _fasterrcnn_mobilenet_v3_large_fpn(
665
+ *,
666
+ weights: Optional[Union[FasterRCNN_MobileNet_V3_Large_FPN_Weights, FasterRCNN_MobileNet_V3_Large_320_FPN_Weights]],
667
+ progress: bool,
668
+ num_classes: Optional[int],
669
+ weights_backbone: Optional[MobileNet_V3_Large_Weights],
670
+ trainable_backbone_layers: Optional[int],
671
+ **kwargs: Any,
672
+ ) -> FasterRCNN:
673
+ if weights is not None:
674
+ weights_backbone = None
675
+ num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
676
+ elif num_classes is None:
677
+ num_classes = 91
678
+
679
+ is_trained = weights is not None or weights_backbone is not None
680
+ trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 6, 3)
681
+ norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
682
+
683
+ backbone = mobilenet_v3_large(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
684
+ backbone = _mobilenet_extractor(backbone, True, trainable_backbone_layers)
685
+ anchor_sizes = (
686
+ (
687
+ 32,
688
+ 64,
689
+ 128,
690
+ 256,
691
+ 512,
692
+ ),
693
+ ) * 3
694
+ aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
695
+ model = FasterRCNN(
696
+ backbone, num_classes, rpn_anchor_generator=AnchorGenerator(anchor_sizes, aspect_ratios), **kwargs
697
+ )
698
+
699
+ if weights is not None:
700
+ model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
701
+
702
+ return model
703
+
704
+
705
+ @register_model()
706
+ @handle_legacy_interface(
707
+ weights=("pretrained", FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.COCO_V1),
708
+ weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
709
+ )
710
+ def fasterrcnn_mobilenet_v3_large_320_fpn(
711
+ *,
712
+ weights: Optional[FasterRCNN_MobileNet_V3_Large_320_FPN_Weights] = None,
713
+ progress: bool = True,
714
+ num_classes: Optional[int] = None,
715
+ weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
716
+ trainable_backbone_layers: Optional[int] = None,
717
+ **kwargs: Any,
718
+ ) -> FasterRCNN:
719
+ """
720
+ Low resolution Faster R-CNN model with a MobileNetV3-Large backbone tuned for mobile use cases.
721
+
722
+ .. betastatus:: detection module
723
+
724
+ It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
725
+ :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
726
+ details.
727
+
728
+ Example::
729
+
730
+ >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(weights=FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.DEFAULT)
731
+ >>> model.eval()
732
+ >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
733
+ >>> predictions = model(x)
734
+
735
+ Args:
736
+ weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights`, optional): The
737
+ pretrained weights to use. See
738
+ :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights` below for
739
+ more details, and possible values. By default, no pre-trained
740
+ weights are used.
741
+ progress (bool, optional): If True, displays a progress bar of the
742
+ download to stderr. Default is True.
743
+ num_classes (int, optional): number of output classes of the model (including the background)
744
+ weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
745
+ pretrained weights for the backbone.
746
+ trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
747
+ final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are
748
+ trainable. If ``None`` is passed (the default) this value is set to 3.
749
+ **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
750
+ base class. Please refer to the `source code
751
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
752
+ for more details about this class.
753
+
754
+ .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights
755
+ :members:
756
+ """
757
+ weights = FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.verify(weights)
758
+ weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
759
+
760
+ defaults = {
761
+ "min_size": 320,
762
+ "max_size": 640,
763
+ "rpn_pre_nms_top_n_test": 150,
764
+ "rpn_post_nms_top_n_test": 150,
765
+ "rpn_score_thresh": 0.05,
766
+ }
767
+
768
+ kwargs = {**defaults, **kwargs}
769
+ return _fasterrcnn_mobilenet_v3_large_fpn(
770
+ weights=weights,
771
+ progress=progress,
772
+ num_classes=num_classes,
773
+ weights_backbone=weights_backbone,
774
+ trainable_backbone_layers=trainable_backbone_layers,
775
+ **kwargs,
776
+ )
777
+
778
+
779
+ @register_model()
780
+ @handle_legacy_interface(
781
+ weights=("pretrained", FasterRCNN_MobileNet_V3_Large_FPN_Weights.COCO_V1),
782
+ weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
783
+ )
784
+ def fasterrcnn_mobilenet_v3_large_fpn(
785
+ *,
786
+ weights: Optional[FasterRCNN_MobileNet_V3_Large_FPN_Weights] = None,
787
+ progress: bool = True,
788
+ num_classes: Optional[int] = None,
789
+ weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
790
+ trainable_backbone_layers: Optional[int] = None,
791
+ **kwargs: Any,
792
+ ) -> FasterRCNN:
793
+ """
794
+ Constructs a high resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone.
795
+
796
+ .. betastatus:: detection module
797
+
798
+ It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
799
+ :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
800
+ details.
801
+
802
+ Example::
803
+
804
+ >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(weights=FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT)
805
+ >>> model.eval()
806
+ >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
807
+ >>> predictions = model(x)
808
+
809
+ Args:
810
+ weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights`, optional): The
811
+ pretrained weights to use. See
812
+ :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights` below for
813
+ more details, and possible values. By default, no pre-trained
814
+ weights are used.
815
+ progress (bool, optional): If True, displays a progress bar of the
816
+ download to stderr. Default is True.
817
+ num_classes (int, optional): number of output classes of the model (including the background)
818
+ weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
819
+ pretrained weights for the backbone.
820
+ trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
821
+ final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are
822
+ trainable. If ``None`` is passed (the default) this value is set to 3.
823
+ **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
824
+ base class. Please refer to the `source code
825
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
826
+ for more details about this class.
827
+
828
+ .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights
829
+ :members:
830
+ """
831
+ weights = FasterRCNN_MobileNet_V3_Large_FPN_Weights.verify(weights)
832
+ weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
833
+
834
+ defaults = {
835
+ "rpn_score_thresh": 0.05,
836
+ }
837
+
838
+ kwargs = {**defaults, **kwargs}
839
+ return _fasterrcnn_mobilenet_v3_large_fpn(
840
+ weights=weights,
841
+ progress=progress,
842
+ num_classes=num_classes,
843
+ weights_backbone=weights_backbone,
844
+ trainable_backbone_layers=trainable_backbone_layers,
845
+ **kwargs,
846
+ )
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/fcos.py ADDED
@@ -0,0 +1,775 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ from collections import OrderedDict
4
+ from functools import partial
5
+ from typing import Any, Callable, Dict, List, Optional, Tuple
6
+
7
+ import torch
8
+ from torch import nn, Tensor
9
+
10
+ from ...ops import boxes as box_ops, generalized_box_iou_loss, misc as misc_nn_ops, sigmoid_focal_loss
11
+ from ...ops.feature_pyramid_network import LastLevelP6P7
12
+ from ...transforms._presets import ObjectDetection
13
+ from ...utils import _log_api_usage_once
14
+ from .._api import register_model, Weights, WeightsEnum
15
+ from .._meta import _COCO_CATEGORIES
16
+ from .._utils import _ovewrite_value_param, handle_legacy_interface
17
+ from ..resnet import resnet50, ResNet50_Weights
18
+ from . import _utils as det_utils
19
+ from .anchor_utils import AnchorGenerator
20
+ from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
21
+ from .transform import GeneralizedRCNNTransform
22
+
23
+
24
+ __all__ = [
25
+ "FCOS",
26
+ "FCOS_ResNet50_FPN_Weights",
27
+ "fcos_resnet50_fpn",
28
+ ]
29
+
30
+
31
+ class FCOSHead(nn.Module):
32
+ """
33
+ A regression and classification head for use in FCOS.
34
+
35
+ Args:
36
+ in_channels (int): number of channels of the input feature
37
+ num_anchors (int): number of anchors to be predicted
38
+ num_classes (int): number of classes to be predicted
39
+ num_convs (Optional[int]): number of conv layer of head. Default: 4.
40
+ """
41
+
42
+ __annotations__ = {
43
+ "box_coder": det_utils.BoxLinearCoder,
44
+ }
45
+
46
+ def __init__(self, in_channels: int, num_anchors: int, num_classes: int, num_convs: Optional[int] = 4) -> None:
47
+ super().__init__()
48
+ self.box_coder = det_utils.BoxLinearCoder(normalize_by_size=True)
49
+ self.classification_head = FCOSClassificationHead(in_channels, num_anchors, num_classes, num_convs)
50
+ self.regression_head = FCOSRegressionHead(in_channels, num_anchors, num_convs)
51
+
52
+ def compute_loss(
53
+ self,
54
+ targets: List[Dict[str, Tensor]],
55
+ head_outputs: Dict[str, Tensor],
56
+ anchors: List[Tensor],
57
+ matched_idxs: List[Tensor],
58
+ ) -> Dict[str, Tensor]:
59
+
60
+ cls_logits = head_outputs["cls_logits"] # [N, HWA, C]
61
+ bbox_regression = head_outputs["bbox_regression"] # [N, HWA, 4]
62
+ bbox_ctrness = head_outputs["bbox_ctrness"] # [N, HWA, 1]
63
+
64
+ all_gt_classes_targets = []
65
+ all_gt_boxes_targets = []
66
+ for targets_per_image, matched_idxs_per_image in zip(targets, matched_idxs):
67
+ if len(targets_per_image["labels"]) == 0:
68
+ gt_classes_targets = targets_per_image["labels"].new_zeros((len(matched_idxs_per_image),))
69
+ gt_boxes_targets = targets_per_image["boxes"].new_zeros((len(matched_idxs_per_image), 4))
70
+ else:
71
+ gt_classes_targets = targets_per_image["labels"][matched_idxs_per_image.clip(min=0)]
72
+ gt_boxes_targets = targets_per_image["boxes"][matched_idxs_per_image.clip(min=0)]
73
+ gt_classes_targets[matched_idxs_per_image < 0] = -1 # background
74
+ all_gt_classes_targets.append(gt_classes_targets)
75
+ all_gt_boxes_targets.append(gt_boxes_targets)
76
+
77
+ # List[Tensor] to Tensor conversion of `all_gt_boxes_target`, `all_gt_classes_targets` and `anchors`
78
+ all_gt_boxes_targets, all_gt_classes_targets, anchors = (
79
+ torch.stack(all_gt_boxes_targets),
80
+ torch.stack(all_gt_classes_targets),
81
+ torch.stack(anchors),
82
+ )
83
+
84
+ # compute foregroud
85
+ foregroud_mask = all_gt_classes_targets >= 0
86
+ num_foreground = foregroud_mask.sum().item()
87
+
88
+ # classification loss
89
+ gt_classes_targets = torch.zeros_like(cls_logits)
90
+ gt_classes_targets[foregroud_mask, all_gt_classes_targets[foregroud_mask]] = 1.0
91
+ loss_cls = sigmoid_focal_loss(cls_logits, gt_classes_targets, reduction="sum")
92
+
93
+ # amp issue: pred_boxes need to convert float
94
+ pred_boxes = self.box_coder.decode(bbox_regression, anchors)
95
+
96
+ # regression loss: GIoU loss
97
+ loss_bbox_reg = generalized_box_iou_loss(
98
+ pred_boxes[foregroud_mask],
99
+ all_gt_boxes_targets[foregroud_mask],
100
+ reduction="sum",
101
+ )
102
+
103
+ # ctrness loss
104
+
105
+ bbox_reg_targets = self.box_coder.encode(anchors, all_gt_boxes_targets)
106
+
107
+ if len(bbox_reg_targets) == 0:
108
+ gt_ctrness_targets = bbox_reg_targets.new_zeros(bbox_reg_targets.size()[:-1])
109
+ else:
110
+ left_right = bbox_reg_targets[:, :, [0, 2]]
111
+ top_bottom = bbox_reg_targets[:, :, [1, 3]]
112
+ gt_ctrness_targets = torch.sqrt(
113
+ (left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0])
114
+ * (top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0])
115
+ )
116
+ pred_centerness = bbox_ctrness.squeeze(dim=2)
117
+ loss_bbox_ctrness = nn.functional.binary_cross_entropy_with_logits(
118
+ pred_centerness[foregroud_mask], gt_ctrness_targets[foregroud_mask], reduction="sum"
119
+ )
120
+
121
+ return {
122
+ "classification": loss_cls / max(1, num_foreground),
123
+ "bbox_regression": loss_bbox_reg / max(1, num_foreground),
124
+ "bbox_ctrness": loss_bbox_ctrness / max(1, num_foreground),
125
+ }
126
+
127
+ def forward(self, x: List[Tensor]) -> Dict[str, Tensor]:
128
+ cls_logits = self.classification_head(x)
129
+ bbox_regression, bbox_ctrness = self.regression_head(x)
130
+ return {
131
+ "cls_logits": cls_logits,
132
+ "bbox_regression": bbox_regression,
133
+ "bbox_ctrness": bbox_ctrness,
134
+ }
135
+
136
+
137
+ class FCOSClassificationHead(nn.Module):
138
+ """
139
+ A classification head for use in FCOS.
140
+
141
+ Args:
142
+ in_channels (int): number of channels of the input feature.
143
+ num_anchors (int): number of anchors to be predicted.
144
+ num_classes (int): number of classes to be predicted.
145
+ num_convs (Optional[int]): number of conv layer. Default: 4.
146
+ prior_probability (Optional[float]): probability of prior. Default: 0.01.
147
+ norm_layer: Module specifying the normalization layer to use.
148
+ """
149
+
150
+ def __init__(
151
+ self,
152
+ in_channels: int,
153
+ num_anchors: int,
154
+ num_classes: int,
155
+ num_convs: int = 4,
156
+ prior_probability: float = 0.01,
157
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
158
+ ) -> None:
159
+ super().__init__()
160
+
161
+ self.num_classes = num_classes
162
+ self.num_anchors = num_anchors
163
+
164
+ if norm_layer is None:
165
+ norm_layer = partial(nn.GroupNorm, 32)
166
+
167
+ conv = []
168
+ for _ in range(num_convs):
169
+ conv.append(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1))
170
+ conv.append(norm_layer(in_channels))
171
+ conv.append(nn.ReLU())
172
+ self.conv = nn.Sequential(*conv)
173
+
174
+ for layer in self.conv.children():
175
+ if isinstance(layer, nn.Conv2d):
176
+ torch.nn.init.normal_(layer.weight, std=0.01)
177
+ torch.nn.init.constant_(layer.bias, 0)
178
+
179
+ self.cls_logits = nn.Conv2d(in_channels, num_anchors * num_classes, kernel_size=3, stride=1, padding=1)
180
+ torch.nn.init.normal_(self.cls_logits.weight, std=0.01)
181
+ torch.nn.init.constant_(self.cls_logits.bias, -math.log((1 - prior_probability) / prior_probability))
182
+
183
+ def forward(self, x: List[Tensor]) -> Tensor:
184
+ all_cls_logits = []
185
+
186
+ for features in x:
187
+ cls_logits = self.conv(features)
188
+ cls_logits = self.cls_logits(cls_logits)
189
+
190
+ # Permute classification output from (N, A * K, H, W) to (N, HWA, K).
191
+ N, _, H, W = cls_logits.shape
192
+ cls_logits = cls_logits.view(N, -1, self.num_classes, H, W)
193
+ cls_logits = cls_logits.permute(0, 3, 4, 1, 2)
194
+ cls_logits = cls_logits.reshape(N, -1, self.num_classes) # Size=(N, HWA, 4)
195
+
196
+ all_cls_logits.append(cls_logits)
197
+
198
+ return torch.cat(all_cls_logits, dim=1)
199
+
200
+
201
+ class FCOSRegressionHead(nn.Module):
202
+ """
203
+ A regression head for use in FCOS, which combines regression branch and center-ness branch.
204
+ This can obtain better performance.
205
+
206
+ Reference: `FCOS: A simple and strong anchor-free object detector <https://arxiv.org/abs/2006.09214>`_.
207
+
208
+ Args:
209
+ in_channels (int): number of channels of the input feature
210
+ num_anchors (int): number of anchors to be predicted
211
+ num_convs (Optional[int]): number of conv layer. Default: 4.
212
+ norm_layer: Module specifying the normalization layer to use.
213
+ """
214
+
215
+ def __init__(
216
+ self,
217
+ in_channels: int,
218
+ num_anchors: int,
219
+ num_convs: int = 4,
220
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
221
+ ):
222
+ super().__init__()
223
+
224
+ if norm_layer is None:
225
+ norm_layer = partial(nn.GroupNorm, 32)
226
+
227
+ conv = []
228
+ for _ in range(num_convs):
229
+ conv.append(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1))
230
+ conv.append(norm_layer(in_channels))
231
+ conv.append(nn.ReLU())
232
+ self.conv = nn.Sequential(*conv)
233
+
234
+ self.bbox_reg = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=3, stride=1, padding=1)
235
+ self.bbox_ctrness = nn.Conv2d(in_channels, num_anchors * 1, kernel_size=3, stride=1, padding=1)
236
+ for layer in [self.bbox_reg, self.bbox_ctrness]:
237
+ torch.nn.init.normal_(layer.weight, std=0.01)
238
+ torch.nn.init.zeros_(layer.bias)
239
+
240
+ for layer in self.conv.children():
241
+ if isinstance(layer, nn.Conv2d):
242
+ torch.nn.init.normal_(layer.weight, std=0.01)
243
+ torch.nn.init.zeros_(layer.bias)
244
+
245
+ def forward(self, x: List[Tensor]) -> Tuple[Tensor, Tensor]:
246
+ all_bbox_regression = []
247
+ all_bbox_ctrness = []
248
+
249
+ for features in x:
250
+ bbox_feature = self.conv(features)
251
+ bbox_regression = nn.functional.relu(self.bbox_reg(bbox_feature))
252
+ bbox_ctrness = self.bbox_ctrness(bbox_feature)
253
+
254
+ # permute bbox regression output from (N, 4 * A, H, W) to (N, HWA, 4).
255
+ N, _, H, W = bbox_regression.shape
256
+ bbox_regression = bbox_regression.view(N, -1, 4, H, W)
257
+ bbox_regression = bbox_regression.permute(0, 3, 4, 1, 2)
258
+ bbox_regression = bbox_regression.reshape(N, -1, 4) # Size=(N, HWA, 4)
259
+ all_bbox_regression.append(bbox_regression)
260
+
261
+ # permute bbox ctrness output from (N, 1 * A, H, W) to (N, HWA, 1).
262
+ bbox_ctrness = bbox_ctrness.view(N, -1, 1, H, W)
263
+ bbox_ctrness = bbox_ctrness.permute(0, 3, 4, 1, 2)
264
+ bbox_ctrness = bbox_ctrness.reshape(N, -1, 1)
265
+ all_bbox_ctrness.append(bbox_ctrness)
266
+
267
+ return torch.cat(all_bbox_regression, dim=1), torch.cat(all_bbox_ctrness, dim=1)
268
+
269
+
270
+ class FCOS(nn.Module):
271
+ """
272
+ Implements FCOS.
273
+
274
+ The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
275
+ image, and should be in 0-1 range. Different images can have different sizes.
276
+
277
+ The behavior of the model changes depending on if it is in training or evaluation mode.
278
+
279
+ During training, the model expects both the input tensors and targets (list of dictionary),
280
+ containing:
281
+ - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
282
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
283
+ - labels (Int64Tensor[N]): the class label for each ground-truth box
284
+
285
+ The model returns a Dict[Tensor] during training, containing the classification, regression
286
+ and centerness losses.
287
+
288
+ During inference, the model requires only the input tensors, and returns the post-processed
289
+ predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
290
+ follows:
291
+ - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
292
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
293
+ - labels (Int64Tensor[N]): the predicted labels for each image
294
+ - scores (Tensor[N]): the scores for each prediction
295
+
296
+ Args:
297
+ backbone (nn.Module): the network used to compute the features for the model.
298
+ It should contain an out_channels attribute, which indicates the number of output
299
+ channels that each feature map has (and it should be the same for all feature maps).
300
+ The backbone should return a single Tensor or an OrderedDict[Tensor].
301
+ num_classes (int): number of output classes of the model (including the background).
302
+ min_size (int): Images are rescaled before feeding them to the backbone:
303
+ we attempt to preserve the aspect ratio and scale the shorter edge
304
+ to ``min_size``. If the resulting longer edge exceeds ``max_size``,
305
+ then downscale so that the longer edge does not exceed ``max_size``.
306
+ This may result in the shorter edge beeing lower than ``min_size``.
307
+ max_size (int): See ``min_size``.
308
+ image_mean (Tuple[float, float, float]): mean values used for input normalization.
309
+ They are generally the mean values of the dataset on which the backbone has been trained
310
+ on
311
+ image_std (Tuple[float, float, float]): std values used for input normalization.
312
+ They are generally the std values of the dataset on which the backbone has been trained on
313
+ anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
314
+ maps. For FCOS, only set one anchor for per position of each level, the width and height equal to
315
+ the stride of feature map, and set aspect ratio = 1.0, so the center of anchor is equivalent to the point
316
+ in FCOS paper.
317
+ head (nn.Module): Module run on top of the feature pyramid.
318
+ Defaults to a module containing a classification and regression module.
319
+ center_sampling_radius (int): radius of the "center" of a groundtruth box,
320
+ within which all anchor points are labeled positive.
321
+ score_thresh (float): Score threshold used for postprocessing the detections.
322
+ nms_thresh (float): NMS threshold used for postprocessing the detections.
323
+ detections_per_img (int): Number of best detections to keep after NMS.
324
+ topk_candidates (int): Number of best detections to keep before NMS.
325
+
326
+ Example:
327
+
328
+ >>> import torch
329
+ >>> import torchvision
330
+ >>> from torchvision.models.detection import FCOS
331
+ >>> from torchvision.models.detection.anchor_utils import AnchorGenerator
332
+ >>> # load a pre-trained model for classification and return
333
+ >>> # only the features
334
+ >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features
335
+ >>> # FCOS needs to know the number of
336
+ >>> # output channels in a backbone. For mobilenet_v2, it's 1280,
337
+ >>> # so we need to add it here
338
+ >>> backbone.out_channels = 1280
339
+ >>>
340
+ >>> # let's make the network generate 5 x 3 anchors per spatial
341
+ >>> # location, with 5 different sizes and 3 different aspect
342
+ >>> # ratios. We have a Tuple[Tuple[int]] because each feature
343
+ >>> # map could potentially have different sizes and
344
+ >>> # aspect ratios
345
+ >>> anchor_generator = AnchorGenerator(
346
+ >>> sizes=((8,), (16,), (32,), (64,), (128,)),
347
+ >>> aspect_ratios=((1.0,),)
348
+ >>> )
349
+ >>>
350
+ >>> # put the pieces together inside a FCOS model
351
+ >>> model = FCOS(
352
+ >>> backbone,
353
+ >>> num_classes=80,
354
+ >>> anchor_generator=anchor_generator,
355
+ >>> )
356
+ >>> model.eval()
357
+ >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
358
+ >>> predictions = model(x)
359
+ """
360
+
361
+ __annotations__ = {
362
+ "box_coder": det_utils.BoxLinearCoder,
363
+ }
364
+
365
+ def __init__(
366
+ self,
367
+ backbone: nn.Module,
368
+ num_classes: int,
369
+ # transform parameters
370
+ min_size: int = 800,
371
+ max_size: int = 1333,
372
+ image_mean: Optional[List[float]] = None,
373
+ image_std: Optional[List[float]] = None,
374
+ # Anchor parameters
375
+ anchor_generator: Optional[AnchorGenerator] = None,
376
+ head: Optional[nn.Module] = None,
377
+ center_sampling_radius: float = 1.5,
378
+ score_thresh: float = 0.2,
379
+ nms_thresh: float = 0.6,
380
+ detections_per_img: int = 100,
381
+ topk_candidates: int = 1000,
382
+ **kwargs,
383
+ ):
384
+ super().__init__()
385
+ _log_api_usage_once(self)
386
+
387
+ if not hasattr(backbone, "out_channels"):
388
+ raise ValueError(
389
+ "backbone should contain an attribute out_channels "
390
+ "specifying the number of output channels (assumed to be the "
391
+ "same for all the levels)"
392
+ )
393
+ self.backbone = backbone
394
+
395
+ if not isinstance(anchor_generator, (AnchorGenerator, type(None))):
396
+ raise TypeError(
397
+ f"anchor_generator should be of type AnchorGenerator or None, instead got {type(anchor_generator)}"
398
+ )
399
+
400
+ if anchor_generator is None:
401
+ anchor_sizes = ((8,), (16,), (32,), (64,), (128,)) # equal to strides of multi-level feature map
402
+ aspect_ratios = ((1.0,),) * len(anchor_sizes) # set only one anchor
403
+ anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios)
404
+ self.anchor_generator = anchor_generator
405
+ if self.anchor_generator.num_anchors_per_location()[0] != 1:
406
+ raise ValueError(
407
+ f"anchor_generator.num_anchors_per_location()[0] should be 1 instead of {anchor_generator.num_anchors_per_location()[0]}"
408
+ )
409
+
410
+ if head is None:
411
+ head = FCOSHead(backbone.out_channels, anchor_generator.num_anchors_per_location()[0], num_classes)
412
+ self.head = head
413
+
414
+ self.box_coder = det_utils.BoxLinearCoder(normalize_by_size=True)
415
+
416
+ if image_mean is None:
417
+ image_mean = [0.485, 0.456, 0.406]
418
+ if image_std is None:
419
+ image_std = [0.229, 0.224, 0.225]
420
+ self.transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs)
421
+
422
+ self.center_sampling_radius = center_sampling_radius
423
+ self.score_thresh = score_thresh
424
+ self.nms_thresh = nms_thresh
425
+ self.detections_per_img = detections_per_img
426
+ self.topk_candidates = topk_candidates
427
+
428
+ # used only on torchscript mode
429
+ self._has_warned = False
430
+
431
+ @torch.jit.unused
432
+ def eager_outputs(
433
+ self, losses: Dict[str, Tensor], detections: List[Dict[str, Tensor]]
434
+ ) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]:
435
+ if self.training:
436
+ return losses
437
+
438
+ return detections
439
+
440
+ def compute_loss(
441
+ self,
442
+ targets: List[Dict[str, Tensor]],
443
+ head_outputs: Dict[str, Tensor],
444
+ anchors: List[Tensor],
445
+ num_anchors_per_level: List[int],
446
+ ) -> Dict[str, Tensor]:
447
+ matched_idxs = []
448
+ for anchors_per_image, targets_per_image in zip(anchors, targets):
449
+ if targets_per_image["boxes"].numel() == 0:
450
+ matched_idxs.append(
451
+ torch.full((anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device)
452
+ )
453
+ continue
454
+
455
+ gt_boxes = targets_per_image["boxes"]
456
+ gt_centers = (gt_boxes[:, :2] + gt_boxes[:, 2:]) / 2 # Nx2
457
+ anchor_centers = (anchors_per_image[:, :2] + anchors_per_image[:, 2:]) / 2 # N
458
+ anchor_sizes = anchors_per_image[:, 2] - anchors_per_image[:, 0]
459
+ # center sampling: anchor point must be close enough to gt center.
460
+ pairwise_match = (anchor_centers[:, None, :] - gt_centers[None, :, :]).abs_().max(
461
+ dim=2
462
+ ).values < self.center_sampling_radius * anchor_sizes[:, None]
463
+ # compute pairwise distance between N points and M boxes
464
+ x, y = anchor_centers.unsqueeze(dim=2).unbind(dim=1) # (N, 1)
465
+ x0, y0, x1, y1 = gt_boxes.unsqueeze(dim=0).unbind(dim=2) # (1, M)
466
+ pairwise_dist = torch.stack([x - x0, y - y0, x1 - x, y1 - y], dim=2) # (N, M)
467
+
468
+ # anchor point must be inside gt
469
+ pairwise_match &= pairwise_dist.min(dim=2).values > 0
470
+
471
+ # each anchor is only responsible for certain scale range.
472
+ lower_bound = anchor_sizes * 4
473
+ lower_bound[: num_anchors_per_level[0]] = 0
474
+ upper_bound = anchor_sizes * 8
475
+ upper_bound[-num_anchors_per_level[-1] :] = float("inf")
476
+ pairwise_dist = pairwise_dist.max(dim=2).values
477
+ pairwise_match &= (pairwise_dist > lower_bound[:, None]) & (pairwise_dist < upper_bound[:, None])
478
+
479
+ # match the GT box with minimum area, if there are multiple GT matches
480
+ gt_areas = (gt_boxes[:, 2] - gt_boxes[:, 0]) * (gt_boxes[:, 3] - gt_boxes[:, 1]) # N
481
+ pairwise_match = pairwise_match.to(torch.float32) * (1e8 - gt_areas[None, :])
482
+ min_values, matched_idx = pairwise_match.max(dim=1) # R, per-anchor match
483
+ matched_idx[min_values < 1e-5] = -1 # unmatched anchors are assigned -1
484
+
485
+ matched_idxs.append(matched_idx)
486
+
487
+ return self.head.compute_loss(targets, head_outputs, anchors, matched_idxs)
488
+
489
+ def postprocess_detections(
490
+ self, head_outputs: Dict[str, List[Tensor]], anchors: List[List[Tensor]], image_shapes: List[Tuple[int, int]]
491
+ ) -> List[Dict[str, Tensor]]:
492
+ class_logits = head_outputs["cls_logits"]
493
+ box_regression = head_outputs["bbox_regression"]
494
+ box_ctrness = head_outputs["bbox_ctrness"]
495
+
496
+ num_images = len(image_shapes)
497
+
498
+ detections: List[Dict[str, Tensor]] = []
499
+
500
+ for index in range(num_images):
501
+ box_regression_per_image = [br[index] for br in box_regression]
502
+ logits_per_image = [cl[index] for cl in class_logits]
503
+ box_ctrness_per_image = [bc[index] for bc in box_ctrness]
504
+ anchors_per_image, image_shape = anchors[index], image_shapes[index]
505
+
506
+ image_boxes = []
507
+ image_scores = []
508
+ image_labels = []
509
+
510
+ for box_regression_per_level, logits_per_level, box_ctrness_per_level, anchors_per_level in zip(
511
+ box_regression_per_image, logits_per_image, box_ctrness_per_image, anchors_per_image
512
+ ):
513
+ num_classes = logits_per_level.shape[-1]
514
+
515
+ # remove low scoring boxes
516
+ scores_per_level = torch.sqrt(
517
+ torch.sigmoid(logits_per_level) * torch.sigmoid(box_ctrness_per_level)
518
+ ).flatten()
519
+ keep_idxs = scores_per_level > self.score_thresh
520
+ scores_per_level = scores_per_level[keep_idxs]
521
+ topk_idxs = torch.where(keep_idxs)[0]
522
+
523
+ # keep only topk scoring predictions
524
+ num_topk = det_utils._topk_min(topk_idxs, self.topk_candidates, 0)
525
+ scores_per_level, idxs = scores_per_level.topk(num_topk)
526
+ topk_idxs = topk_idxs[idxs]
527
+
528
+ anchor_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor")
529
+ labels_per_level = topk_idxs % num_classes
530
+
531
+ boxes_per_level = self.box_coder.decode(
532
+ box_regression_per_level[anchor_idxs], anchors_per_level[anchor_idxs]
533
+ )
534
+ boxes_per_level = box_ops.clip_boxes_to_image(boxes_per_level, image_shape)
535
+
536
+ image_boxes.append(boxes_per_level)
537
+ image_scores.append(scores_per_level)
538
+ image_labels.append(labels_per_level)
539
+
540
+ image_boxes = torch.cat(image_boxes, dim=0)
541
+ image_scores = torch.cat(image_scores, dim=0)
542
+ image_labels = torch.cat(image_labels, dim=0)
543
+
544
+ # non-maximum suppression
545
+ keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh)
546
+ keep = keep[: self.detections_per_img]
547
+
548
+ detections.append(
549
+ {
550
+ "boxes": image_boxes[keep],
551
+ "scores": image_scores[keep],
552
+ "labels": image_labels[keep],
553
+ }
554
+ )
555
+
556
+ return detections
557
+
558
+ def forward(
559
+ self,
560
+ images: List[Tensor],
561
+ targets: Optional[List[Dict[str, Tensor]]] = None,
562
+ ) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]:
563
+ """
564
+ Args:
565
+ images (list[Tensor]): images to be processed
566
+ targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)
567
+
568
+ Returns:
569
+ result (list[BoxList] or dict[Tensor]): the output from the model.
570
+ During training, it returns a dict[Tensor] which contains the losses.
571
+ During testing, it returns list[BoxList] contains additional fields
572
+ like `scores`, `labels` and `mask` (for Mask R-CNN models).
573
+ """
574
+ if self.training:
575
+
576
+ if targets is None:
577
+ torch._assert(False, "targets should not be none when in training mode")
578
+ else:
579
+ for target in targets:
580
+ boxes = target["boxes"]
581
+ torch._assert(isinstance(boxes, torch.Tensor), "Expected target boxes to be of type Tensor.")
582
+ torch._assert(
583
+ len(boxes.shape) == 2 and boxes.shape[-1] == 4,
584
+ f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.",
585
+ )
586
+
587
+ original_image_sizes: List[Tuple[int, int]] = []
588
+ for img in images:
589
+ val = img.shape[-2:]
590
+ torch._assert(
591
+ len(val) == 2,
592
+ f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}",
593
+ )
594
+ original_image_sizes.append((val[0], val[1]))
595
+
596
+ # transform the input
597
+ images, targets = self.transform(images, targets)
598
+
599
+ # Check for degenerate boxes
600
+ if targets is not None:
601
+ for target_idx, target in enumerate(targets):
602
+ boxes = target["boxes"]
603
+ degenerate_boxes = boxes[:, 2:] <= boxes[:, :2]
604
+ if degenerate_boxes.any():
605
+ # print the first degenerate box
606
+ bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0]
607
+ degen_bb: List[float] = boxes[bb_idx].tolist()
608
+ torch._assert(
609
+ False,
610
+ f"All bounding boxes should have positive height and width. Found invalid box {degen_bb} for target at index {target_idx}.",
611
+ )
612
+
613
+ # get the features from the backbone
614
+ features = self.backbone(images.tensors)
615
+ if isinstance(features, torch.Tensor):
616
+ features = OrderedDict([("0", features)])
617
+
618
+ features = list(features.values())
619
+
620
+ # compute the fcos heads outputs using the features
621
+ head_outputs = self.head(features)
622
+
623
+ # create the set of anchors
624
+ anchors = self.anchor_generator(images, features)
625
+ # recover level sizes
626
+ num_anchors_per_level = [x.size(2) * x.size(3) for x in features]
627
+
628
+ losses = {}
629
+ detections: List[Dict[str, Tensor]] = []
630
+ if self.training:
631
+ if targets is None:
632
+ torch._assert(False, "targets should not be none when in training mode")
633
+ else:
634
+ # compute the losses
635
+ losses = self.compute_loss(targets, head_outputs, anchors, num_anchors_per_level)
636
+ else:
637
+ # split outputs per level
638
+ split_head_outputs: Dict[str, List[Tensor]] = {}
639
+ for k in head_outputs:
640
+ split_head_outputs[k] = list(head_outputs[k].split(num_anchors_per_level, dim=1))
641
+ split_anchors = [list(a.split(num_anchors_per_level)) for a in anchors]
642
+
643
+ # compute the detections
644
+ detections = self.postprocess_detections(split_head_outputs, split_anchors, images.image_sizes)
645
+ detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes)
646
+
647
+ if torch.jit.is_scripting():
648
+ if not self._has_warned:
649
+ warnings.warn("FCOS always returns a (Losses, Detections) tuple in scripting")
650
+ self._has_warned = True
651
+ return losses, detections
652
+ return self.eager_outputs(losses, detections)
653
+
654
+
655
+ class FCOS_ResNet50_FPN_Weights(WeightsEnum):
656
+ COCO_V1 = Weights(
657
+ url="https://download.pytorch.org/models/fcos_resnet50_fpn_coco-99b0c9b7.pth",
658
+ transforms=ObjectDetection,
659
+ meta={
660
+ "num_params": 32269600,
661
+ "categories": _COCO_CATEGORIES,
662
+ "min_size": (1, 1),
663
+ "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#fcos-resnet-50-fpn",
664
+ "_metrics": {
665
+ "COCO-val2017": {
666
+ "box_map": 39.2,
667
+ }
668
+ },
669
+ "_ops": 128.207,
670
+ "_file_size": 123.608,
671
+ "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
672
+ },
673
+ )
674
+ DEFAULT = COCO_V1
675
+
676
+
677
+ @register_model()
678
+ @handle_legacy_interface(
679
+ weights=("pretrained", FCOS_ResNet50_FPN_Weights.COCO_V1),
680
+ weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
681
+ )
682
+ def fcos_resnet50_fpn(
683
+ *,
684
+ weights: Optional[FCOS_ResNet50_FPN_Weights] = None,
685
+ progress: bool = True,
686
+ num_classes: Optional[int] = None,
687
+ weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
688
+ trainable_backbone_layers: Optional[int] = None,
689
+ **kwargs: Any,
690
+ ) -> FCOS:
691
+ """
692
+ Constructs a FCOS model with a ResNet-50-FPN backbone.
693
+
694
+ .. betastatus:: detection module
695
+
696
+ Reference: `FCOS: Fully Convolutional One-Stage Object Detection <https://arxiv.org/abs/1904.01355>`_.
697
+ `FCOS: A simple and strong anchor-free object detector <https://arxiv.org/abs/2006.09214>`_.
698
+
699
+ The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
700
+ image, and should be in ``0-1`` range. Different images can have different sizes.
701
+
702
+ The behavior of the model changes depending on if it is in training or evaluation mode.
703
+
704
+ During training, the model expects both the input tensors and targets (list of dictionary),
705
+ containing:
706
+
707
+ - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
708
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
709
+ - labels (``Int64Tensor[N]``): the class label for each ground-truth box
710
+
711
+ The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
712
+ losses.
713
+
714
+ During inference, the model requires only the input tensors, and returns the post-processed
715
+ predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
716
+ follows, where ``N`` is the number of detections:
717
+
718
+ - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
719
+ ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
720
+ - labels (``Int64Tensor[N]``): the predicted labels for each detection
721
+ - scores (``Tensor[N]``): the scores of each detection
722
+
723
+ For more details on the output, you may refer to :ref:`instance_seg_output`.
724
+
725
+ Example:
726
+
727
+ >>> model = torchvision.models.detection.fcos_resnet50_fpn(weights=FCOS_ResNet50_FPN_Weights.DEFAULT)
728
+ >>> model.eval()
729
+ >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
730
+ >>> predictions = model(x)
731
+
732
+ Args:
733
+ weights (:class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights`, optional): The
734
+ pretrained weights to use. See
735
+ :class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights`
736
+ below for more details, and possible values. By default, no
737
+ pre-trained weights are used.
738
+ progress (bool): If True, displays a progress bar of the download to stderr
739
+ num_classes (int, optional): number of output classes of the model (including the background)
740
+ weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for
741
+ the backbone.
742
+ trainable_backbone_layers (int, optional): number of trainable (not frozen) resnet layers starting
743
+ from final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
744
+ trainable. If ``None`` is passed (the default) this value is set to 3. Default: None
745
+ **kwargs: parameters passed to the ``torchvision.models.detection.FCOS``
746
+ base class. Please refer to the `source code
747
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/fcos.py>`_
748
+ for more details about this class.
749
+
750
+ .. autoclass:: torchvision.models.detection.FCOS_ResNet50_FPN_Weights
751
+ :members:
752
+ """
753
+ weights = FCOS_ResNet50_FPN_Weights.verify(weights)
754
+ weights_backbone = ResNet50_Weights.verify(weights_backbone)
755
+
756
+ if weights is not None:
757
+ weights_backbone = None
758
+ num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
759
+ elif num_classes is None:
760
+ num_classes = 91
761
+
762
+ is_trained = weights is not None or weights_backbone is not None
763
+ trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
764
+ norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
765
+
766
+ backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
767
+ backbone = _resnet_fpn_extractor(
768
+ backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(256, 256)
769
+ )
770
+ model = FCOS(backbone, num_classes, **kwargs)
771
+
772
+ if weights is not None:
773
+ model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
774
+
775
+ return model
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/generalized_rcnn.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implements the Generalized R-CNN framework
3
+ """
4
+
5
+ import warnings
6
+ from collections import OrderedDict
7
+ from typing import Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ from torch import nn, Tensor
11
+
12
+ from ...utils import _log_api_usage_once
13
+
14
+
15
+ class GeneralizedRCNN(nn.Module):
16
+ """
17
+ Main class for Generalized R-CNN.
18
+
19
+ Args:
20
+ backbone (nn.Module):
21
+ rpn (nn.Module):
22
+ roi_heads (nn.Module): takes the features + the proposals from the RPN and computes
23
+ detections / masks from it.
24
+ transform (nn.Module): performs the data transformation from the inputs to feed into
25
+ the model
26
+ """
27
+
28
+ def __init__(self, backbone: nn.Module, rpn: nn.Module, roi_heads: nn.Module, transform: nn.Module) -> None:
29
+ super().__init__()
30
+ _log_api_usage_once(self)
31
+ self.transform = transform
32
+ self.backbone = backbone
33
+ self.rpn = rpn
34
+ self.roi_heads = roi_heads
35
+ # used only on torchscript mode
36
+ self._has_warned = False
37
+
38
+ @torch.jit.unused
39
+ def eager_outputs(self, losses, detections):
40
+ # type: (Dict[str, Tensor], List[Dict[str, Tensor]]) -> Union[Dict[str, Tensor], List[Dict[str, Tensor]]]
41
+ if self.training:
42
+ return losses
43
+
44
+ return detections
45
+
46
+ def forward(self, images, targets=None):
47
+ # type: (List[Tensor], Optional[List[Dict[str, Tensor]]]) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]
48
+ """
49
+ Args:
50
+ images (list[Tensor]): images to be processed
51
+ targets (list[Dict[str, Tensor]]): ground-truth boxes present in the image (optional)
52
+
53
+ Returns:
54
+ result (list[BoxList] or dict[Tensor]): the output from the model.
55
+ During training, it returns a dict[Tensor] which contains the losses.
56
+ During testing, it returns list[BoxList] contains additional fields
57
+ like `scores`, `labels` and `mask` (for Mask R-CNN models).
58
+
59
+ """
60
+ if self.training:
61
+ if targets is None:
62
+ torch._assert(False, "targets should not be none when in training mode")
63
+ else:
64
+ for target in targets:
65
+ boxes = target["boxes"]
66
+ if isinstance(boxes, torch.Tensor):
67
+ torch._assert(
68
+ len(boxes.shape) == 2 and boxes.shape[-1] == 4,
69
+ f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.",
70
+ )
71
+ else:
72
+ torch._assert(False, f"Expected target boxes to be of type Tensor, got {type(boxes)}.")
73
+
74
+ original_image_sizes: List[Tuple[int, int]] = []
75
+ for img in images:
76
+ val = img.shape[-2:]
77
+ torch._assert(
78
+ len(val) == 2,
79
+ f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}",
80
+ )
81
+ original_image_sizes.append((val[0], val[1]))
82
+
83
+ images, targets = self.transform(images, targets)
84
+
85
+ # Check for degenerate boxes
86
+ # TODO: Move this to a function
87
+ if targets is not None:
88
+ for target_idx, target in enumerate(targets):
89
+ boxes = target["boxes"]
90
+ degenerate_boxes = boxes[:, 2:] <= boxes[:, :2]
91
+ if degenerate_boxes.any():
92
+ # print the first degenerate box
93
+ bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0]
94
+ degen_bb: List[float] = boxes[bb_idx].tolist()
95
+ torch._assert(
96
+ False,
97
+ "All bounding boxes should have positive height and width."
98
+ f" Found invalid box {degen_bb} for target at index {target_idx}.",
99
+ )
100
+
101
+ features = self.backbone(images.tensors)
102
+ if isinstance(features, torch.Tensor):
103
+ features = OrderedDict([("0", features)])
104
+ proposals, proposal_losses = self.rpn(images, features, targets)
105
+ detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)
106
+ detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes) # type: ignore[operator]
107
+
108
+ losses = {}
109
+ losses.update(detector_losses)
110
+ losses.update(proposal_losses)
111
+
112
+ if torch.jit.is_scripting():
113
+ if not self._has_warned:
114
+ warnings.warn("RCNN always returns a (Losses, Detections) tuple in scripting")
115
+ self._has_warned = True
116
+ return losses, detections
117
+ else:
118
+ return self.eager_outputs(losses, detections)
minigpt2/lib/python3.10/site-packages/torchvision/models/detection/image_list.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+
3
+ import torch
4
+ from torch import Tensor
5
+
6
+
7
+ class ImageList:
8
+ """
9
+ Structure that holds a list of images (of possibly
10
+ varying sizes) as a single tensor.
11
+ This works by padding the images to the same size,
12
+ and storing in a field the original sizes of each image
13
+
14
+ Args:
15
+ tensors (tensor): Tensor containing images.
16
+ image_sizes (list[tuple[int, int]]): List of Tuples each containing size of images.
17
+ """
18
+
19
+ def __init__(self, tensors: Tensor, image_sizes: List[Tuple[int, int]]) -> None:
20
+ self.tensors = tensors
21
+ self.image_sizes = image_sizes
22
+
23
+ def to(self, device: torch.device) -> "ImageList":
24
+ cast_tensor = self.tensors.to(device)
25
+ return ImageList(cast_tensor, self.image_sizes)