Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- wemm/lib/python3.10/site-packages/botocore/data/ivs/2020-07-14/endpoint-rule-set-1.json.gz +3 -0
- wemm/lib/python3.10/site-packages/torchvision/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/__pycache__/extension.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/datapoints/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/datapoints/__pycache__/_video.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/datapoints/_dataset_wrapper.py +499 -0
- wemm/lib/python3.10/site-packages/torchvision/datasets/clevr.py +88 -0
- wemm/lib/python3.10/site-packages/torchvision/io/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/io/__pycache__/_load_gpu_decoder.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/io/_load_gpu_decoder.py +8 -0
- wemm/lib/python3.10/site-packages/torchvision/io/image.py +264 -0
- wemm/lib/python3.10/site-packages/torchvision/io/video.py +415 -0
- wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/_api.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/_meta.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/alexnet.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/feature_extraction.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/mnasnet.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/shufflenetv2.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/_meta.py +1554 -0
- wemm/lib/python3.10/site-packages/torchvision/models/densenet.py +448 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/anchor_utils.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/backbone_utils.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/image_list.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/mask_rcnn.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/transform.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/_utils.py +548 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/backbone_utils.py +242 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/fcos.py +771 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/keypoint_rcnn.py +472 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/mask_rcnn.py +587 -0
- wemm/lib/python3.10/site-packages/torchvision/models/detection/rpn.py +387 -0
- wemm/lib/python3.10/site-packages/torchvision/models/inception.py +478 -0
- wemm/lib/python3.10/site-packages/torchvision/models/maxvit.py +832 -0
- wemm/lib/python3.10/site-packages/torchvision/models/mnasnet.py +434 -0
- wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__init__.py +1 -0
- wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__pycache__/_utils.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__pycache__/raft.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/_utils.py +48 -0
- wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/raft.py +934 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__init__.py +5 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/googlenet.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/mobilenet.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/mobilenetv2.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/mobilenetv3.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/resnet.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/utils.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/torchvision/models/quantization/googlenet.py +210 -0
wemm/lib/python3.10/site-packages/botocore/data/ivs/2020-07-14/endpoint-rule-set-1.json.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c33ca625b69f3d08bdca7ee800860952e37438e73c37458e1dd927c31ada3c65
|
| 3 |
+
size 1286
|
wemm/lib/python3.10/site-packages/torchvision/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (4.04 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/__pycache__/extension.cpython-310.pyc
ADDED
|
Binary file (2.92 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/datapoints/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (824 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/datapoints/__pycache__/_video.cpython-310.pyc
ADDED
|
Binary file (9.86 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/datapoints/_dataset_wrapper.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# type: ignore
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import contextlib
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch.utils.data import Dataset
|
| 10 |
+
|
| 11 |
+
from torchvision import datapoints, datasets
|
| 12 |
+
from torchvision.transforms.v2 import functional as F
|
| 13 |
+
|
| 14 |
+
__all__ = ["wrap_dataset_for_transforms_v2"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def wrap_dataset_for_transforms_v2(dataset):
|
| 18 |
+
"""[BETA] Wrap a ``torchvision.dataset`` for usage with :mod:`torchvision.transforms.v2`.
|
| 19 |
+
|
| 20 |
+
.. v2betastatus:: wrap_dataset_for_transforms_v2 function
|
| 21 |
+
|
| 22 |
+
Example:
|
| 23 |
+
>>> dataset = torchvision.datasets.CocoDetection(...)
|
| 24 |
+
>>> dataset = wrap_dataset_for_transforms_v2(dataset)
|
| 25 |
+
|
| 26 |
+
.. note::
|
| 27 |
+
|
| 28 |
+
For now, only the most popular datasets are supported. Furthermore, the wrapper only supports dataset
|
| 29 |
+
configurations that are fully supported by ``torchvision.transforms.v2``. If you encounter an error prompting you
|
| 30 |
+
to raise an issue to ``torchvision`` for a dataset or configuration that you need, please do so.
|
| 31 |
+
|
| 32 |
+
The dataset samples are wrapped according to the description below.
|
| 33 |
+
|
| 34 |
+
Special cases:
|
| 35 |
+
|
| 36 |
+
* :class:`~torchvision.datasets.CocoDetection`: Instead of returning the target as list of dicts, the wrapper
|
| 37 |
+
returns a dict of lists. In addition, the key-value-pairs ``"boxes"`` (in ``XYXY`` coordinate format),
|
| 38 |
+
``"masks"`` and ``"labels"`` are added and wrap the data in the corresponding ``torchvision.datapoints``.
|
| 39 |
+
The original keys are preserved.
|
| 40 |
+
* :class:`~torchvision.datasets.VOCDetection`: The key-value-pairs ``"boxes"`` and ``"labels"`` are added to
|
| 41 |
+
the target and wrap the data in the corresponding ``torchvision.datapoints``. The original keys are
|
| 42 |
+
preserved.
|
| 43 |
+
* :class:`~torchvision.datasets.CelebA`: The target for ``target_type="bbox"`` is converted to the ``XYXY``
|
| 44 |
+
coordinate format and wrapped into a :class:`~torchvision.datapoints.BoundingBox` datapoint.
|
| 45 |
+
* :class:`~torchvision.datasets.Kitti`: Instead returning the target as list of dictsthe wrapper returns a dict
|
| 46 |
+
of lists. In addition, the key-value-pairs ``"boxes"`` and ``"labels"`` are added and wrap the data
|
| 47 |
+
in the corresponding ``torchvision.datapoints``. The original keys are preserved.
|
| 48 |
+
* :class:`~torchvision.datasets.OxfordIIITPet`: The target for ``target_type="segmentation"`` is wrapped into a
|
| 49 |
+
:class:`~torchvision.datapoints.Mask` datapoint.
|
| 50 |
+
* :class:`~torchvision.datasets.Cityscapes`: The target for ``target_type="semantic"`` is wrapped into a
|
| 51 |
+
:class:`~torchvision.datapoints.Mask` datapoint. The target for ``target_type="instance"`` is *replaced* by
|
| 52 |
+
a dictionary with the key-value-pairs ``"masks"`` (as :class:`~torchvision.datapoints.Mask` datapoint) and
|
| 53 |
+
``"labels"``.
|
| 54 |
+
* :class:`~torchvision.datasets.WIDERFace`: The value for key ``"bbox"`` in the target is converted to ``XYXY``
|
| 55 |
+
coordinate format and wrapped into a :class:`~torchvision.datapoints.BoundingBox` datapoint.
|
| 56 |
+
|
| 57 |
+
Image classification datasets
|
| 58 |
+
|
| 59 |
+
This wrapper is a no-op for image classification datasets, since they were already fully supported by
|
| 60 |
+
:mod:`torchvision.transforms` and thus no change is needed for :mod:`torchvision.transforms.v2`.
|
| 61 |
+
|
| 62 |
+
Segmentation datasets
|
| 63 |
+
|
| 64 |
+
Segmentation datasets, e.g. :class:`~torchvision.datasets.VOCSegmentation` return a two-tuple of
|
| 65 |
+
:class:`PIL.Image.Image`'s. This wrapper leaves the image as is (first item), while wrapping the
|
| 66 |
+
segmentation mask into a :class:`~torchvision.datapoints.Mask` (second item).
|
| 67 |
+
|
| 68 |
+
Video classification datasets
|
| 69 |
+
|
| 70 |
+
Video classification datasets, e.g. :class:`~torchvision.datasets.Kinetics` return a three-tuple containing a
|
| 71 |
+
:class:`torch.Tensor` for the video and audio and a :class:`int` as label. This wrapper wraps the video into a
|
| 72 |
+
:class:`~torchvision.datapoints.Video` while leaving the other items as is.
|
| 73 |
+
|
| 74 |
+
.. note::
|
| 75 |
+
|
| 76 |
+
Only datasets constructed with ``output_format="TCHW"`` are supported, since the alternative
|
| 77 |
+
``output_format="THWC"`` is not supported by :mod:`torchvision.transforms.v2`.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
dataset: the dataset instance to wrap for compatibility with transforms v2.
|
| 81 |
+
"""
|
| 82 |
+
return VisionDatasetDatapointWrapper(dataset)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class WrapperFactories(dict):
|
| 86 |
+
def register(self, dataset_cls):
|
| 87 |
+
def decorator(wrapper_factory):
|
| 88 |
+
self[dataset_cls] = wrapper_factory
|
| 89 |
+
return wrapper_factory
|
| 90 |
+
|
| 91 |
+
return decorator
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# We need this two-stage design, i.e. a wrapper factory producing the actual wrapper, since some wrappers depend on the
|
| 95 |
+
# dataset instance rather than just the class, since they require the user defined instance attributes. Thus, we can
|
| 96 |
+
# provide a wrapping from the dataset class to the factory here, but can only instantiate the wrapper at runtime when
|
| 97 |
+
# we have access to the dataset instance.
|
| 98 |
+
WRAPPER_FACTORIES = WrapperFactories()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class VisionDatasetDatapointWrapper(Dataset):
|
| 102 |
+
def __init__(self, dataset):
|
| 103 |
+
dataset_cls = type(dataset)
|
| 104 |
+
|
| 105 |
+
if not isinstance(dataset, datasets.VisionDataset):
|
| 106 |
+
raise TypeError(
|
| 107 |
+
f"This wrapper is meant for subclasses of `torchvision.datasets.VisionDataset`, "
|
| 108 |
+
f"but got a '{dataset_cls.__name__}' instead."
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
for cls in dataset_cls.mro():
|
| 112 |
+
if cls in WRAPPER_FACTORIES:
|
| 113 |
+
wrapper_factory = WRAPPER_FACTORIES[cls]
|
| 114 |
+
break
|
| 115 |
+
elif cls is datasets.VisionDataset:
|
| 116 |
+
# TODO: If we have documentation on how to do that, put a link in the error message.
|
| 117 |
+
msg = f"No wrapper exists for dataset class {dataset_cls.__name__}. Please wrap the output yourself."
|
| 118 |
+
if dataset_cls in datasets.__dict__.values():
|
| 119 |
+
msg = (
|
| 120 |
+
f"{msg} If an automated wrapper for this dataset would be useful for you, "
|
| 121 |
+
f"please open an issue at https://github.com/pytorch/vision/issues."
|
| 122 |
+
)
|
| 123 |
+
raise TypeError(msg)
|
| 124 |
+
|
| 125 |
+
self._dataset = dataset
|
| 126 |
+
self._wrapper = wrapper_factory(dataset)
|
| 127 |
+
|
| 128 |
+
# We need to disable the transforms on the dataset here to be able to inject the wrapping before we apply them.
|
| 129 |
+
# Although internally, `datasets.VisionDataset` merges `transform` and `target_transform` into the joint
|
| 130 |
+
# `transforms`
|
| 131 |
+
# https://github.com/pytorch/vision/blob/135a0f9ea9841b6324b4fe8974e2543cbb95709a/torchvision/datasets/vision.py#L52-L54
|
| 132 |
+
# some (if not most) datasets still use `transform` and `target_transform` individually. Thus, we need to
|
| 133 |
+
# disable all three here to be able to extract the untransformed sample to wrap.
|
| 134 |
+
self.transform, dataset.transform = dataset.transform, None
|
| 135 |
+
self.target_transform, dataset.target_transform = dataset.target_transform, None
|
| 136 |
+
self.transforms, dataset.transforms = dataset.transforms, None
|
| 137 |
+
|
| 138 |
+
def __getattr__(self, item):
|
| 139 |
+
with contextlib.suppress(AttributeError):
|
| 140 |
+
return object.__getattribute__(self, item)
|
| 141 |
+
|
| 142 |
+
return getattr(self._dataset, item)
|
| 143 |
+
|
| 144 |
+
def __getitem__(self, idx):
|
| 145 |
+
# This gets us the raw sample since we disabled the transforms for the underlying dataset in the constructor
|
| 146 |
+
# of this class
|
| 147 |
+
sample = self._dataset[idx]
|
| 148 |
+
|
| 149 |
+
sample = self._wrapper(idx, sample)
|
| 150 |
+
|
| 151 |
+
# Regardless of whether the user has supplied the transforms individually (`transform` and `target_transform`)
|
| 152 |
+
# or joint (`transforms`), we can access the full functionality through `transforms`
|
| 153 |
+
if self.transforms is not None:
|
| 154 |
+
sample = self.transforms(*sample)
|
| 155 |
+
|
| 156 |
+
return sample
|
| 157 |
+
|
| 158 |
+
def __len__(self):
|
| 159 |
+
return len(self._dataset)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def raise_not_supported(description):
|
| 163 |
+
raise RuntimeError(
|
| 164 |
+
f"{description} is currently not supported by this wrapper. "
|
| 165 |
+
f"If this would be helpful for you, please open an issue at https://github.com/pytorch/vision/issues."
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def identity(item):
|
| 170 |
+
return item
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def identity_wrapper_factory(dataset):
|
| 174 |
+
def wrapper(idx, sample):
|
| 175 |
+
return sample
|
| 176 |
+
|
| 177 |
+
return wrapper
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def pil_image_to_mask(pil_image):
|
| 181 |
+
return datapoints.Mask(pil_image)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def list_of_dicts_to_dict_of_lists(list_of_dicts):
|
| 185 |
+
dict_of_lists = defaultdict(list)
|
| 186 |
+
for dct in list_of_dicts:
|
| 187 |
+
for key, value in dct.items():
|
| 188 |
+
dict_of_lists[key].append(value)
|
| 189 |
+
return dict(dict_of_lists)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def wrap_target_by_type(target, *, target_types, type_wrappers):
|
| 193 |
+
if not isinstance(target, (tuple, list)):
|
| 194 |
+
target = [target]
|
| 195 |
+
|
| 196 |
+
wrapped_target = tuple(
|
| 197 |
+
type_wrappers.get(target_type, identity)(item) for target_type, item in zip(target_types, target)
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
if len(wrapped_target) == 1:
|
| 201 |
+
wrapped_target = wrapped_target[0]
|
| 202 |
+
|
| 203 |
+
return wrapped_target
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def classification_wrapper_factory(dataset):
|
| 207 |
+
return identity_wrapper_factory(dataset)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
for dataset_cls in [
|
| 211 |
+
datasets.Caltech256,
|
| 212 |
+
datasets.CIFAR10,
|
| 213 |
+
datasets.CIFAR100,
|
| 214 |
+
datasets.ImageNet,
|
| 215 |
+
datasets.MNIST,
|
| 216 |
+
datasets.FashionMNIST,
|
| 217 |
+
datasets.GTSRB,
|
| 218 |
+
datasets.DatasetFolder,
|
| 219 |
+
datasets.ImageFolder,
|
| 220 |
+
]:
|
| 221 |
+
WRAPPER_FACTORIES.register(dataset_cls)(classification_wrapper_factory)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def segmentation_wrapper_factory(dataset):
|
| 225 |
+
def wrapper(idx, sample):
|
| 226 |
+
image, mask = sample
|
| 227 |
+
return image, pil_image_to_mask(mask)
|
| 228 |
+
|
| 229 |
+
return wrapper
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
for dataset_cls in [
|
| 233 |
+
datasets.VOCSegmentation,
|
| 234 |
+
]:
|
| 235 |
+
WRAPPER_FACTORIES.register(dataset_cls)(segmentation_wrapper_factory)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def video_classification_wrapper_factory(dataset):
|
| 239 |
+
if dataset.video_clips.output_format == "THWC":
|
| 240 |
+
raise RuntimeError(
|
| 241 |
+
f"{type(dataset).__name__} with `output_format='THWC'` is not supported by this wrapper, "
|
| 242 |
+
f"since it is not compatible with the transformations. Please use `output_format='TCHW'` instead."
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
def wrapper(idx, sample):
|
| 246 |
+
video, audio, label = sample
|
| 247 |
+
|
| 248 |
+
video = datapoints.Video(video)
|
| 249 |
+
|
| 250 |
+
return video, audio, label
|
| 251 |
+
|
| 252 |
+
return wrapper
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
for dataset_cls in [
|
| 256 |
+
datasets.HMDB51,
|
| 257 |
+
datasets.Kinetics,
|
| 258 |
+
datasets.UCF101,
|
| 259 |
+
]:
|
| 260 |
+
WRAPPER_FACTORIES.register(dataset_cls)(video_classification_wrapper_factory)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@WRAPPER_FACTORIES.register(datasets.Caltech101)
|
| 264 |
+
def caltech101_wrapper_factory(dataset):
|
| 265 |
+
if "annotation" in dataset.target_type:
|
| 266 |
+
raise_not_supported("Caltech101 dataset with `target_type=['annotation', ...]`")
|
| 267 |
+
|
| 268 |
+
return classification_wrapper_factory(dataset)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@WRAPPER_FACTORIES.register(datasets.CocoDetection)
|
| 272 |
+
def coco_dectection_wrapper_factory(dataset):
|
| 273 |
+
def segmentation_to_mask(segmentation, *, spatial_size):
|
| 274 |
+
from pycocotools import mask
|
| 275 |
+
|
| 276 |
+
segmentation = (
|
| 277 |
+
mask.frPyObjects(segmentation, *spatial_size)
|
| 278 |
+
if isinstance(segmentation, dict)
|
| 279 |
+
else mask.merge(mask.frPyObjects(segmentation, *spatial_size))
|
| 280 |
+
)
|
| 281 |
+
return torch.from_numpy(mask.decode(segmentation))
|
| 282 |
+
|
| 283 |
+
def wrapper(idx, sample):
|
| 284 |
+
image_id = dataset.ids[idx]
|
| 285 |
+
|
| 286 |
+
image, target = sample
|
| 287 |
+
|
| 288 |
+
if not target:
|
| 289 |
+
return image, dict(image_id=image_id)
|
| 290 |
+
|
| 291 |
+
batched_target = list_of_dicts_to_dict_of_lists(target)
|
| 292 |
+
|
| 293 |
+
batched_target["image_id"] = image_id
|
| 294 |
+
|
| 295 |
+
spatial_size = tuple(F.get_spatial_size(image))
|
| 296 |
+
batched_target["boxes"] = F.convert_format_bounding_box(
|
| 297 |
+
datapoints.BoundingBox(
|
| 298 |
+
batched_target["bbox"],
|
| 299 |
+
format=datapoints.BoundingBoxFormat.XYWH,
|
| 300 |
+
spatial_size=spatial_size,
|
| 301 |
+
),
|
| 302 |
+
new_format=datapoints.BoundingBoxFormat.XYXY,
|
| 303 |
+
)
|
| 304 |
+
batched_target["masks"] = datapoints.Mask(
|
| 305 |
+
torch.stack(
|
| 306 |
+
[
|
| 307 |
+
segmentation_to_mask(segmentation, spatial_size=spatial_size)
|
| 308 |
+
for segmentation in batched_target["segmentation"]
|
| 309 |
+
]
|
| 310 |
+
),
|
| 311 |
+
)
|
| 312 |
+
batched_target["labels"] = torch.tensor(batched_target["category_id"])
|
| 313 |
+
|
| 314 |
+
return image, batched_target
|
| 315 |
+
|
| 316 |
+
return wrapper
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
WRAPPER_FACTORIES.register(datasets.CocoCaptions)(identity_wrapper_factory)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
VOC_DETECTION_CATEGORIES = [
|
| 323 |
+
"__background__",
|
| 324 |
+
"aeroplane",
|
| 325 |
+
"bicycle",
|
| 326 |
+
"bird",
|
| 327 |
+
"boat",
|
| 328 |
+
"bottle",
|
| 329 |
+
"bus",
|
| 330 |
+
"car",
|
| 331 |
+
"cat",
|
| 332 |
+
"chair",
|
| 333 |
+
"cow",
|
| 334 |
+
"diningtable",
|
| 335 |
+
"dog",
|
| 336 |
+
"horse",
|
| 337 |
+
"motorbike",
|
| 338 |
+
"person",
|
| 339 |
+
"pottedplant",
|
| 340 |
+
"sheep",
|
| 341 |
+
"sofa",
|
| 342 |
+
"train",
|
| 343 |
+
"tvmonitor",
|
| 344 |
+
]
|
| 345 |
+
VOC_DETECTION_CATEGORY_TO_IDX = dict(zip(VOC_DETECTION_CATEGORIES, range(len(VOC_DETECTION_CATEGORIES))))
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
@WRAPPER_FACTORIES.register(datasets.VOCDetection)
|
| 349 |
+
def voc_detection_wrapper_factory(dataset):
|
| 350 |
+
def wrapper(idx, sample):
|
| 351 |
+
image, target = sample
|
| 352 |
+
|
| 353 |
+
batched_instances = list_of_dicts_to_dict_of_lists(target["annotation"]["object"])
|
| 354 |
+
|
| 355 |
+
target["boxes"] = datapoints.BoundingBox(
|
| 356 |
+
[
|
| 357 |
+
[int(bndbox[part]) for part in ("xmin", "ymin", "xmax", "ymax")]
|
| 358 |
+
for bndbox in batched_instances["bndbox"]
|
| 359 |
+
],
|
| 360 |
+
format=datapoints.BoundingBoxFormat.XYXY,
|
| 361 |
+
spatial_size=(image.height, image.width),
|
| 362 |
+
)
|
| 363 |
+
target["labels"] = torch.tensor(
|
| 364 |
+
[VOC_DETECTION_CATEGORY_TO_IDX[category] for category in batched_instances["name"]]
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
return image, target
|
| 368 |
+
|
| 369 |
+
return wrapper
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@WRAPPER_FACTORIES.register(datasets.SBDataset)
|
| 373 |
+
def sbd_wrapper(dataset):
|
| 374 |
+
if dataset.mode == "boundaries":
|
| 375 |
+
raise_not_supported("SBDataset with mode='boundaries'")
|
| 376 |
+
|
| 377 |
+
return segmentation_wrapper_factory(dataset)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
@WRAPPER_FACTORIES.register(datasets.CelebA)
|
| 381 |
+
def celeba_wrapper_factory(dataset):
|
| 382 |
+
if any(target_type in dataset.target_type for target_type in ["attr", "landmarks"]):
|
| 383 |
+
raise_not_supported("`CelebA` dataset with `target_type=['attr', 'landmarks', ...]`")
|
| 384 |
+
|
| 385 |
+
def wrapper(idx, sample):
|
| 386 |
+
image, target = sample
|
| 387 |
+
|
| 388 |
+
target = wrap_target_by_type(
|
| 389 |
+
target,
|
| 390 |
+
target_types=dataset.target_type,
|
| 391 |
+
type_wrappers={
|
| 392 |
+
"bbox": lambda item: F.convert_format_bounding_box(
|
| 393 |
+
datapoints.BoundingBox(
|
| 394 |
+
item,
|
| 395 |
+
format=datapoints.BoundingBoxFormat.XYWH,
|
| 396 |
+
spatial_size=(image.height, image.width),
|
| 397 |
+
),
|
| 398 |
+
new_format=datapoints.BoundingBoxFormat.XYXY,
|
| 399 |
+
),
|
| 400 |
+
},
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
return image, target
|
| 404 |
+
|
| 405 |
+
return wrapper
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
KITTI_CATEGORIES = ["Car", "Van", "Truck", "Pedestrian", "Person_sitting", "Cyclist", "Tram", "Misc", "DontCare"]
|
| 409 |
+
KITTI_CATEGORY_TO_IDX = dict(zip(KITTI_CATEGORIES, range(len(KITTI_CATEGORIES))))
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
@WRAPPER_FACTORIES.register(datasets.Kitti)
|
| 413 |
+
def kitti_wrapper_factory(dataset):
|
| 414 |
+
def wrapper(idx, sample):
|
| 415 |
+
image, target = sample
|
| 416 |
+
|
| 417 |
+
if target is not None:
|
| 418 |
+
target = list_of_dicts_to_dict_of_lists(target)
|
| 419 |
+
|
| 420 |
+
target["boxes"] = datapoints.BoundingBox(
|
| 421 |
+
target["bbox"], format=datapoints.BoundingBoxFormat.XYXY, spatial_size=(image.height, image.width)
|
| 422 |
+
)
|
| 423 |
+
target["labels"] = torch.tensor([KITTI_CATEGORY_TO_IDX[category] for category in target["type"]])
|
| 424 |
+
|
| 425 |
+
return image, target
|
| 426 |
+
|
| 427 |
+
return wrapper
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
@WRAPPER_FACTORIES.register(datasets.OxfordIIITPet)
|
| 431 |
+
def oxford_iiit_pet_wrapper_factor(dataset):
|
| 432 |
+
def wrapper(idx, sample):
|
| 433 |
+
image, target = sample
|
| 434 |
+
|
| 435 |
+
if target is not None:
|
| 436 |
+
target = wrap_target_by_type(
|
| 437 |
+
target,
|
| 438 |
+
target_types=dataset._target_types,
|
| 439 |
+
type_wrappers={
|
| 440 |
+
"segmentation": pil_image_to_mask,
|
| 441 |
+
},
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
return image, target
|
| 445 |
+
|
| 446 |
+
return wrapper
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
@WRAPPER_FACTORIES.register(datasets.Cityscapes)
|
| 450 |
+
def cityscapes_wrapper_factory(dataset):
|
| 451 |
+
if any(target_type in dataset.target_type for target_type in ["polygon", "color"]):
|
| 452 |
+
raise_not_supported("`Cityscapes` dataset with `target_type=['polygon', 'color', ...]`")
|
| 453 |
+
|
| 454 |
+
def instance_segmentation_wrapper(mask):
|
| 455 |
+
# See https://github.com/mcordts/cityscapesScripts/blob/8da5dd00c9069058ccc134654116aac52d4f6fa2/cityscapesscripts/preparation/json2instanceImg.py#L7-L21
|
| 456 |
+
data = pil_image_to_mask(mask)
|
| 457 |
+
masks = []
|
| 458 |
+
labels = []
|
| 459 |
+
for id in data.unique():
|
| 460 |
+
masks.append(data == id)
|
| 461 |
+
label = id
|
| 462 |
+
if label >= 1_000:
|
| 463 |
+
label //= 1_000
|
| 464 |
+
labels.append(label)
|
| 465 |
+
return dict(masks=datapoints.Mask(torch.stack(masks)), labels=torch.stack(labels))
|
| 466 |
+
|
| 467 |
+
def wrapper(idx, sample):
|
| 468 |
+
image, target = sample
|
| 469 |
+
|
| 470 |
+
target = wrap_target_by_type(
|
| 471 |
+
target,
|
| 472 |
+
target_types=dataset.target_type,
|
| 473 |
+
type_wrappers={
|
| 474 |
+
"instance": instance_segmentation_wrapper,
|
| 475 |
+
"semantic": pil_image_to_mask,
|
| 476 |
+
},
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
return image, target
|
| 480 |
+
|
| 481 |
+
return wrapper
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@WRAPPER_FACTORIES.register(datasets.WIDERFace)
|
| 485 |
+
def widerface_wrapper(dataset):
|
| 486 |
+
def wrapper(idx, sample):
|
| 487 |
+
image, target = sample
|
| 488 |
+
|
| 489 |
+
if target is not None:
|
| 490 |
+
target["bbox"] = F.convert_format_bounding_box(
|
| 491 |
+
datapoints.BoundingBox(
|
| 492 |
+
target["bbox"], format=datapoints.BoundingBoxFormat.XYWH, spatial_size=(image.height, image.width)
|
| 493 |
+
),
|
| 494 |
+
new_format=datapoints.BoundingBoxFormat.XYXY,
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
return image, target
|
| 498 |
+
|
| 499 |
+
return wrapper
|
wemm/lib/python3.10/site-packages/torchvision/datasets/clevr.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import pathlib
|
| 3 |
+
from typing import Any, Callable, List, Optional, Tuple
|
| 4 |
+
from urllib.parse import urlparse
|
| 5 |
+
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
from .utils import download_and_extract_archive, verify_str_arg
|
| 9 |
+
from .vision import VisionDataset
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CLEVRClassification(VisionDataset):
|
| 13 |
+
"""`CLEVR <https://cs.stanford.edu/people/jcjohns/clevr/>`_ classification dataset.
|
| 14 |
+
|
| 15 |
+
The number of objects in a scene are used as label.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
root (string): Root directory of dataset where directory ``root/clevr`` exists or will be saved to if download is
|
| 19 |
+
set to True.
|
| 20 |
+
split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``.
|
| 21 |
+
transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed
|
| 22 |
+
version. E.g, ``transforms.RandomCrop``
|
| 23 |
+
target_transform (callable, optional): A function/transform that takes in them target and transforms it.
|
| 24 |
+
download (bool, optional): If true, downloads the dataset from the internet and puts it in root directory. If
|
| 25 |
+
dataset is already downloaded, it is not downloaded again.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
_URL = "https://dl.fbaipublicfiles.com/clevr/CLEVR_v1.0.zip"
|
| 29 |
+
_MD5 = "b11922020e72d0cd9154779b2d3d07d2"
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
root: str,
|
| 34 |
+
split: str = "train",
|
| 35 |
+
transform: Optional[Callable] = None,
|
| 36 |
+
target_transform: Optional[Callable] = None,
|
| 37 |
+
download: bool = False,
|
| 38 |
+
) -> None:
|
| 39 |
+
self._split = verify_str_arg(split, "split", ("train", "val", "test"))
|
| 40 |
+
super().__init__(root, transform=transform, target_transform=target_transform)
|
| 41 |
+
self._base_folder = pathlib.Path(self.root) / "clevr"
|
| 42 |
+
self._data_folder = self._base_folder / pathlib.Path(urlparse(self._URL).path).stem
|
| 43 |
+
|
| 44 |
+
if download:
|
| 45 |
+
self._download()
|
| 46 |
+
|
| 47 |
+
if not self._check_exists():
|
| 48 |
+
raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
|
| 49 |
+
|
| 50 |
+
self._image_files = sorted(self._data_folder.joinpath("images", self._split).glob("*"))
|
| 51 |
+
|
| 52 |
+
self._labels: List[Optional[int]]
|
| 53 |
+
if self._split != "test":
|
| 54 |
+
with open(self._data_folder / "scenes" / f"CLEVR_{self._split}_scenes.json") as file:
|
| 55 |
+
content = json.load(file)
|
| 56 |
+
num_objects = {scene["image_filename"]: len(scene["objects"]) for scene in content["scenes"]}
|
| 57 |
+
self._labels = [num_objects[image_file.name] for image_file in self._image_files]
|
| 58 |
+
else:
|
| 59 |
+
self._labels = [None] * len(self._image_files)
|
| 60 |
+
|
| 61 |
+
def __len__(self) -> int:
|
| 62 |
+
return len(self._image_files)
|
| 63 |
+
|
| 64 |
+
def __getitem__(self, idx: int) -> Tuple[Any, Any]:
|
| 65 |
+
image_file = self._image_files[idx]
|
| 66 |
+
label = self._labels[idx]
|
| 67 |
+
|
| 68 |
+
image = Image.open(image_file).convert("RGB")
|
| 69 |
+
|
| 70 |
+
if self.transform:
|
| 71 |
+
image = self.transform(image)
|
| 72 |
+
|
| 73 |
+
if self.target_transform:
|
| 74 |
+
label = self.target_transform(label)
|
| 75 |
+
|
| 76 |
+
return image, label
|
| 77 |
+
|
| 78 |
+
def _check_exists(self) -> bool:
|
| 79 |
+
return self._data_folder.exists() and self._data_folder.is_dir()
|
| 80 |
+
|
| 81 |
+
def _download(self) -> None:
|
| 82 |
+
if self._check_exists():
|
| 83 |
+
return
|
| 84 |
+
|
| 85 |
+
download_and_extract_archive(self._URL, str(self._base_folder), md5=self._MD5)
|
| 86 |
+
|
| 87 |
+
def extra_repr(self) -> str:
|
| 88 |
+
return f"split={self._split}"
|
wemm/lib/python3.10/site-packages/torchvision/io/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.35 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/io/__pycache__/_load_gpu_decoder.cpython-310.pyc
ADDED
|
Binary file (333 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/io/_load_gpu_decoder.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ..extension import _load_library
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
try:
|
| 5 |
+
_load_library("Decoder")
|
| 6 |
+
_HAS_GPU_VIDEO_DECODER = True
|
| 7 |
+
except (ImportError, OSError):
|
| 8 |
+
_HAS_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
from warnings import warn
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from ..extension import _load_library
|
| 7 |
+
from ..utils import _log_api_usage_once
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
_load_library("image")
|
| 12 |
+
except (ImportError, OSError) as e:
|
| 13 |
+
warn(
|
| 14 |
+
f"Failed to load image Python extension: '{e}'"
|
| 15 |
+
f"If you don't plan on using image functionality from `torchvision.io`, you can ignore this warning. "
|
| 16 |
+
f"Otherwise, there might be something wrong with your environment. "
|
| 17 |
+
f"Did you have `libjpeg` or `libpng` installed before building `torchvision` from source?"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ImageReadMode(Enum):
|
| 22 |
+
"""
|
| 23 |
+
Support for various modes while reading images.
|
| 24 |
+
|
| 25 |
+
Use ``ImageReadMode.UNCHANGED`` for loading the image as-is,
|
| 26 |
+
``ImageReadMode.GRAY`` for converting to grayscale,
|
| 27 |
+
``ImageReadMode.GRAY_ALPHA`` for grayscale with transparency,
|
| 28 |
+
``ImageReadMode.RGB`` for RGB and ``ImageReadMode.RGB_ALPHA`` for
|
| 29 |
+
RGB with transparency.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
UNCHANGED = 0
|
| 33 |
+
GRAY = 1
|
| 34 |
+
GRAY_ALPHA = 2
|
| 35 |
+
RGB = 3
|
| 36 |
+
RGB_ALPHA = 4
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def read_file(path: str) -> torch.Tensor:
|
| 40 |
+
"""
|
| 41 |
+
Reads and outputs the bytes contents of a file as a uint8 Tensor
|
| 42 |
+
with one dimension.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
path (str): the path to the file to be read
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
data (Tensor)
|
| 49 |
+
"""
|
| 50 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 51 |
+
_log_api_usage_once(read_file)
|
| 52 |
+
data = torch.ops.image.read_file(path)
|
| 53 |
+
return data
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def write_file(filename: str, data: torch.Tensor) -> None:
|
| 57 |
+
"""
|
| 58 |
+
Writes the contents of an uint8 tensor with one dimension to a
|
| 59 |
+
file.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
filename (str): the path to the file to be written
|
| 63 |
+
data (Tensor): the contents to be written to the output file
|
| 64 |
+
"""
|
| 65 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 66 |
+
_log_api_usage_once(write_file)
|
| 67 |
+
torch.ops.image.write_file(filename, data)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def decode_png(input: torch.Tensor, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor:
|
| 71 |
+
"""
|
| 72 |
+
Decodes a PNG image into a 3 dimensional RGB or grayscale Tensor.
|
| 73 |
+
Optionally converts the image to the desired format.
|
| 74 |
+
The values of the output tensor are uint8 in [0, 255].
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
input (Tensor[1]): a one dimensional uint8 tensor containing
|
| 78 |
+
the raw bytes of the PNG image.
|
| 79 |
+
mode (ImageReadMode): the read mode used for optionally
|
| 80 |
+
converting the image. Default: ``ImageReadMode.UNCHANGED``.
|
| 81 |
+
See `ImageReadMode` class for more information on various
|
| 82 |
+
available modes.
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
output (Tensor[image_channels, image_height, image_width])
|
| 86 |
+
"""
|
| 87 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 88 |
+
_log_api_usage_once(decode_png)
|
| 89 |
+
output = torch.ops.image.decode_png(input, mode.value, False)
|
| 90 |
+
return output
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def encode_png(input: torch.Tensor, compression_level: int = 6) -> torch.Tensor:
|
| 94 |
+
"""
|
| 95 |
+
Takes an input tensor in CHW layout and returns a buffer with the contents
|
| 96 |
+
of its corresponding PNG file.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
input (Tensor[channels, image_height, image_width]): int8 image tensor of
|
| 100 |
+
``c`` channels, where ``c`` must 3 or 1.
|
| 101 |
+
compression_level (int): Compression factor for the resulting file, it must be a number
|
| 102 |
+
between 0 and 9. Default: 6
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
Tensor[1]: A one dimensional int8 tensor that contains the raw bytes of the
|
| 106 |
+
PNG file.
|
| 107 |
+
"""
|
| 108 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 109 |
+
_log_api_usage_once(encode_png)
|
| 110 |
+
output = torch.ops.image.encode_png(input, compression_level)
|
| 111 |
+
return output
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def write_png(input: torch.Tensor, filename: str, compression_level: int = 6):
|
| 115 |
+
"""
|
| 116 |
+
Takes an input tensor in CHW layout (or HW in the case of grayscale images)
|
| 117 |
+
and saves it in a PNG file.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
input (Tensor[channels, image_height, image_width]): int8 image tensor of
|
| 121 |
+
``c`` channels, where ``c`` must be 1 or 3.
|
| 122 |
+
filename (str): Path to save the image.
|
| 123 |
+
compression_level (int): Compression factor for the resulting file, it must be a number
|
| 124 |
+
between 0 and 9. Default: 6
|
| 125 |
+
"""
|
| 126 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 127 |
+
_log_api_usage_once(write_png)
|
| 128 |
+
output = encode_png(input, compression_level)
|
| 129 |
+
write_file(filename, output)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def decode_jpeg(
|
| 133 |
+
input: torch.Tensor, mode: ImageReadMode = ImageReadMode.UNCHANGED, device: str = "cpu"
|
| 134 |
+
) -> torch.Tensor:
|
| 135 |
+
"""
|
| 136 |
+
Decodes a JPEG image into a 3 dimensional RGB or grayscale Tensor.
|
| 137 |
+
Optionally converts the image to the desired format.
|
| 138 |
+
The values of the output tensor are uint8 between 0 and 255.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
input (Tensor[1]): a one dimensional uint8 tensor containing
|
| 142 |
+
the raw bytes of the JPEG image. This tensor must be on CPU,
|
| 143 |
+
regardless of the ``device`` parameter.
|
| 144 |
+
mode (ImageReadMode): the read mode used for optionally
|
| 145 |
+
converting the image. The supported modes are: ``ImageReadMode.UNCHANGED``,
|
| 146 |
+
``ImageReadMode.GRAY`` and ``ImageReadMode.RGB``
|
| 147 |
+
Default: ``ImageReadMode.UNCHANGED``.
|
| 148 |
+
See ``ImageReadMode`` class for more information on various
|
| 149 |
+
available modes.
|
| 150 |
+
device (str or torch.device): The device on which the decoded image will
|
| 151 |
+
be stored. If a cuda device is specified, the image will be decoded
|
| 152 |
+
with `nvjpeg <https://developer.nvidia.com/nvjpeg>`_. This is only
|
| 153 |
+
supported for CUDA version >= 10.1
|
| 154 |
+
|
| 155 |
+
.. betastatus:: device parameter
|
| 156 |
+
|
| 157 |
+
.. warning::
|
| 158 |
+
There is a memory leak in the nvjpeg library for CUDA versions < 11.6.
|
| 159 |
+
Make sure to rely on CUDA 11.6 or above before using ``device="cuda"``.
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
output (Tensor[image_channels, image_height, image_width])
|
| 163 |
+
"""
|
| 164 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 165 |
+
_log_api_usage_once(decode_jpeg)
|
| 166 |
+
device = torch.device(device)
|
| 167 |
+
if device.type == "cuda":
|
| 168 |
+
output = torch.ops.image.decode_jpeg_cuda(input, mode.value, device)
|
| 169 |
+
else:
|
| 170 |
+
output = torch.ops.image.decode_jpeg(input, mode.value)
|
| 171 |
+
return output
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def encode_jpeg(input: torch.Tensor, quality: int = 75) -> torch.Tensor:
|
| 175 |
+
"""
|
| 176 |
+
Takes an input tensor in CHW layout and returns a buffer with the contents
|
| 177 |
+
of its corresponding JPEG file.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
input (Tensor[channels, image_height, image_width])): int8 image tensor of
|
| 181 |
+
``c`` channels, where ``c`` must be 1 or 3.
|
| 182 |
+
quality (int): Quality of the resulting JPEG file, it must be a number between
|
| 183 |
+
1 and 100. Default: 75
|
| 184 |
+
|
| 185 |
+
Returns:
|
| 186 |
+
output (Tensor[1]): A one dimensional int8 tensor that contains the raw bytes of the
|
| 187 |
+
JPEG file.
|
| 188 |
+
"""
|
| 189 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 190 |
+
_log_api_usage_once(encode_jpeg)
|
| 191 |
+
if quality < 1 or quality > 100:
|
| 192 |
+
raise ValueError("Image quality should be a positive number between 1 and 100")
|
| 193 |
+
|
| 194 |
+
output = torch.ops.image.encode_jpeg(input, quality)
|
| 195 |
+
return output
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def write_jpeg(input: torch.Tensor, filename: str, quality: int = 75):
|
| 199 |
+
"""
|
| 200 |
+
Takes an input tensor in CHW layout and saves it in a JPEG file.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
input (Tensor[channels, image_height, image_width]): int8 image tensor of ``c``
|
| 204 |
+
channels, where ``c`` must be 1 or 3.
|
| 205 |
+
filename (str): Path to save the image.
|
| 206 |
+
quality (int): Quality of the resulting JPEG file, it must be a number
|
| 207 |
+
between 1 and 100. Default: 75
|
| 208 |
+
"""
|
| 209 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 210 |
+
_log_api_usage_once(write_jpeg)
|
| 211 |
+
output = encode_jpeg(input, quality)
|
| 212 |
+
write_file(filename, output)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def decode_image(input: torch.Tensor, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor:
|
| 216 |
+
"""
|
| 217 |
+
Detects whether an image is a JPEG or PNG and performs the appropriate
|
| 218 |
+
operation to decode the image into a 3 dimensional RGB or grayscale Tensor.
|
| 219 |
+
|
| 220 |
+
Optionally converts the image to the desired format.
|
| 221 |
+
The values of the output tensor are uint8 in [0, 255].
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
input (Tensor): a one dimensional uint8 tensor containing the raw bytes of the
|
| 225 |
+
PNG or JPEG image.
|
| 226 |
+
mode (ImageReadMode): the read mode used for optionally converting the image.
|
| 227 |
+
Default: ``ImageReadMode.UNCHANGED``.
|
| 228 |
+
See ``ImageReadMode`` class for more information on various
|
| 229 |
+
available modes.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
output (Tensor[image_channels, image_height, image_width])
|
| 233 |
+
"""
|
| 234 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 235 |
+
_log_api_usage_once(decode_image)
|
| 236 |
+
output = torch.ops.image.decode_image(input, mode.value)
|
| 237 |
+
return output
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def read_image(path: str, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor:
|
| 241 |
+
"""
|
| 242 |
+
Reads a JPEG or PNG image into a 3 dimensional RGB or grayscale Tensor.
|
| 243 |
+
Optionally converts the image to the desired format.
|
| 244 |
+
The values of the output tensor are uint8 in [0, 255].
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
path (str): path of the JPEG or PNG image.
|
| 248 |
+
mode (ImageReadMode): the read mode used for optionally converting the image.
|
| 249 |
+
Default: ``ImageReadMode.UNCHANGED``.
|
| 250 |
+
See ``ImageReadMode`` class for more information on various
|
| 251 |
+
available modes.
|
| 252 |
+
|
| 253 |
+
Returns:
|
| 254 |
+
output (Tensor[image_channels, image_height, image_width])
|
| 255 |
+
"""
|
| 256 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 257 |
+
_log_api_usage_once(read_image)
|
| 258 |
+
data = read_file(path)
|
| 259 |
+
return decode_image(data, mode)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _read_png_16(path: str, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor:
|
| 263 |
+
data = read_file(path)
|
| 264 |
+
return torch.ops.image.decode_png(data, mode.value, True)
|
wemm/lib/python3.10/site-packages/torchvision/io/video.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import warnings
|
| 6 |
+
from fractions import Fraction
|
| 7 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from ..utils import _log_api_usage_once
|
| 13 |
+
from . import _video_opt
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import av
|
| 17 |
+
|
| 18 |
+
av.logging.set_level(av.logging.ERROR)
|
| 19 |
+
if not hasattr(av.video.frame.VideoFrame, "pict_type"):
|
| 20 |
+
av = ImportError(
|
| 21 |
+
"""\
|
| 22 |
+
Your version of PyAV is too old for the necessary video operations in torchvision.
|
| 23 |
+
If you are on Python 3.5, you will have to build from source (the conda-forge
|
| 24 |
+
packages are not up-to-date). See
|
| 25 |
+
https://github.com/mikeboers/PyAV#installation for instructions on how to
|
| 26 |
+
install PyAV on your system.
|
| 27 |
+
"""
|
| 28 |
+
)
|
| 29 |
+
except ImportError:
|
| 30 |
+
av = ImportError(
|
| 31 |
+
"""\
|
| 32 |
+
PyAV is not installed, and is necessary for the video operations in torchvision.
|
| 33 |
+
See https://github.com/mikeboers/PyAV#installation for instructions on how to
|
| 34 |
+
install PyAV on your system.
|
| 35 |
+
"""
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _check_av_available() -> None:
|
| 40 |
+
if isinstance(av, Exception):
|
| 41 |
+
raise av
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _av_available() -> bool:
|
| 45 |
+
return not isinstance(av, Exception)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# PyAV has some reference cycles
|
| 49 |
+
_CALLED_TIMES = 0
|
| 50 |
+
_GC_COLLECTION_INTERVAL = 10
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def write_video(
|
| 54 |
+
filename: str,
|
| 55 |
+
video_array: torch.Tensor,
|
| 56 |
+
fps: float,
|
| 57 |
+
video_codec: str = "libx264",
|
| 58 |
+
options: Optional[Dict[str, Any]] = None,
|
| 59 |
+
audio_array: Optional[torch.Tensor] = None,
|
| 60 |
+
audio_fps: Optional[float] = None,
|
| 61 |
+
audio_codec: Optional[str] = None,
|
| 62 |
+
audio_options: Optional[Dict[str, Any]] = None,
|
| 63 |
+
) -> None:
|
| 64 |
+
"""
|
| 65 |
+
Writes a 4d tensor in [T, H, W, C] format in a video file
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
filename (str): path where the video will be saved
|
| 69 |
+
video_array (Tensor[T, H, W, C]): tensor containing the individual frames,
|
| 70 |
+
as a uint8 tensor in [T, H, W, C] format
|
| 71 |
+
fps (Number): video frames per second
|
| 72 |
+
video_codec (str): the name of the video codec, i.e. "libx264", "h264", etc.
|
| 73 |
+
options (Dict): dictionary containing options to be passed into the PyAV video stream
|
| 74 |
+
audio_array (Tensor[C, N]): tensor containing the audio, where C is the number of channels
|
| 75 |
+
and N is the number of samples
|
| 76 |
+
audio_fps (Number): audio sample rate, typically 44100 or 48000
|
| 77 |
+
audio_codec (str): the name of the audio codec, i.e. "mp3", "aac", etc.
|
| 78 |
+
audio_options (Dict): dictionary containing options to be passed into the PyAV audio stream
|
| 79 |
+
"""
|
| 80 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 81 |
+
_log_api_usage_once(write_video)
|
| 82 |
+
_check_av_available()
|
| 83 |
+
video_array = torch.as_tensor(video_array, dtype=torch.uint8).numpy()
|
| 84 |
+
|
| 85 |
+
# PyAV does not support floating point numbers with decimal point
|
| 86 |
+
# and will throw OverflowException in case this is not the case
|
| 87 |
+
if isinstance(fps, float):
|
| 88 |
+
fps = np.round(fps)
|
| 89 |
+
|
| 90 |
+
with av.open(filename, mode="w") as container:
|
| 91 |
+
stream = container.add_stream(video_codec, rate=fps)
|
| 92 |
+
stream.width = video_array.shape[2]
|
| 93 |
+
stream.height = video_array.shape[1]
|
| 94 |
+
stream.pix_fmt = "yuv420p" if video_codec != "libx264rgb" else "rgb24"
|
| 95 |
+
stream.options = options or {}
|
| 96 |
+
|
| 97 |
+
if audio_array is not None:
|
| 98 |
+
audio_format_dtypes = {
|
| 99 |
+
"dbl": "<f8",
|
| 100 |
+
"dblp": "<f8",
|
| 101 |
+
"flt": "<f4",
|
| 102 |
+
"fltp": "<f4",
|
| 103 |
+
"s16": "<i2",
|
| 104 |
+
"s16p": "<i2",
|
| 105 |
+
"s32": "<i4",
|
| 106 |
+
"s32p": "<i4",
|
| 107 |
+
"u8": "u1",
|
| 108 |
+
"u8p": "u1",
|
| 109 |
+
}
|
| 110 |
+
a_stream = container.add_stream(audio_codec, rate=audio_fps)
|
| 111 |
+
a_stream.options = audio_options or {}
|
| 112 |
+
|
| 113 |
+
num_channels = audio_array.shape[0]
|
| 114 |
+
audio_layout = "stereo" if num_channels > 1 else "mono"
|
| 115 |
+
audio_sample_fmt = container.streams.audio[0].format.name
|
| 116 |
+
|
| 117 |
+
format_dtype = np.dtype(audio_format_dtypes[audio_sample_fmt])
|
| 118 |
+
audio_array = torch.as_tensor(audio_array).numpy().astype(format_dtype)
|
| 119 |
+
|
| 120 |
+
frame = av.AudioFrame.from_ndarray(audio_array, format=audio_sample_fmt, layout=audio_layout)
|
| 121 |
+
|
| 122 |
+
frame.sample_rate = audio_fps
|
| 123 |
+
|
| 124 |
+
for packet in a_stream.encode(frame):
|
| 125 |
+
container.mux(packet)
|
| 126 |
+
|
| 127 |
+
for packet in a_stream.encode():
|
| 128 |
+
container.mux(packet)
|
| 129 |
+
|
| 130 |
+
for img in video_array:
|
| 131 |
+
frame = av.VideoFrame.from_ndarray(img, format="rgb24")
|
| 132 |
+
frame.pict_type = "NONE"
|
| 133 |
+
for packet in stream.encode(frame):
|
| 134 |
+
container.mux(packet)
|
| 135 |
+
|
| 136 |
+
# Flush stream
|
| 137 |
+
for packet in stream.encode():
|
| 138 |
+
container.mux(packet)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _read_from_stream(
|
| 142 |
+
container: "av.container.Container",
|
| 143 |
+
start_offset: float,
|
| 144 |
+
end_offset: float,
|
| 145 |
+
pts_unit: str,
|
| 146 |
+
stream: "av.stream.Stream",
|
| 147 |
+
stream_name: Dict[str, Optional[Union[int, Tuple[int, ...], List[int]]]],
|
| 148 |
+
) -> List["av.frame.Frame"]:
|
| 149 |
+
global _CALLED_TIMES, _GC_COLLECTION_INTERVAL
|
| 150 |
+
_CALLED_TIMES += 1
|
| 151 |
+
if _CALLED_TIMES % _GC_COLLECTION_INTERVAL == _GC_COLLECTION_INTERVAL - 1:
|
| 152 |
+
gc.collect()
|
| 153 |
+
|
| 154 |
+
if pts_unit == "sec":
|
| 155 |
+
# TODO: we should change all of this from ground up to simply take
|
| 156 |
+
# sec and convert to MS in C++
|
| 157 |
+
start_offset = int(math.floor(start_offset * (1 / stream.time_base)))
|
| 158 |
+
if end_offset != float("inf"):
|
| 159 |
+
end_offset = int(math.ceil(end_offset * (1 / stream.time_base)))
|
| 160 |
+
else:
|
| 161 |
+
warnings.warn("The pts_unit 'pts' gives wrong results. Please use pts_unit 'sec'.")
|
| 162 |
+
|
| 163 |
+
frames = {}
|
| 164 |
+
should_buffer = True
|
| 165 |
+
max_buffer_size = 5
|
| 166 |
+
if stream.type == "video":
|
| 167 |
+
# DivX-style packed B-frames can have out-of-order pts (2 frames in a single pkt)
|
| 168 |
+
# so need to buffer some extra frames to sort everything
|
| 169 |
+
# properly
|
| 170 |
+
extradata = stream.codec_context.extradata
|
| 171 |
+
# overly complicated way of finding if `divx_packed` is set, following
|
| 172 |
+
# https://github.com/FFmpeg/FFmpeg/commit/d5a21172283572af587b3d939eba0091484d3263
|
| 173 |
+
if extradata and b"DivX" in extradata:
|
| 174 |
+
# can't use regex directly because of some weird characters sometimes...
|
| 175 |
+
pos = extradata.find(b"DivX")
|
| 176 |
+
d = extradata[pos:]
|
| 177 |
+
o = re.search(rb"DivX(\d+)Build(\d+)(\w)", d)
|
| 178 |
+
if o is None:
|
| 179 |
+
o = re.search(rb"DivX(\d+)b(\d+)(\w)", d)
|
| 180 |
+
if o is not None:
|
| 181 |
+
should_buffer = o.group(3) == b"p"
|
| 182 |
+
seek_offset = start_offset
|
| 183 |
+
# some files don't seek to the right location, so better be safe here
|
| 184 |
+
seek_offset = max(seek_offset - 1, 0)
|
| 185 |
+
if should_buffer:
|
| 186 |
+
# FIXME this is kind of a hack, but we will jump to the previous keyframe
|
| 187 |
+
# so this will be safe
|
| 188 |
+
seek_offset = max(seek_offset - max_buffer_size, 0)
|
| 189 |
+
try:
|
| 190 |
+
# TODO check if stream needs to always be the video stream here or not
|
| 191 |
+
container.seek(seek_offset, any_frame=False, backward=True, stream=stream)
|
| 192 |
+
except av.AVError:
|
| 193 |
+
# TODO add some warnings in this case
|
| 194 |
+
# print("Corrupted file?", container.name)
|
| 195 |
+
return []
|
| 196 |
+
buffer_count = 0
|
| 197 |
+
try:
|
| 198 |
+
for _idx, frame in enumerate(container.decode(**stream_name)):
|
| 199 |
+
frames[frame.pts] = frame
|
| 200 |
+
if frame.pts >= end_offset:
|
| 201 |
+
if should_buffer and buffer_count < max_buffer_size:
|
| 202 |
+
buffer_count += 1
|
| 203 |
+
continue
|
| 204 |
+
break
|
| 205 |
+
except av.AVError:
|
| 206 |
+
# TODO add a warning
|
| 207 |
+
pass
|
| 208 |
+
# ensure that the results are sorted wrt the pts
|
| 209 |
+
result = [frames[i] for i in sorted(frames) if start_offset <= frames[i].pts <= end_offset]
|
| 210 |
+
if len(frames) > 0 and start_offset > 0 and start_offset not in frames:
|
| 211 |
+
# if there is no frame that exactly matches the pts of start_offset
|
| 212 |
+
# add the last frame smaller than start_offset, to guarantee that
|
| 213 |
+
# we will have all the necessary data. This is most useful for audio
|
| 214 |
+
preceding_frames = [i for i in frames if i < start_offset]
|
| 215 |
+
if len(preceding_frames) > 0:
|
| 216 |
+
first_frame_pts = max(preceding_frames)
|
| 217 |
+
result.insert(0, frames[first_frame_pts])
|
| 218 |
+
return result
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _align_audio_frames(
|
| 222 |
+
aframes: torch.Tensor, audio_frames: List["av.frame.Frame"], ref_start: int, ref_end: float
|
| 223 |
+
) -> torch.Tensor:
|
| 224 |
+
start, end = audio_frames[0].pts, audio_frames[-1].pts
|
| 225 |
+
total_aframes = aframes.shape[1]
|
| 226 |
+
step_per_aframe = (end - start + 1) / total_aframes
|
| 227 |
+
s_idx = 0
|
| 228 |
+
e_idx = total_aframes
|
| 229 |
+
if start < ref_start:
|
| 230 |
+
s_idx = int((ref_start - start) / step_per_aframe)
|
| 231 |
+
if end > ref_end:
|
| 232 |
+
e_idx = int((ref_end - end) / step_per_aframe)
|
| 233 |
+
return aframes[:, s_idx:e_idx]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def read_video(
|
| 237 |
+
filename: str,
|
| 238 |
+
start_pts: Union[float, Fraction] = 0,
|
| 239 |
+
end_pts: Optional[Union[float, Fraction]] = None,
|
| 240 |
+
pts_unit: str = "pts",
|
| 241 |
+
output_format: str = "THWC",
|
| 242 |
+
) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, Any]]:
|
| 243 |
+
"""
|
| 244 |
+
Reads a video from a file, returning both the video frames and the audio frames
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
filename (str): path to the video file
|
| 248 |
+
start_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional):
|
| 249 |
+
The start presentation time of the video
|
| 250 |
+
end_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional):
|
| 251 |
+
The end presentation time
|
| 252 |
+
pts_unit (str, optional): unit in which start_pts and end_pts values will be interpreted,
|
| 253 |
+
either 'pts' or 'sec'. Defaults to 'pts'.
|
| 254 |
+
output_format (str, optional): The format of the output video tensors. Can be either "THWC" (default) or "TCHW".
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
vframes (Tensor[T, H, W, C] or Tensor[T, C, H, W]): the `T` video frames
|
| 258 |
+
aframes (Tensor[K, L]): the audio frames, where `K` is the number of channels and `L` is the number of points
|
| 259 |
+
info (Dict): metadata for the video and audio. Can contain the fields video_fps (float) and audio_fps (int)
|
| 260 |
+
"""
|
| 261 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 262 |
+
_log_api_usage_once(read_video)
|
| 263 |
+
|
| 264 |
+
output_format = output_format.upper()
|
| 265 |
+
if output_format not in ("THWC", "TCHW"):
|
| 266 |
+
raise ValueError(f"output_format should be either 'THWC' or 'TCHW', got {output_format}.")
|
| 267 |
+
|
| 268 |
+
from torchvision import get_video_backend
|
| 269 |
+
|
| 270 |
+
if not os.path.exists(filename):
|
| 271 |
+
raise RuntimeError(f"File not found: {filename}")
|
| 272 |
+
|
| 273 |
+
if get_video_backend() != "pyav":
|
| 274 |
+
vframes, aframes, info = _video_opt._read_video(filename, start_pts, end_pts, pts_unit)
|
| 275 |
+
else:
|
| 276 |
+
_check_av_available()
|
| 277 |
+
|
| 278 |
+
if end_pts is None:
|
| 279 |
+
end_pts = float("inf")
|
| 280 |
+
|
| 281 |
+
if end_pts < start_pts:
|
| 282 |
+
raise ValueError(
|
| 283 |
+
f"end_pts should be larger than start_pts, got start_pts={start_pts} and end_pts={end_pts}"
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
info = {}
|
| 287 |
+
video_frames = []
|
| 288 |
+
audio_frames = []
|
| 289 |
+
audio_timebase = _video_opt.default_timebase
|
| 290 |
+
|
| 291 |
+
try:
|
| 292 |
+
with av.open(filename, metadata_errors="ignore") as container:
|
| 293 |
+
if container.streams.audio:
|
| 294 |
+
audio_timebase = container.streams.audio[0].time_base
|
| 295 |
+
if container.streams.video:
|
| 296 |
+
video_frames = _read_from_stream(
|
| 297 |
+
container,
|
| 298 |
+
start_pts,
|
| 299 |
+
end_pts,
|
| 300 |
+
pts_unit,
|
| 301 |
+
container.streams.video[0],
|
| 302 |
+
{"video": 0},
|
| 303 |
+
)
|
| 304 |
+
video_fps = container.streams.video[0].average_rate
|
| 305 |
+
# guard against potentially corrupted files
|
| 306 |
+
if video_fps is not None:
|
| 307 |
+
info["video_fps"] = float(video_fps)
|
| 308 |
+
|
| 309 |
+
if container.streams.audio:
|
| 310 |
+
audio_frames = _read_from_stream(
|
| 311 |
+
container,
|
| 312 |
+
start_pts,
|
| 313 |
+
end_pts,
|
| 314 |
+
pts_unit,
|
| 315 |
+
container.streams.audio[0],
|
| 316 |
+
{"audio": 0},
|
| 317 |
+
)
|
| 318 |
+
info["audio_fps"] = container.streams.audio[0].rate
|
| 319 |
+
|
| 320 |
+
except av.AVError:
|
| 321 |
+
# TODO raise a warning?
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
vframes_list = [frame.to_rgb().to_ndarray() for frame in video_frames]
|
| 325 |
+
aframes_list = [frame.to_ndarray() for frame in audio_frames]
|
| 326 |
+
|
| 327 |
+
if vframes_list:
|
| 328 |
+
vframes = torch.as_tensor(np.stack(vframes_list))
|
| 329 |
+
else:
|
| 330 |
+
vframes = torch.empty((0, 1, 1, 3), dtype=torch.uint8)
|
| 331 |
+
|
| 332 |
+
if aframes_list:
|
| 333 |
+
aframes = np.concatenate(aframes_list, 1)
|
| 334 |
+
aframes = torch.as_tensor(aframes)
|
| 335 |
+
if pts_unit == "sec":
|
| 336 |
+
start_pts = int(math.floor(start_pts * (1 / audio_timebase)))
|
| 337 |
+
if end_pts != float("inf"):
|
| 338 |
+
end_pts = int(math.ceil(end_pts * (1 / audio_timebase)))
|
| 339 |
+
aframes = _align_audio_frames(aframes, audio_frames, start_pts, end_pts)
|
| 340 |
+
else:
|
| 341 |
+
aframes = torch.empty((1, 0), dtype=torch.float32)
|
| 342 |
+
|
| 343 |
+
if output_format == "TCHW":
|
| 344 |
+
# [T,H,W,C] --> [T,C,H,W]
|
| 345 |
+
vframes = vframes.permute(0, 3, 1, 2)
|
| 346 |
+
|
| 347 |
+
return vframes, aframes, info
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def _can_read_timestamps_from_packets(container: "av.container.Container") -> bool:
|
| 351 |
+
extradata = container.streams[0].codec_context.extradata
|
| 352 |
+
if extradata is None:
|
| 353 |
+
return False
|
| 354 |
+
if b"Lavc" in extradata:
|
| 355 |
+
return True
|
| 356 |
+
return False
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _decode_video_timestamps(container: "av.container.Container") -> List[int]:
|
| 360 |
+
if _can_read_timestamps_from_packets(container):
|
| 361 |
+
# fast path
|
| 362 |
+
return [x.pts for x in container.demux(video=0) if x.pts is not None]
|
| 363 |
+
else:
|
| 364 |
+
return [x.pts for x in container.decode(video=0) if x.pts is not None]
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def read_video_timestamps(filename: str, pts_unit: str = "pts") -> Tuple[List[int], Optional[float]]:
|
| 368 |
+
"""
|
| 369 |
+
List the video frames timestamps.
|
| 370 |
+
|
| 371 |
+
Note that the function decodes the whole video frame-by-frame.
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
filename (str): path to the video file
|
| 375 |
+
pts_unit (str, optional): unit in which timestamp values will be returned
|
| 376 |
+
either 'pts' or 'sec'. Defaults to 'pts'.
|
| 377 |
+
|
| 378 |
+
Returns:
|
| 379 |
+
pts (List[int] if pts_unit = 'pts', List[Fraction] if pts_unit = 'sec'):
|
| 380 |
+
presentation timestamps for each one of the frames in the video.
|
| 381 |
+
video_fps (float, optional): the frame rate for the video
|
| 382 |
+
|
| 383 |
+
"""
|
| 384 |
+
if not torch.jit.is_scripting() and not torch.jit.is_tracing():
|
| 385 |
+
_log_api_usage_once(read_video_timestamps)
|
| 386 |
+
from torchvision import get_video_backend
|
| 387 |
+
|
| 388 |
+
if get_video_backend() != "pyav":
|
| 389 |
+
return _video_opt._read_video_timestamps(filename, pts_unit)
|
| 390 |
+
|
| 391 |
+
_check_av_available()
|
| 392 |
+
|
| 393 |
+
video_fps = None
|
| 394 |
+
pts = []
|
| 395 |
+
|
| 396 |
+
try:
|
| 397 |
+
with av.open(filename, metadata_errors="ignore") as container:
|
| 398 |
+
if container.streams.video:
|
| 399 |
+
video_stream = container.streams.video[0]
|
| 400 |
+
video_time_base = video_stream.time_base
|
| 401 |
+
try:
|
| 402 |
+
pts = _decode_video_timestamps(container)
|
| 403 |
+
except av.AVError:
|
| 404 |
+
warnings.warn(f"Failed decoding frames for file {filename}")
|
| 405 |
+
video_fps = float(video_stream.average_rate)
|
| 406 |
+
except av.AVError as e:
|
| 407 |
+
msg = f"Failed to open container for {filename}; Caught error: {e}"
|
| 408 |
+
warnings.warn(msg, RuntimeWarning)
|
| 409 |
+
|
| 410 |
+
pts.sort()
|
| 411 |
+
|
| 412 |
+
if pts_unit == "sec":
|
| 413 |
+
pts = [x * video_time_base for x in pts]
|
| 414 |
+
|
| 415 |
+
return pts, video_fps
|
wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/_api.cpython-310.pyc
ADDED
|
Binary file (8.48 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/_meta.cpython-310.pyc
ADDED
|
Binary file (19.4 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/alexnet.cpython-310.pyc
ADDED
|
Binary file (4.37 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/feature_extraction.cpython-310.pyc
ADDED
|
Binary file (20.9 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/mnasnet.cpython-310.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/__pycache__/shufflenetv2.cpython-310.pyc
ADDED
|
Binary file (12.4 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/_meta.py
ADDED
|
@@ -0,0 +1,1554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file is part of the private API. Please do not refer to any variables defined here directly as they will be
|
| 3 |
+
removed on future versions without warning.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
# This will eventually be replaced with a call at torchvision.datasets.info("imagenet").categories
|
| 7 |
+
_IMAGENET_CATEGORIES = [
|
| 8 |
+
"tench",
|
| 9 |
+
"goldfish",
|
| 10 |
+
"great white shark",
|
| 11 |
+
"tiger shark",
|
| 12 |
+
"hammerhead",
|
| 13 |
+
"electric ray",
|
| 14 |
+
"stingray",
|
| 15 |
+
"cock",
|
| 16 |
+
"hen",
|
| 17 |
+
"ostrich",
|
| 18 |
+
"brambling",
|
| 19 |
+
"goldfinch",
|
| 20 |
+
"house finch",
|
| 21 |
+
"junco",
|
| 22 |
+
"indigo bunting",
|
| 23 |
+
"robin",
|
| 24 |
+
"bulbul",
|
| 25 |
+
"jay",
|
| 26 |
+
"magpie",
|
| 27 |
+
"chickadee",
|
| 28 |
+
"water ouzel",
|
| 29 |
+
"kite",
|
| 30 |
+
"bald eagle",
|
| 31 |
+
"vulture",
|
| 32 |
+
"great grey owl",
|
| 33 |
+
"European fire salamander",
|
| 34 |
+
"common newt",
|
| 35 |
+
"eft",
|
| 36 |
+
"spotted salamander",
|
| 37 |
+
"axolotl",
|
| 38 |
+
"bullfrog",
|
| 39 |
+
"tree frog",
|
| 40 |
+
"tailed frog",
|
| 41 |
+
"loggerhead",
|
| 42 |
+
"leatherback turtle",
|
| 43 |
+
"mud turtle",
|
| 44 |
+
"terrapin",
|
| 45 |
+
"box turtle",
|
| 46 |
+
"banded gecko",
|
| 47 |
+
"common iguana",
|
| 48 |
+
"American chameleon",
|
| 49 |
+
"whiptail",
|
| 50 |
+
"agama",
|
| 51 |
+
"frilled lizard",
|
| 52 |
+
"alligator lizard",
|
| 53 |
+
"Gila monster",
|
| 54 |
+
"green lizard",
|
| 55 |
+
"African chameleon",
|
| 56 |
+
"Komodo dragon",
|
| 57 |
+
"African crocodile",
|
| 58 |
+
"American alligator",
|
| 59 |
+
"triceratops",
|
| 60 |
+
"thunder snake",
|
| 61 |
+
"ringneck snake",
|
| 62 |
+
"hognose snake",
|
| 63 |
+
"green snake",
|
| 64 |
+
"king snake",
|
| 65 |
+
"garter snake",
|
| 66 |
+
"water snake",
|
| 67 |
+
"vine snake",
|
| 68 |
+
"night snake",
|
| 69 |
+
"boa constrictor",
|
| 70 |
+
"rock python",
|
| 71 |
+
"Indian cobra",
|
| 72 |
+
"green mamba",
|
| 73 |
+
"sea snake",
|
| 74 |
+
"horned viper",
|
| 75 |
+
"diamondback",
|
| 76 |
+
"sidewinder",
|
| 77 |
+
"trilobite",
|
| 78 |
+
"harvestman",
|
| 79 |
+
"scorpion",
|
| 80 |
+
"black and gold garden spider",
|
| 81 |
+
"barn spider",
|
| 82 |
+
"garden spider",
|
| 83 |
+
"black widow",
|
| 84 |
+
"tarantula",
|
| 85 |
+
"wolf spider",
|
| 86 |
+
"tick",
|
| 87 |
+
"centipede",
|
| 88 |
+
"black grouse",
|
| 89 |
+
"ptarmigan",
|
| 90 |
+
"ruffed grouse",
|
| 91 |
+
"prairie chicken",
|
| 92 |
+
"peacock",
|
| 93 |
+
"quail",
|
| 94 |
+
"partridge",
|
| 95 |
+
"African grey",
|
| 96 |
+
"macaw",
|
| 97 |
+
"sulphur-crested cockatoo",
|
| 98 |
+
"lorikeet",
|
| 99 |
+
"coucal",
|
| 100 |
+
"bee eater",
|
| 101 |
+
"hornbill",
|
| 102 |
+
"hummingbird",
|
| 103 |
+
"jacamar",
|
| 104 |
+
"toucan",
|
| 105 |
+
"drake",
|
| 106 |
+
"red-breasted merganser",
|
| 107 |
+
"goose",
|
| 108 |
+
"black swan",
|
| 109 |
+
"tusker",
|
| 110 |
+
"echidna",
|
| 111 |
+
"platypus",
|
| 112 |
+
"wallaby",
|
| 113 |
+
"koala",
|
| 114 |
+
"wombat",
|
| 115 |
+
"jellyfish",
|
| 116 |
+
"sea anemone",
|
| 117 |
+
"brain coral",
|
| 118 |
+
"flatworm",
|
| 119 |
+
"nematode",
|
| 120 |
+
"conch",
|
| 121 |
+
"snail",
|
| 122 |
+
"slug",
|
| 123 |
+
"sea slug",
|
| 124 |
+
"chiton",
|
| 125 |
+
"chambered nautilus",
|
| 126 |
+
"Dungeness crab",
|
| 127 |
+
"rock crab",
|
| 128 |
+
"fiddler crab",
|
| 129 |
+
"king crab",
|
| 130 |
+
"American lobster",
|
| 131 |
+
"spiny lobster",
|
| 132 |
+
"crayfish",
|
| 133 |
+
"hermit crab",
|
| 134 |
+
"isopod",
|
| 135 |
+
"white stork",
|
| 136 |
+
"black stork",
|
| 137 |
+
"spoonbill",
|
| 138 |
+
"flamingo",
|
| 139 |
+
"little blue heron",
|
| 140 |
+
"American egret",
|
| 141 |
+
"bittern",
|
| 142 |
+
"crane bird",
|
| 143 |
+
"limpkin",
|
| 144 |
+
"European gallinule",
|
| 145 |
+
"American coot",
|
| 146 |
+
"bustard",
|
| 147 |
+
"ruddy turnstone",
|
| 148 |
+
"red-backed sandpiper",
|
| 149 |
+
"redshank",
|
| 150 |
+
"dowitcher",
|
| 151 |
+
"oystercatcher",
|
| 152 |
+
"pelican",
|
| 153 |
+
"king penguin",
|
| 154 |
+
"albatross",
|
| 155 |
+
"grey whale",
|
| 156 |
+
"killer whale",
|
| 157 |
+
"dugong",
|
| 158 |
+
"sea lion",
|
| 159 |
+
"Chihuahua",
|
| 160 |
+
"Japanese spaniel",
|
| 161 |
+
"Maltese dog",
|
| 162 |
+
"Pekinese",
|
| 163 |
+
"Shih-Tzu",
|
| 164 |
+
"Blenheim spaniel",
|
| 165 |
+
"papillon",
|
| 166 |
+
"toy terrier",
|
| 167 |
+
"Rhodesian ridgeback",
|
| 168 |
+
"Afghan hound",
|
| 169 |
+
"basset",
|
| 170 |
+
"beagle",
|
| 171 |
+
"bloodhound",
|
| 172 |
+
"bluetick",
|
| 173 |
+
"black-and-tan coonhound",
|
| 174 |
+
"Walker hound",
|
| 175 |
+
"English foxhound",
|
| 176 |
+
"redbone",
|
| 177 |
+
"borzoi",
|
| 178 |
+
"Irish wolfhound",
|
| 179 |
+
"Italian greyhound",
|
| 180 |
+
"whippet",
|
| 181 |
+
"Ibizan hound",
|
| 182 |
+
"Norwegian elkhound",
|
| 183 |
+
"otterhound",
|
| 184 |
+
"Saluki",
|
| 185 |
+
"Scottish deerhound",
|
| 186 |
+
"Weimaraner",
|
| 187 |
+
"Staffordshire bullterrier",
|
| 188 |
+
"American Staffordshire terrier",
|
| 189 |
+
"Bedlington terrier",
|
| 190 |
+
"Border terrier",
|
| 191 |
+
"Kerry blue terrier",
|
| 192 |
+
"Irish terrier",
|
| 193 |
+
"Norfolk terrier",
|
| 194 |
+
"Norwich terrier",
|
| 195 |
+
"Yorkshire terrier",
|
| 196 |
+
"wire-haired fox terrier",
|
| 197 |
+
"Lakeland terrier",
|
| 198 |
+
"Sealyham terrier",
|
| 199 |
+
"Airedale",
|
| 200 |
+
"cairn",
|
| 201 |
+
"Australian terrier",
|
| 202 |
+
"Dandie Dinmont",
|
| 203 |
+
"Boston bull",
|
| 204 |
+
"miniature schnauzer",
|
| 205 |
+
"giant schnauzer",
|
| 206 |
+
"standard schnauzer",
|
| 207 |
+
"Scotch terrier",
|
| 208 |
+
"Tibetan terrier",
|
| 209 |
+
"silky terrier",
|
| 210 |
+
"soft-coated wheaten terrier",
|
| 211 |
+
"West Highland white terrier",
|
| 212 |
+
"Lhasa",
|
| 213 |
+
"flat-coated retriever",
|
| 214 |
+
"curly-coated retriever",
|
| 215 |
+
"golden retriever",
|
| 216 |
+
"Labrador retriever",
|
| 217 |
+
"Chesapeake Bay retriever",
|
| 218 |
+
"German short-haired pointer",
|
| 219 |
+
"vizsla",
|
| 220 |
+
"English setter",
|
| 221 |
+
"Irish setter",
|
| 222 |
+
"Gordon setter",
|
| 223 |
+
"Brittany spaniel",
|
| 224 |
+
"clumber",
|
| 225 |
+
"English springer",
|
| 226 |
+
"Welsh springer spaniel",
|
| 227 |
+
"cocker spaniel",
|
| 228 |
+
"Sussex spaniel",
|
| 229 |
+
"Irish water spaniel",
|
| 230 |
+
"kuvasz",
|
| 231 |
+
"schipperke",
|
| 232 |
+
"groenendael",
|
| 233 |
+
"malinois",
|
| 234 |
+
"briard",
|
| 235 |
+
"kelpie",
|
| 236 |
+
"komondor",
|
| 237 |
+
"Old English sheepdog",
|
| 238 |
+
"Shetland sheepdog",
|
| 239 |
+
"collie",
|
| 240 |
+
"Border collie",
|
| 241 |
+
"Bouvier des Flandres",
|
| 242 |
+
"Rottweiler",
|
| 243 |
+
"German shepherd",
|
| 244 |
+
"Doberman",
|
| 245 |
+
"miniature pinscher",
|
| 246 |
+
"Greater Swiss Mountain dog",
|
| 247 |
+
"Bernese mountain dog",
|
| 248 |
+
"Appenzeller",
|
| 249 |
+
"EntleBucher",
|
| 250 |
+
"boxer",
|
| 251 |
+
"bull mastiff",
|
| 252 |
+
"Tibetan mastiff",
|
| 253 |
+
"French bulldog",
|
| 254 |
+
"Great Dane",
|
| 255 |
+
"Saint Bernard",
|
| 256 |
+
"Eskimo dog",
|
| 257 |
+
"malamute",
|
| 258 |
+
"Siberian husky",
|
| 259 |
+
"dalmatian",
|
| 260 |
+
"affenpinscher",
|
| 261 |
+
"basenji",
|
| 262 |
+
"pug",
|
| 263 |
+
"Leonberg",
|
| 264 |
+
"Newfoundland",
|
| 265 |
+
"Great Pyrenees",
|
| 266 |
+
"Samoyed",
|
| 267 |
+
"Pomeranian",
|
| 268 |
+
"chow",
|
| 269 |
+
"keeshond",
|
| 270 |
+
"Brabancon griffon",
|
| 271 |
+
"Pembroke",
|
| 272 |
+
"Cardigan",
|
| 273 |
+
"toy poodle",
|
| 274 |
+
"miniature poodle",
|
| 275 |
+
"standard poodle",
|
| 276 |
+
"Mexican hairless",
|
| 277 |
+
"timber wolf",
|
| 278 |
+
"white wolf",
|
| 279 |
+
"red wolf",
|
| 280 |
+
"coyote",
|
| 281 |
+
"dingo",
|
| 282 |
+
"dhole",
|
| 283 |
+
"African hunting dog",
|
| 284 |
+
"hyena",
|
| 285 |
+
"red fox",
|
| 286 |
+
"kit fox",
|
| 287 |
+
"Arctic fox",
|
| 288 |
+
"grey fox",
|
| 289 |
+
"tabby",
|
| 290 |
+
"tiger cat",
|
| 291 |
+
"Persian cat",
|
| 292 |
+
"Siamese cat",
|
| 293 |
+
"Egyptian cat",
|
| 294 |
+
"cougar",
|
| 295 |
+
"lynx",
|
| 296 |
+
"leopard",
|
| 297 |
+
"snow leopard",
|
| 298 |
+
"jaguar",
|
| 299 |
+
"lion",
|
| 300 |
+
"tiger",
|
| 301 |
+
"cheetah",
|
| 302 |
+
"brown bear",
|
| 303 |
+
"American black bear",
|
| 304 |
+
"ice bear",
|
| 305 |
+
"sloth bear",
|
| 306 |
+
"mongoose",
|
| 307 |
+
"meerkat",
|
| 308 |
+
"tiger beetle",
|
| 309 |
+
"ladybug",
|
| 310 |
+
"ground beetle",
|
| 311 |
+
"long-horned beetle",
|
| 312 |
+
"leaf beetle",
|
| 313 |
+
"dung beetle",
|
| 314 |
+
"rhinoceros beetle",
|
| 315 |
+
"weevil",
|
| 316 |
+
"fly",
|
| 317 |
+
"bee",
|
| 318 |
+
"ant",
|
| 319 |
+
"grasshopper",
|
| 320 |
+
"cricket",
|
| 321 |
+
"walking stick",
|
| 322 |
+
"cockroach",
|
| 323 |
+
"mantis",
|
| 324 |
+
"cicada",
|
| 325 |
+
"leafhopper",
|
| 326 |
+
"lacewing",
|
| 327 |
+
"dragonfly",
|
| 328 |
+
"damselfly",
|
| 329 |
+
"admiral",
|
| 330 |
+
"ringlet",
|
| 331 |
+
"monarch",
|
| 332 |
+
"cabbage butterfly",
|
| 333 |
+
"sulphur butterfly",
|
| 334 |
+
"lycaenid",
|
| 335 |
+
"starfish",
|
| 336 |
+
"sea urchin",
|
| 337 |
+
"sea cucumber",
|
| 338 |
+
"wood rabbit",
|
| 339 |
+
"hare",
|
| 340 |
+
"Angora",
|
| 341 |
+
"hamster",
|
| 342 |
+
"porcupine",
|
| 343 |
+
"fox squirrel",
|
| 344 |
+
"marmot",
|
| 345 |
+
"beaver",
|
| 346 |
+
"guinea pig",
|
| 347 |
+
"sorrel",
|
| 348 |
+
"zebra",
|
| 349 |
+
"hog",
|
| 350 |
+
"wild boar",
|
| 351 |
+
"warthog",
|
| 352 |
+
"hippopotamus",
|
| 353 |
+
"ox",
|
| 354 |
+
"water buffalo",
|
| 355 |
+
"bison",
|
| 356 |
+
"ram",
|
| 357 |
+
"bighorn",
|
| 358 |
+
"ibex",
|
| 359 |
+
"hartebeest",
|
| 360 |
+
"impala",
|
| 361 |
+
"gazelle",
|
| 362 |
+
"Arabian camel",
|
| 363 |
+
"llama",
|
| 364 |
+
"weasel",
|
| 365 |
+
"mink",
|
| 366 |
+
"polecat",
|
| 367 |
+
"black-footed ferret",
|
| 368 |
+
"otter",
|
| 369 |
+
"skunk",
|
| 370 |
+
"badger",
|
| 371 |
+
"armadillo",
|
| 372 |
+
"three-toed sloth",
|
| 373 |
+
"orangutan",
|
| 374 |
+
"gorilla",
|
| 375 |
+
"chimpanzee",
|
| 376 |
+
"gibbon",
|
| 377 |
+
"siamang",
|
| 378 |
+
"guenon",
|
| 379 |
+
"patas",
|
| 380 |
+
"baboon",
|
| 381 |
+
"macaque",
|
| 382 |
+
"langur",
|
| 383 |
+
"colobus",
|
| 384 |
+
"proboscis monkey",
|
| 385 |
+
"marmoset",
|
| 386 |
+
"capuchin",
|
| 387 |
+
"howler monkey",
|
| 388 |
+
"titi",
|
| 389 |
+
"spider monkey",
|
| 390 |
+
"squirrel monkey",
|
| 391 |
+
"Madagascar cat",
|
| 392 |
+
"indri",
|
| 393 |
+
"Indian elephant",
|
| 394 |
+
"African elephant",
|
| 395 |
+
"lesser panda",
|
| 396 |
+
"giant panda",
|
| 397 |
+
"barracouta",
|
| 398 |
+
"eel",
|
| 399 |
+
"coho",
|
| 400 |
+
"rock beauty",
|
| 401 |
+
"anemone fish",
|
| 402 |
+
"sturgeon",
|
| 403 |
+
"gar",
|
| 404 |
+
"lionfish",
|
| 405 |
+
"puffer",
|
| 406 |
+
"abacus",
|
| 407 |
+
"abaya",
|
| 408 |
+
"academic gown",
|
| 409 |
+
"accordion",
|
| 410 |
+
"acoustic guitar",
|
| 411 |
+
"aircraft carrier",
|
| 412 |
+
"airliner",
|
| 413 |
+
"airship",
|
| 414 |
+
"altar",
|
| 415 |
+
"ambulance",
|
| 416 |
+
"amphibian",
|
| 417 |
+
"analog clock",
|
| 418 |
+
"apiary",
|
| 419 |
+
"apron",
|
| 420 |
+
"ashcan",
|
| 421 |
+
"assault rifle",
|
| 422 |
+
"backpack",
|
| 423 |
+
"bakery",
|
| 424 |
+
"balance beam",
|
| 425 |
+
"balloon",
|
| 426 |
+
"ballpoint",
|
| 427 |
+
"Band Aid",
|
| 428 |
+
"banjo",
|
| 429 |
+
"bannister",
|
| 430 |
+
"barbell",
|
| 431 |
+
"barber chair",
|
| 432 |
+
"barbershop",
|
| 433 |
+
"barn",
|
| 434 |
+
"barometer",
|
| 435 |
+
"barrel",
|
| 436 |
+
"barrow",
|
| 437 |
+
"baseball",
|
| 438 |
+
"basketball",
|
| 439 |
+
"bassinet",
|
| 440 |
+
"bassoon",
|
| 441 |
+
"bathing cap",
|
| 442 |
+
"bath towel",
|
| 443 |
+
"bathtub",
|
| 444 |
+
"beach wagon",
|
| 445 |
+
"beacon",
|
| 446 |
+
"beaker",
|
| 447 |
+
"bearskin",
|
| 448 |
+
"beer bottle",
|
| 449 |
+
"beer glass",
|
| 450 |
+
"bell cote",
|
| 451 |
+
"bib",
|
| 452 |
+
"bicycle-built-for-two",
|
| 453 |
+
"bikini",
|
| 454 |
+
"binder",
|
| 455 |
+
"binoculars",
|
| 456 |
+
"birdhouse",
|
| 457 |
+
"boathouse",
|
| 458 |
+
"bobsled",
|
| 459 |
+
"bolo tie",
|
| 460 |
+
"bonnet",
|
| 461 |
+
"bookcase",
|
| 462 |
+
"bookshop",
|
| 463 |
+
"bottlecap",
|
| 464 |
+
"bow",
|
| 465 |
+
"bow tie",
|
| 466 |
+
"brass",
|
| 467 |
+
"brassiere",
|
| 468 |
+
"breakwater",
|
| 469 |
+
"breastplate",
|
| 470 |
+
"broom",
|
| 471 |
+
"bucket",
|
| 472 |
+
"buckle",
|
| 473 |
+
"bulletproof vest",
|
| 474 |
+
"bullet train",
|
| 475 |
+
"butcher shop",
|
| 476 |
+
"cab",
|
| 477 |
+
"caldron",
|
| 478 |
+
"candle",
|
| 479 |
+
"cannon",
|
| 480 |
+
"canoe",
|
| 481 |
+
"can opener",
|
| 482 |
+
"cardigan",
|
| 483 |
+
"car mirror",
|
| 484 |
+
"carousel",
|
| 485 |
+
"carpenter's kit",
|
| 486 |
+
"carton",
|
| 487 |
+
"car wheel",
|
| 488 |
+
"cash machine",
|
| 489 |
+
"cassette",
|
| 490 |
+
"cassette player",
|
| 491 |
+
"castle",
|
| 492 |
+
"catamaran",
|
| 493 |
+
"CD player",
|
| 494 |
+
"cello",
|
| 495 |
+
"cellular telephone",
|
| 496 |
+
"chain",
|
| 497 |
+
"chainlink fence",
|
| 498 |
+
"chain mail",
|
| 499 |
+
"chain saw",
|
| 500 |
+
"chest",
|
| 501 |
+
"chiffonier",
|
| 502 |
+
"chime",
|
| 503 |
+
"china cabinet",
|
| 504 |
+
"Christmas stocking",
|
| 505 |
+
"church",
|
| 506 |
+
"cinema",
|
| 507 |
+
"cleaver",
|
| 508 |
+
"cliff dwelling",
|
| 509 |
+
"cloak",
|
| 510 |
+
"clog",
|
| 511 |
+
"cocktail shaker",
|
| 512 |
+
"coffee mug",
|
| 513 |
+
"coffeepot",
|
| 514 |
+
"coil",
|
| 515 |
+
"combination lock",
|
| 516 |
+
"computer keyboard",
|
| 517 |
+
"confectionery",
|
| 518 |
+
"container ship",
|
| 519 |
+
"convertible",
|
| 520 |
+
"corkscrew",
|
| 521 |
+
"cornet",
|
| 522 |
+
"cowboy boot",
|
| 523 |
+
"cowboy hat",
|
| 524 |
+
"cradle",
|
| 525 |
+
"crane",
|
| 526 |
+
"crash helmet",
|
| 527 |
+
"crate",
|
| 528 |
+
"crib",
|
| 529 |
+
"Crock Pot",
|
| 530 |
+
"croquet ball",
|
| 531 |
+
"crutch",
|
| 532 |
+
"cuirass",
|
| 533 |
+
"dam",
|
| 534 |
+
"desk",
|
| 535 |
+
"desktop computer",
|
| 536 |
+
"dial telephone",
|
| 537 |
+
"diaper",
|
| 538 |
+
"digital clock",
|
| 539 |
+
"digital watch",
|
| 540 |
+
"dining table",
|
| 541 |
+
"dishrag",
|
| 542 |
+
"dishwasher",
|
| 543 |
+
"disk brake",
|
| 544 |
+
"dock",
|
| 545 |
+
"dogsled",
|
| 546 |
+
"dome",
|
| 547 |
+
"doormat",
|
| 548 |
+
"drilling platform",
|
| 549 |
+
"drum",
|
| 550 |
+
"drumstick",
|
| 551 |
+
"dumbbell",
|
| 552 |
+
"Dutch oven",
|
| 553 |
+
"electric fan",
|
| 554 |
+
"electric guitar",
|
| 555 |
+
"electric locomotive",
|
| 556 |
+
"entertainment center",
|
| 557 |
+
"envelope",
|
| 558 |
+
"espresso maker",
|
| 559 |
+
"face powder",
|
| 560 |
+
"feather boa",
|
| 561 |
+
"file",
|
| 562 |
+
"fireboat",
|
| 563 |
+
"fire engine",
|
| 564 |
+
"fire screen",
|
| 565 |
+
"flagpole",
|
| 566 |
+
"flute",
|
| 567 |
+
"folding chair",
|
| 568 |
+
"football helmet",
|
| 569 |
+
"forklift",
|
| 570 |
+
"fountain",
|
| 571 |
+
"fountain pen",
|
| 572 |
+
"four-poster",
|
| 573 |
+
"freight car",
|
| 574 |
+
"French horn",
|
| 575 |
+
"frying pan",
|
| 576 |
+
"fur coat",
|
| 577 |
+
"garbage truck",
|
| 578 |
+
"gasmask",
|
| 579 |
+
"gas pump",
|
| 580 |
+
"goblet",
|
| 581 |
+
"go-kart",
|
| 582 |
+
"golf ball",
|
| 583 |
+
"golfcart",
|
| 584 |
+
"gondola",
|
| 585 |
+
"gong",
|
| 586 |
+
"gown",
|
| 587 |
+
"grand piano",
|
| 588 |
+
"greenhouse",
|
| 589 |
+
"grille",
|
| 590 |
+
"grocery store",
|
| 591 |
+
"guillotine",
|
| 592 |
+
"hair slide",
|
| 593 |
+
"hair spray",
|
| 594 |
+
"half track",
|
| 595 |
+
"hammer",
|
| 596 |
+
"hamper",
|
| 597 |
+
"hand blower",
|
| 598 |
+
"hand-held computer",
|
| 599 |
+
"handkerchief",
|
| 600 |
+
"hard disc",
|
| 601 |
+
"harmonica",
|
| 602 |
+
"harp",
|
| 603 |
+
"harvester",
|
| 604 |
+
"hatchet",
|
| 605 |
+
"holster",
|
| 606 |
+
"home theater",
|
| 607 |
+
"honeycomb",
|
| 608 |
+
"hook",
|
| 609 |
+
"hoopskirt",
|
| 610 |
+
"horizontal bar",
|
| 611 |
+
"horse cart",
|
| 612 |
+
"hourglass",
|
| 613 |
+
"iPod",
|
| 614 |
+
"iron",
|
| 615 |
+
"jack-o'-lantern",
|
| 616 |
+
"jean",
|
| 617 |
+
"jeep",
|
| 618 |
+
"jersey",
|
| 619 |
+
"jigsaw puzzle",
|
| 620 |
+
"jinrikisha",
|
| 621 |
+
"joystick",
|
| 622 |
+
"kimono",
|
| 623 |
+
"knee pad",
|
| 624 |
+
"knot",
|
| 625 |
+
"lab coat",
|
| 626 |
+
"ladle",
|
| 627 |
+
"lampshade",
|
| 628 |
+
"laptop",
|
| 629 |
+
"lawn mower",
|
| 630 |
+
"lens cap",
|
| 631 |
+
"letter opener",
|
| 632 |
+
"library",
|
| 633 |
+
"lifeboat",
|
| 634 |
+
"lighter",
|
| 635 |
+
"limousine",
|
| 636 |
+
"liner",
|
| 637 |
+
"lipstick",
|
| 638 |
+
"Loafer",
|
| 639 |
+
"lotion",
|
| 640 |
+
"loudspeaker",
|
| 641 |
+
"loupe",
|
| 642 |
+
"lumbermill",
|
| 643 |
+
"magnetic compass",
|
| 644 |
+
"mailbag",
|
| 645 |
+
"mailbox",
|
| 646 |
+
"maillot",
|
| 647 |
+
"maillot tank suit",
|
| 648 |
+
"manhole cover",
|
| 649 |
+
"maraca",
|
| 650 |
+
"marimba",
|
| 651 |
+
"mask",
|
| 652 |
+
"matchstick",
|
| 653 |
+
"maypole",
|
| 654 |
+
"maze",
|
| 655 |
+
"measuring cup",
|
| 656 |
+
"medicine chest",
|
| 657 |
+
"megalith",
|
| 658 |
+
"microphone",
|
| 659 |
+
"microwave",
|
| 660 |
+
"military uniform",
|
| 661 |
+
"milk can",
|
| 662 |
+
"minibus",
|
| 663 |
+
"miniskirt",
|
| 664 |
+
"minivan",
|
| 665 |
+
"missile",
|
| 666 |
+
"mitten",
|
| 667 |
+
"mixing bowl",
|
| 668 |
+
"mobile home",
|
| 669 |
+
"Model T",
|
| 670 |
+
"modem",
|
| 671 |
+
"monastery",
|
| 672 |
+
"monitor",
|
| 673 |
+
"moped",
|
| 674 |
+
"mortar",
|
| 675 |
+
"mortarboard",
|
| 676 |
+
"mosque",
|
| 677 |
+
"mosquito net",
|
| 678 |
+
"motor scooter",
|
| 679 |
+
"mountain bike",
|
| 680 |
+
"mountain tent",
|
| 681 |
+
"mouse",
|
| 682 |
+
"mousetrap",
|
| 683 |
+
"moving van",
|
| 684 |
+
"muzzle",
|
| 685 |
+
"nail",
|
| 686 |
+
"neck brace",
|
| 687 |
+
"necklace",
|
| 688 |
+
"nipple",
|
| 689 |
+
"notebook",
|
| 690 |
+
"obelisk",
|
| 691 |
+
"oboe",
|
| 692 |
+
"ocarina",
|
| 693 |
+
"odometer",
|
| 694 |
+
"oil filter",
|
| 695 |
+
"organ",
|
| 696 |
+
"oscilloscope",
|
| 697 |
+
"overskirt",
|
| 698 |
+
"oxcart",
|
| 699 |
+
"oxygen mask",
|
| 700 |
+
"packet",
|
| 701 |
+
"paddle",
|
| 702 |
+
"paddlewheel",
|
| 703 |
+
"padlock",
|
| 704 |
+
"paintbrush",
|
| 705 |
+
"pajama",
|
| 706 |
+
"palace",
|
| 707 |
+
"panpipe",
|
| 708 |
+
"paper towel",
|
| 709 |
+
"parachute",
|
| 710 |
+
"parallel bars",
|
| 711 |
+
"park bench",
|
| 712 |
+
"parking meter",
|
| 713 |
+
"passenger car",
|
| 714 |
+
"patio",
|
| 715 |
+
"pay-phone",
|
| 716 |
+
"pedestal",
|
| 717 |
+
"pencil box",
|
| 718 |
+
"pencil sharpener",
|
| 719 |
+
"perfume",
|
| 720 |
+
"Petri dish",
|
| 721 |
+
"photocopier",
|
| 722 |
+
"pick",
|
| 723 |
+
"pickelhaube",
|
| 724 |
+
"picket fence",
|
| 725 |
+
"pickup",
|
| 726 |
+
"pier",
|
| 727 |
+
"piggy bank",
|
| 728 |
+
"pill bottle",
|
| 729 |
+
"pillow",
|
| 730 |
+
"ping-pong ball",
|
| 731 |
+
"pinwheel",
|
| 732 |
+
"pirate",
|
| 733 |
+
"pitcher",
|
| 734 |
+
"plane",
|
| 735 |
+
"planetarium",
|
| 736 |
+
"plastic bag",
|
| 737 |
+
"plate rack",
|
| 738 |
+
"plow",
|
| 739 |
+
"plunger",
|
| 740 |
+
"Polaroid camera",
|
| 741 |
+
"pole",
|
| 742 |
+
"police van",
|
| 743 |
+
"poncho",
|
| 744 |
+
"pool table",
|
| 745 |
+
"pop bottle",
|
| 746 |
+
"pot",
|
| 747 |
+
"potter's wheel",
|
| 748 |
+
"power drill",
|
| 749 |
+
"prayer rug",
|
| 750 |
+
"printer",
|
| 751 |
+
"prison",
|
| 752 |
+
"projectile",
|
| 753 |
+
"projector",
|
| 754 |
+
"puck",
|
| 755 |
+
"punching bag",
|
| 756 |
+
"purse",
|
| 757 |
+
"quill",
|
| 758 |
+
"quilt",
|
| 759 |
+
"racer",
|
| 760 |
+
"racket",
|
| 761 |
+
"radiator",
|
| 762 |
+
"radio",
|
| 763 |
+
"radio telescope",
|
| 764 |
+
"rain barrel",
|
| 765 |
+
"recreational vehicle",
|
| 766 |
+
"reel",
|
| 767 |
+
"reflex camera",
|
| 768 |
+
"refrigerator",
|
| 769 |
+
"remote control",
|
| 770 |
+
"restaurant",
|
| 771 |
+
"revolver",
|
| 772 |
+
"rifle",
|
| 773 |
+
"rocking chair",
|
| 774 |
+
"rotisserie",
|
| 775 |
+
"rubber eraser",
|
| 776 |
+
"rugby ball",
|
| 777 |
+
"rule",
|
| 778 |
+
"running shoe",
|
| 779 |
+
"safe",
|
| 780 |
+
"safety pin",
|
| 781 |
+
"saltshaker",
|
| 782 |
+
"sandal",
|
| 783 |
+
"sarong",
|
| 784 |
+
"sax",
|
| 785 |
+
"scabbard",
|
| 786 |
+
"scale",
|
| 787 |
+
"school bus",
|
| 788 |
+
"schooner",
|
| 789 |
+
"scoreboard",
|
| 790 |
+
"screen",
|
| 791 |
+
"screw",
|
| 792 |
+
"screwdriver",
|
| 793 |
+
"seat belt",
|
| 794 |
+
"sewing machine",
|
| 795 |
+
"shield",
|
| 796 |
+
"shoe shop",
|
| 797 |
+
"shoji",
|
| 798 |
+
"shopping basket",
|
| 799 |
+
"shopping cart",
|
| 800 |
+
"shovel",
|
| 801 |
+
"shower cap",
|
| 802 |
+
"shower curtain",
|
| 803 |
+
"ski",
|
| 804 |
+
"ski mask",
|
| 805 |
+
"sleeping bag",
|
| 806 |
+
"slide rule",
|
| 807 |
+
"sliding door",
|
| 808 |
+
"slot",
|
| 809 |
+
"snorkel",
|
| 810 |
+
"snowmobile",
|
| 811 |
+
"snowplow",
|
| 812 |
+
"soap dispenser",
|
| 813 |
+
"soccer ball",
|
| 814 |
+
"sock",
|
| 815 |
+
"solar dish",
|
| 816 |
+
"sombrero",
|
| 817 |
+
"soup bowl",
|
| 818 |
+
"space bar",
|
| 819 |
+
"space heater",
|
| 820 |
+
"space shuttle",
|
| 821 |
+
"spatula",
|
| 822 |
+
"speedboat",
|
| 823 |
+
"spider web",
|
| 824 |
+
"spindle",
|
| 825 |
+
"sports car",
|
| 826 |
+
"spotlight",
|
| 827 |
+
"stage",
|
| 828 |
+
"steam locomotive",
|
| 829 |
+
"steel arch bridge",
|
| 830 |
+
"steel drum",
|
| 831 |
+
"stethoscope",
|
| 832 |
+
"stole",
|
| 833 |
+
"stone wall",
|
| 834 |
+
"stopwatch",
|
| 835 |
+
"stove",
|
| 836 |
+
"strainer",
|
| 837 |
+
"streetcar",
|
| 838 |
+
"stretcher",
|
| 839 |
+
"studio couch",
|
| 840 |
+
"stupa",
|
| 841 |
+
"submarine",
|
| 842 |
+
"suit",
|
| 843 |
+
"sundial",
|
| 844 |
+
"sunglass",
|
| 845 |
+
"sunglasses",
|
| 846 |
+
"sunscreen",
|
| 847 |
+
"suspension bridge",
|
| 848 |
+
"swab",
|
| 849 |
+
"sweatshirt",
|
| 850 |
+
"swimming trunks",
|
| 851 |
+
"swing",
|
| 852 |
+
"switch",
|
| 853 |
+
"syringe",
|
| 854 |
+
"table lamp",
|
| 855 |
+
"tank",
|
| 856 |
+
"tape player",
|
| 857 |
+
"teapot",
|
| 858 |
+
"teddy",
|
| 859 |
+
"television",
|
| 860 |
+
"tennis ball",
|
| 861 |
+
"thatch",
|
| 862 |
+
"theater curtain",
|
| 863 |
+
"thimble",
|
| 864 |
+
"thresher",
|
| 865 |
+
"throne",
|
| 866 |
+
"tile roof",
|
| 867 |
+
"toaster",
|
| 868 |
+
"tobacco shop",
|
| 869 |
+
"toilet seat",
|
| 870 |
+
"torch",
|
| 871 |
+
"totem pole",
|
| 872 |
+
"tow truck",
|
| 873 |
+
"toyshop",
|
| 874 |
+
"tractor",
|
| 875 |
+
"trailer truck",
|
| 876 |
+
"tray",
|
| 877 |
+
"trench coat",
|
| 878 |
+
"tricycle",
|
| 879 |
+
"trimaran",
|
| 880 |
+
"tripod",
|
| 881 |
+
"triumphal arch",
|
| 882 |
+
"trolleybus",
|
| 883 |
+
"trombone",
|
| 884 |
+
"tub",
|
| 885 |
+
"turnstile",
|
| 886 |
+
"typewriter keyboard",
|
| 887 |
+
"umbrella",
|
| 888 |
+
"unicycle",
|
| 889 |
+
"upright",
|
| 890 |
+
"vacuum",
|
| 891 |
+
"vase",
|
| 892 |
+
"vault",
|
| 893 |
+
"velvet",
|
| 894 |
+
"vending machine",
|
| 895 |
+
"vestment",
|
| 896 |
+
"viaduct",
|
| 897 |
+
"violin",
|
| 898 |
+
"volleyball",
|
| 899 |
+
"waffle iron",
|
| 900 |
+
"wall clock",
|
| 901 |
+
"wallet",
|
| 902 |
+
"wardrobe",
|
| 903 |
+
"warplane",
|
| 904 |
+
"washbasin",
|
| 905 |
+
"washer",
|
| 906 |
+
"water bottle",
|
| 907 |
+
"water jug",
|
| 908 |
+
"water tower",
|
| 909 |
+
"whiskey jug",
|
| 910 |
+
"whistle",
|
| 911 |
+
"wig",
|
| 912 |
+
"window screen",
|
| 913 |
+
"window shade",
|
| 914 |
+
"Windsor tie",
|
| 915 |
+
"wine bottle",
|
| 916 |
+
"wing",
|
| 917 |
+
"wok",
|
| 918 |
+
"wooden spoon",
|
| 919 |
+
"wool",
|
| 920 |
+
"worm fence",
|
| 921 |
+
"wreck",
|
| 922 |
+
"yawl",
|
| 923 |
+
"yurt",
|
| 924 |
+
"web site",
|
| 925 |
+
"comic book",
|
| 926 |
+
"crossword puzzle",
|
| 927 |
+
"street sign",
|
| 928 |
+
"traffic light",
|
| 929 |
+
"book jacket",
|
| 930 |
+
"menu",
|
| 931 |
+
"plate",
|
| 932 |
+
"guacamole",
|
| 933 |
+
"consomme",
|
| 934 |
+
"hot pot",
|
| 935 |
+
"trifle",
|
| 936 |
+
"ice cream",
|
| 937 |
+
"ice lolly",
|
| 938 |
+
"French loaf",
|
| 939 |
+
"bagel",
|
| 940 |
+
"pretzel",
|
| 941 |
+
"cheeseburger",
|
| 942 |
+
"hotdog",
|
| 943 |
+
"mashed potato",
|
| 944 |
+
"head cabbage",
|
| 945 |
+
"broccoli",
|
| 946 |
+
"cauliflower",
|
| 947 |
+
"zucchini",
|
| 948 |
+
"spaghetti squash",
|
| 949 |
+
"acorn squash",
|
| 950 |
+
"butternut squash",
|
| 951 |
+
"cucumber",
|
| 952 |
+
"artichoke",
|
| 953 |
+
"bell pepper",
|
| 954 |
+
"cardoon",
|
| 955 |
+
"mushroom",
|
| 956 |
+
"Granny Smith",
|
| 957 |
+
"strawberry",
|
| 958 |
+
"orange",
|
| 959 |
+
"lemon",
|
| 960 |
+
"fig",
|
| 961 |
+
"pineapple",
|
| 962 |
+
"banana",
|
| 963 |
+
"jackfruit",
|
| 964 |
+
"custard apple",
|
| 965 |
+
"pomegranate",
|
| 966 |
+
"hay",
|
| 967 |
+
"carbonara",
|
| 968 |
+
"chocolate sauce",
|
| 969 |
+
"dough",
|
| 970 |
+
"meat loaf",
|
| 971 |
+
"pizza",
|
| 972 |
+
"potpie",
|
| 973 |
+
"burrito",
|
| 974 |
+
"red wine",
|
| 975 |
+
"espresso",
|
| 976 |
+
"cup",
|
| 977 |
+
"eggnog",
|
| 978 |
+
"alp",
|
| 979 |
+
"bubble",
|
| 980 |
+
"cliff",
|
| 981 |
+
"coral reef",
|
| 982 |
+
"geyser",
|
| 983 |
+
"lakeside",
|
| 984 |
+
"promontory",
|
| 985 |
+
"sandbar",
|
| 986 |
+
"seashore",
|
| 987 |
+
"valley",
|
| 988 |
+
"volcano",
|
| 989 |
+
"ballplayer",
|
| 990 |
+
"groom",
|
| 991 |
+
"scuba diver",
|
| 992 |
+
"rapeseed",
|
| 993 |
+
"daisy",
|
| 994 |
+
"yellow lady's slipper",
|
| 995 |
+
"corn",
|
| 996 |
+
"acorn",
|
| 997 |
+
"hip",
|
| 998 |
+
"buckeye",
|
| 999 |
+
"coral fungus",
|
| 1000 |
+
"agaric",
|
| 1001 |
+
"gyromitra",
|
| 1002 |
+
"stinkhorn",
|
| 1003 |
+
"earthstar",
|
| 1004 |
+
"hen-of-the-woods",
|
| 1005 |
+
"bolete",
|
| 1006 |
+
"ear",
|
| 1007 |
+
"toilet tissue",
|
| 1008 |
+
]
|
| 1009 |
+
|
| 1010 |
+
# To be replaced with torchvision.datasets.info("coco").categories
|
| 1011 |
+
_COCO_CATEGORIES = [
|
| 1012 |
+
"__background__",
|
| 1013 |
+
"person",
|
| 1014 |
+
"bicycle",
|
| 1015 |
+
"car",
|
| 1016 |
+
"motorcycle",
|
| 1017 |
+
"airplane",
|
| 1018 |
+
"bus",
|
| 1019 |
+
"train",
|
| 1020 |
+
"truck",
|
| 1021 |
+
"boat",
|
| 1022 |
+
"traffic light",
|
| 1023 |
+
"fire hydrant",
|
| 1024 |
+
"N/A",
|
| 1025 |
+
"stop sign",
|
| 1026 |
+
"parking meter",
|
| 1027 |
+
"bench",
|
| 1028 |
+
"bird",
|
| 1029 |
+
"cat",
|
| 1030 |
+
"dog",
|
| 1031 |
+
"horse",
|
| 1032 |
+
"sheep",
|
| 1033 |
+
"cow",
|
| 1034 |
+
"elephant",
|
| 1035 |
+
"bear",
|
| 1036 |
+
"zebra",
|
| 1037 |
+
"giraffe",
|
| 1038 |
+
"N/A",
|
| 1039 |
+
"backpack",
|
| 1040 |
+
"umbrella",
|
| 1041 |
+
"N/A",
|
| 1042 |
+
"N/A",
|
| 1043 |
+
"handbag",
|
| 1044 |
+
"tie",
|
| 1045 |
+
"suitcase",
|
| 1046 |
+
"frisbee",
|
| 1047 |
+
"skis",
|
| 1048 |
+
"snowboard",
|
| 1049 |
+
"sports ball",
|
| 1050 |
+
"kite",
|
| 1051 |
+
"baseball bat",
|
| 1052 |
+
"baseball glove",
|
| 1053 |
+
"skateboard",
|
| 1054 |
+
"surfboard",
|
| 1055 |
+
"tennis racket",
|
| 1056 |
+
"bottle",
|
| 1057 |
+
"N/A",
|
| 1058 |
+
"wine glass",
|
| 1059 |
+
"cup",
|
| 1060 |
+
"fork",
|
| 1061 |
+
"knife",
|
| 1062 |
+
"spoon",
|
| 1063 |
+
"bowl",
|
| 1064 |
+
"banana",
|
| 1065 |
+
"apple",
|
| 1066 |
+
"sandwich",
|
| 1067 |
+
"orange",
|
| 1068 |
+
"broccoli",
|
| 1069 |
+
"carrot",
|
| 1070 |
+
"hot dog",
|
| 1071 |
+
"pizza",
|
| 1072 |
+
"donut",
|
| 1073 |
+
"cake",
|
| 1074 |
+
"chair",
|
| 1075 |
+
"couch",
|
| 1076 |
+
"potted plant",
|
| 1077 |
+
"bed",
|
| 1078 |
+
"N/A",
|
| 1079 |
+
"dining table",
|
| 1080 |
+
"N/A",
|
| 1081 |
+
"N/A",
|
| 1082 |
+
"toilet",
|
| 1083 |
+
"N/A",
|
| 1084 |
+
"tv",
|
| 1085 |
+
"laptop",
|
| 1086 |
+
"mouse",
|
| 1087 |
+
"remote",
|
| 1088 |
+
"keyboard",
|
| 1089 |
+
"cell phone",
|
| 1090 |
+
"microwave",
|
| 1091 |
+
"oven",
|
| 1092 |
+
"toaster",
|
| 1093 |
+
"sink",
|
| 1094 |
+
"refrigerator",
|
| 1095 |
+
"N/A",
|
| 1096 |
+
"book",
|
| 1097 |
+
"clock",
|
| 1098 |
+
"vase",
|
| 1099 |
+
"scissors",
|
| 1100 |
+
"teddy bear",
|
| 1101 |
+
"hair drier",
|
| 1102 |
+
"toothbrush",
|
| 1103 |
+
]
|
| 1104 |
+
|
| 1105 |
+
# To be replaced with torchvision.datasets.info("coco_kp")
|
| 1106 |
+
_COCO_PERSON_CATEGORIES = ["no person", "person"]
|
| 1107 |
+
_COCO_PERSON_KEYPOINT_NAMES = [
|
| 1108 |
+
"nose",
|
| 1109 |
+
"left_eye",
|
| 1110 |
+
"right_eye",
|
| 1111 |
+
"left_ear",
|
| 1112 |
+
"right_ear",
|
| 1113 |
+
"left_shoulder",
|
| 1114 |
+
"right_shoulder",
|
| 1115 |
+
"left_elbow",
|
| 1116 |
+
"right_elbow",
|
| 1117 |
+
"left_wrist",
|
| 1118 |
+
"right_wrist",
|
| 1119 |
+
"left_hip",
|
| 1120 |
+
"right_hip",
|
| 1121 |
+
"left_knee",
|
| 1122 |
+
"right_knee",
|
| 1123 |
+
"left_ankle",
|
| 1124 |
+
"right_ankle",
|
| 1125 |
+
]
|
| 1126 |
+
|
| 1127 |
+
# To be replaced with torchvision.datasets.info("voc").categories
|
| 1128 |
+
_VOC_CATEGORIES = [
|
| 1129 |
+
"__background__",
|
| 1130 |
+
"aeroplane",
|
| 1131 |
+
"bicycle",
|
| 1132 |
+
"bird",
|
| 1133 |
+
"boat",
|
| 1134 |
+
"bottle",
|
| 1135 |
+
"bus",
|
| 1136 |
+
"car",
|
| 1137 |
+
"cat",
|
| 1138 |
+
"chair",
|
| 1139 |
+
"cow",
|
| 1140 |
+
"diningtable",
|
| 1141 |
+
"dog",
|
| 1142 |
+
"horse",
|
| 1143 |
+
"motorbike",
|
| 1144 |
+
"person",
|
| 1145 |
+
"pottedplant",
|
| 1146 |
+
"sheep",
|
| 1147 |
+
"sofa",
|
| 1148 |
+
"train",
|
| 1149 |
+
"tvmonitor",
|
| 1150 |
+
]
|
| 1151 |
+
|
| 1152 |
+
# To be replaced with torchvision.datasets.info("kinetics400").categories
|
| 1153 |
+
_KINETICS400_CATEGORIES = [
|
| 1154 |
+
"abseiling",
|
| 1155 |
+
"air drumming",
|
| 1156 |
+
"answering questions",
|
| 1157 |
+
"applauding",
|
| 1158 |
+
"applying cream",
|
| 1159 |
+
"archery",
|
| 1160 |
+
"arm wrestling",
|
| 1161 |
+
"arranging flowers",
|
| 1162 |
+
"assembling computer",
|
| 1163 |
+
"auctioning",
|
| 1164 |
+
"baby waking up",
|
| 1165 |
+
"baking cookies",
|
| 1166 |
+
"balloon blowing",
|
| 1167 |
+
"bandaging",
|
| 1168 |
+
"barbequing",
|
| 1169 |
+
"bartending",
|
| 1170 |
+
"beatboxing",
|
| 1171 |
+
"bee keeping",
|
| 1172 |
+
"belly dancing",
|
| 1173 |
+
"bench pressing",
|
| 1174 |
+
"bending back",
|
| 1175 |
+
"bending metal",
|
| 1176 |
+
"biking through snow",
|
| 1177 |
+
"blasting sand",
|
| 1178 |
+
"blowing glass",
|
| 1179 |
+
"blowing leaves",
|
| 1180 |
+
"blowing nose",
|
| 1181 |
+
"blowing out candles",
|
| 1182 |
+
"bobsledding",
|
| 1183 |
+
"bookbinding",
|
| 1184 |
+
"bouncing on trampoline",
|
| 1185 |
+
"bowling",
|
| 1186 |
+
"braiding hair",
|
| 1187 |
+
"breading or breadcrumbing",
|
| 1188 |
+
"breakdancing",
|
| 1189 |
+
"brush painting",
|
| 1190 |
+
"brushing hair",
|
| 1191 |
+
"brushing teeth",
|
| 1192 |
+
"building cabinet",
|
| 1193 |
+
"building shed",
|
| 1194 |
+
"bungee jumping",
|
| 1195 |
+
"busking",
|
| 1196 |
+
"canoeing or kayaking",
|
| 1197 |
+
"capoeira",
|
| 1198 |
+
"carrying baby",
|
| 1199 |
+
"cartwheeling",
|
| 1200 |
+
"carving pumpkin",
|
| 1201 |
+
"catching fish",
|
| 1202 |
+
"catching or throwing baseball",
|
| 1203 |
+
"catching or throwing frisbee",
|
| 1204 |
+
"catching or throwing softball",
|
| 1205 |
+
"celebrating",
|
| 1206 |
+
"changing oil",
|
| 1207 |
+
"changing wheel",
|
| 1208 |
+
"checking tires",
|
| 1209 |
+
"cheerleading",
|
| 1210 |
+
"chopping wood",
|
| 1211 |
+
"clapping",
|
| 1212 |
+
"clay pottery making",
|
| 1213 |
+
"clean and jerk",
|
| 1214 |
+
"cleaning floor",
|
| 1215 |
+
"cleaning gutters",
|
| 1216 |
+
"cleaning pool",
|
| 1217 |
+
"cleaning shoes",
|
| 1218 |
+
"cleaning toilet",
|
| 1219 |
+
"cleaning windows",
|
| 1220 |
+
"climbing a rope",
|
| 1221 |
+
"climbing ladder",
|
| 1222 |
+
"climbing tree",
|
| 1223 |
+
"contact juggling",
|
| 1224 |
+
"cooking chicken",
|
| 1225 |
+
"cooking egg",
|
| 1226 |
+
"cooking on campfire",
|
| 1227 |
+
"cooking sausages",
|
| 1228 |
+
"counting money",
|
| 1229 |
+
"country line dancing",
|
| 1230 |
+
"cracking neck",
|
| 1231 |
+
"crawling baby",
|
| 1232 |
+
"crossing river",
|
| 1233 |
+
"crying",
|
| 1234 |
+
"curling hair",
|
| 1235 |
+
"cutting nails",
|
| 1236 |
+
"cutting pineapple",
|
| 1237 |
+
"cutting watermelon",
|
| 1238 |
+
"dancing ballet",
|
| 1239 |
+
"dancing charleston",
|
| 1240 |
+
"dancing gangnam style",
|
| 1241 |
+
"dancing macarena",
|
| 1242 |
+
"deadlifting",
|
| 1243 |
+
"decorating the christmas tree",
|
| 1244 |
+
"digging",
|
| 1245 |
+
"dining",
|
| 1246 |
+
"disc golfing",
|
| 1247 |
+
"diving cliff",
|
| 1248 |
+
"dodgeball",
|
| 1249 |
+
"doing aerobics",
|
| 1250 |
+
"doing laundry",
|
| 1251 |
+
"doing nails",
|
| 1252 |
+
"drawing",
|
| 1253 |
+
"dribbling basketball",
|
| 1254 |
+
"drinking",
|
| 1255 |
+
"drinking beer",
|
| 1256 |
+
"drinking shots",
|
| 1257 |
+
"driving car",
|
| 1258 |
+
"driving tractor",
|
| 1259 |
+
"drop kicking",
|
| 1260 |
+
"drumming fingers",
|
| 1261 |
+
"dunking basketball",
|
| 1262 |
+
"dying hair",
|
| 1263 |
+
"eating burger",
|
| 1264 |
+
"eating cake",
|
| 1265 |
+
"eating carrots",
|
| 1266 |
+
"eating chips",
|
| 1267 |
+
"eating doughnuts",
|
| 1268 |
+
"eating hotdog",
|
| 1269 |
+
"eating ice cream",
|
| 1270 |
+
"eating spaghetti",
|
| 1271 |
+
"eating watermelon",
|
| 1272 |
+
"egg hunting",
|
| 1273 |
+
"exercising arm",
|
| 1274 |
+
"exercising with an exercise ball",
|
| 1275 |
+
"extinguishing fire",
|
| 1276 |
+
"faceplanting",
|
| 1277 |
+
"feeding birds",
|
| 1278 |
+
"feeding fish",
|
| 1279 |
+
"feeding goats",
|
| 1280 |
+
"filling eyebrows",
|
| 1281 |
+
"finger snapping",
|
| 1282 |
+
"fixing hair",
|
| 1283 |
+
"flipping pancake",
|
| 1284 |
+
"flying kite",
|
| 1285 |
+
"folding clothes",
|
| 1286 |
+
"folding napkins",
|
| 1287 |
+
"folding paper",
|
| 1288 |
+
"front raises",
|
| 1289 |
+
"frying vegetables",
|
| 1290 |
+
"garbage collecting",
|
| 1291 |
+
"gargling",
|
| 1292 |
+
"getting a haircut",
|
| 1293 |
+
"getting a tattoo",
|
| 1294 |
+
"giving or receiving award",
|
| 1295 |
+
"golf chipping",
|
| 1296 |
+
"golf driving",
|
| 1297 |
+
"golf putting",
|
| 1298 |
+
"grinding meat",
|
| 1299 |
+
"grooming dog",
|
| 1300 |
+
"grooming horse",
|
| 1301 |
+
"gymnastics tumbling",
|
| 1302 |
+
"hammer throw",
|
| 1303 |
+
"headbanging",
|
| 1304 |
+
"headbutting",
|
| 1305 |
+
"high jump",
|
| 1306 |
+
"high kick",
|
| 1307 |
+
"hitting baseball",
|
| 1308 |
+
"hockey stop",
|
| 1309 |
+
"holding snake",
|
| 1310 |
+
"hopscotch",
|
| 1311 |
+
"hoverboarding",
|
| 1312 |
+
"hugging",
|
| 1313 |
+
"hula hooping",
|
| 1314 |
+
"hurdling",
|
| 1315 |
+
"hurling (sport)",
|
| 1316 |
+
"ice climbing",
|
| 1317 |
+
"ice fishing",
|
| 1318 |
+
"ice skating",
|
| 1319 |
+
"ironing",
|
| 1320 |
+
"javelin throw",
|
| 1321 |
+
"jetskiing",
|
| 1322 |
+
"jogging",
|
| 1323 |
+
"juggling balls",
|
| 1324 |
+
"juggling fire",
|
| 1325 |
+
"juggling soccer ball",
|
| 1326 |
+
"jumping into pool",
|
| 1327 |
+
"jumpstyle dancing",
|
| 1328 |
+
"kicking field goal",
|
| 1329 |
+
"kicking soccer ball",
|
| 1330 |
+
"kissing",
|
| 1331 |
+
"kitesurfing",
|
| 1332 |
+
"knitting",
|
| 1333 |
+
"krumping",
|
| 1334 |
+
"laughing",
|
| 1335 |
+
"laying bricks",
|
| 1336 |
+
"long jump",
|
| 1337 |
+
"lunge",
|
| 1338 |
+
"making a cake",
|
| 1339 |
+
"making a sandwich",
|
| 1340 |
+
"making bed",
|
| 1341 |
+
"making jewelry",
|
| 1342 |
+
"making pizza",
|
| 1343 |
+
"making snowman",
|
| 1344 |
+
"making sushi",
|
| 1345 |
+
"making tea",
|
| 1346 |
+
"marching",
|
| 1347 |
+
"massaging back",
|
| 1348 |
+
"massaging feet",
|
| 1349 |
+
"massaging legs",
|
| 1350 |
+
"massaging person's head",
|
| 1351 |
+
"milking cow",
|
| 1352 |
+
"mopping floor",
|
| 1353 |
+
"motorcycling",
|
| 1354 |
+
"moving furniture",
|
| 1355 |
+
"mowing lawn",
|
| 1356 |
+
"news anchoring",
|
| 1357 |
+
"opening bottle",
|
| 1358 |
+
"opening present",
|
| 1359 |
+
"paragliding",
|
| 1360 |
+
"parasailing",
|
| 1361 |
+
"parkour",
|
| 1362 |
+
"passing American football (in game)",
|
| 1363 |
+
"passing American football (not in game)",
|
| 1364 |
+
"peeling apples",
|
| 1365 |
+
"peeling potatoes",
|
| 1366 |
+
"petting animal (not cat)",
|
| 1367 |
+
"petting cat",
|
| 1368 |
+
"picking fruit",
|
| 1369 |
+
"planting trees",
|
| 1370 |
+
"plastering",
|
| 1371 |
+
"playing accordion",
|
| 1372 |
+
"playing badminton",
|
| 1373 |
+
"playing bagpipes",
|
| 1374 |
+
"playing basketball",
|
| 1375 |
+
"playing bass guitar",
|
| 1376 |
+
"playing cards",
|
| 1377 |
+
"playing cello",
|
| 1378 |
+
"playing chess",
|
| 1379 |
+
"playing clarinet",
|
| 1380 |
+
"playing controller",
|
| 1381 |
+
"playing cricket",
|
| 1382 |
+
"playing cymbals",
|
| 1383 |
+
"playing didgeridoo",
|
| 1384 |
+
"playing drums",
|
| 1385 |
+
"playing flute",
|
| 1386 |
+
"playing guitar",
|
| 1387 |
+
"playing harmonica",
|
| 1388 |
+
"playing harp",
|
| 1389 |
+
"playing ice hockey",
|
| 1390 |
+
"playing keyboard",
|
| 1391 |
+
"playing kickball",
|
| 1392 |
+
"playing monopoly",
|
| 1393 |
+
"playing organ",
|
| 1394 |
+
"playing paintball",
|
| 1395 |
+
"playing piano",
|
| 1396 |
+
"playing poker",
|
| 1397 |
+
"playing recorder",
|
| 1398 |
+
"playing saxophone",
|
| 1399 |
+
"playing squash or racquetball",
|
| 1400 |
+
"playing tennis",
|
| 1401 |
+
"playing trombone",
|
| 1402 |
+
"playing trumpet",
|
| 1403 |
+
"playing ukulele",
|
| 1404 |
+
"playing violin",
|
| 1405 |
+
"playing volleyball",
|
| 1406 |
+
"playing xylophone",
|
| 1407 |
+
"pole vault",
|
| 1408 |
+
"presenting weather forecast",
|
| 1409 |
+
"pull ups",
|
| 1410 |
+
"pumping fist",
|
| 1411 |
+
"pumping gas",
|
| 1412 |
+
"punching bag",
|
| 1413 |
+
"punching person (boxing)",
|
| 1414 |
+
"push up",
|
| 1415 |
+
"pushing car",
|
| 1416 |
+
"pushing cart",
|
| 1417 |
+
"pushing wheelchair",
|
| 1418 |
+
"reading book",
|
| 1419 |
+
"reading newspaper",
|
| 1420 |
+
"recording music",
|
| 1421 |
+
"riding a bike",
|
| 1422 |
+
"riding camel",
|
| 1423 |
+
"riding elephant",
|
| 1424 |
+
"riding mechanical bull",
|
| 1425 |
+
"riding mountain bike",
|
| 1426 |
+
"riding mule",
|
| 1427 |
+
"riding or walking with horse",
|
| 1428 |
+
"riding scooter",
|
| 1429 |
+
"riding unicycle",
|
| 1430 |
+
"ripping paper",
|
| 1431 |
+
"robot dancing",
|
| 1432 |
+
"rock climbing",
|
| 1433 |
+
"rock scissors paper",
|
| 1434 |
+
"roller skating",
|
| 1435 |
+
"running on treadmill",
|
| 1436 |
+
"sailing",
|
| 1437 |
+
"salsa dancing",
|
| 1438 |
+
"sanding floor",
|
| 1439 |
+
"scrambling eggs",
|
| 1440 |
+
"scuba diving",
|
| 1441 |
+
"setting table",
|
| 1442 |
+
"shaking hands",
|
| 1443 |
+
"shaking head",
|
| 1444 |
+
"sharpening knives",
|
| 1445 |
+
"sharpening pencil",
|
| 1446 |
+
"shaving head",
|
| 1447 |
+
"shaving legs",
|
| 1448 |
+
"shearing sheep",
|
| 1449 |
+
"shining shoes",
|
| 1450 |
+
"shooting basketball",
|
| 1451 |
+
"shooting goal (soccer)",
|
| 1452 |
+
"shot put",
|
| 1453 |
+
"shoveling snow",
|
| 1454 |
+
"shredding paper",
|
| 1455 |
+
"shuffling cards",
|
| 1456 |
+
"side kick",
|
| 1457 |
+
"sign language interpreting",
|
| 1458 |
+
"singing",
|
| 1459 |
+
"situp",
|
| 1460 |
+
"skateboarding",
|
| 1461 |
+
"ski jumping",
|
| 1462 |
+
"skiing (not slalom or crosscountry)",
|
| 1463 |
+
"skiing crosscountry",
|
| 1464 |
+
"skiing slalom",
|
| 1465 |
+
"skipping rope",
|
| 1466 |
+
"skydiving",
|
| 1467 |
+
"slacklining",
|
| 1468 |
+
"slapping",
|
| 1469 |
+
"sled dog racing",
|
| 1470 |
+
"smoking",
|
| 1471 |
+
"smoking hookah",
|
| 1472 |
+
"snatch weight lifting",
|
| 1473 |
+
"sneezing",
|
| 1474 |
+
"sniffing",
|
| 1475 |
+
"snorkeling",
|
| 1476 |
+
"snowboarding",
|
| 1477 |
+
"snowkiting",
|
| 1478 |
+
"snowmobiling",
|
| 1479 |
+
"somersaulting",
|
| 1480 |
+
"spinning poi",
|
| 1481 |
+
"spray painting",
|
| 1482 |
+
"spraying",
|
| 1483 |
+
"springboard diving",
|
| 1484 |
+
"squat",
|
| 1485 |
+
"sticking tongue out",
|
| 1486 |
+
"stomping grapes",
|
| 1487 |
+
"stretching arm",
|
| 1488 |
+
"stretching leg",
|
| 1489 |
+
"strumming guitar",
|
| 1490 |
+
"surfing crowd",
|
| 1491 |
+
"surfing water",
|
| 1492 |
+
"sweeping floor",
|
| 1493 |
+
"swimming backstroke",
|
| 1494 |
+
"swimming breast stroke",
|
| 1495 |
+
"swimming butterfly stroke",
|
| 1496 |
+
"swing dancing",
|
| 1497 |
+
"swinging legs",
|
| 1498 |
+
"swinging on something",
|
| 1499 |
+
"sword fighting",
|
| 1500 |
+
"tai chi",
|
| 1501 |
+
"taking a shower",
|
| 1502 |
+
"tango dancing",
|
| 1503 |
+
"tap dancing",
|
| 1504 |
+
"tapping guitar",
|
| 1505 |
+
"tapping pen",
|
| 1506 |
+
"tasting beer",
|
| 1507 |
+
"tasting food",
|
| 1508 |
+
"testifying",
|
| 1509 |
+
"texting",
|
| 1510 |
+
"throwing axe",
|
| 1511 |
+
"throwing ball",
|
| 1512 |
+
"throwing discus",
|
| 1513 |
+
"tickling",
|
| 1514 |
+
"tobogganing",
|
| 1515 |
+
"tossing coin",
|
| 1516 |
+
"tossing salad",
|
| 1517 |
+
"training dog",
|
| 1518 |
+
"trapezing",
|
| 1519 |
+
"trimming or shaving beard",
|
| 1520 |
+
"trimming trees",
|
| 1521 |
+
"triple jump",
|
| 1522 |
+
"tying bow tie",
|
| 1523 |
+
"tying knot (not on a tie)",
|
| 1524 |
+
"tying tie",
|
| 1525 |
+
"unboxing",
|
| 1526 |
+
"unloading truck",
|
| 1527 |
+
"using computer",
|
| 1528 |
+
"using remote controller (not gaming)",
|
| 1529 |
+
"using segway",
|
| 1530 |
+
"vault",
|
| 1531 |
+
"waiting in line",
|
| 1532 |
+
"walking the dog",
|
| 1533 |
+
"washing dishes",
|
| 1534 |
+
"washing feet",
|
| 1535 |
+
"washing hair",
|
| 1536 |
+
"washing hands",
|
| 1537 |
+
"water skiing",
|
| 1538 |
+
"water sliding",
|
| 1539 |
+
"watering plants",
|
| 1540 |
+
"waxing back",
|
| 1541 |
+
"waxing chest",
|
| 1542 |
+
"waxing eyebrows",
|
| 1543 |
+
"waxing legs",
|
| 1544 |
+
"weaving basket",
|
| 1545 |
+
"welding",
|
| 1546 |
+
"whistling",
|
| 1547 |
+
"windsurfing",
|
| 1548 |
+
"wrapping present",
|
| 1549 |
+
"wrestling",
|
| 1550 |
+
"writing",
|
| 1551 |
+
"yawning",
|
| 1552 |
+
"yoga",
|
| 1553 |
+
"zumba",
|
| 1554 |
+
]
|
wemm/lib/python3.10/site-packages/torchvision/models/densenet.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
from functools import partial
|
| 4 |
+
from typing import Any, List, Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import torch.utils.checkpoint as cp
|
| 10 |
+
from torch import Tensor
|
| 11 |
+
|
| 12 |
+
from ..transforms._presets import ImageClassification
|
| 13 |
+
from ..utils import _log_api_usage_once
|
| 14 |
+
from ._api import register_model, Weights, WeightsEnum
|
| 15 |
+
from ._meta import _IMAGENET_CATEGORIES
|
| 16 |
+
from ._utils import _ovewrite_named_param, handle_legacy_interface
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"DenseNet",
|
| 20 |
+
"DenseNet121_Weights",
|
| 21 |
+
"DenseNet161_Weights",
|
| 22 |
+
"DenseNet169_Weights",
|
| 23 |
+
"DenseNet201_Weights",
|
| 24 |
+
"densenet121",
|
| 25 |
+
"densenet161",
|
| 26 |
+
"densenet169",
|
| 27 |
+
"densenet201",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class _DenseLayer(nn.Module):
|
| 32 |
+
def __init__(
|
| 33 |
+
self, num_input_features: int, growth_rate: int, bn_size: int, drop_rate: float, memory_efficient: bool = False
|
| 34 |
+
) -> None:
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.norm1 = nn.BatchNorm2d(num_input_features)
|
| 37 |
+
self.relu1 = nn.ReLU(inplace=True)
|
| 38 |
+
self.conv1 = nn.Conv2d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False)
|
| 39 |
+
|
| 40 |
+
self.norm2 = nn.BatchNorm2d(bn_size * growth_rate)
|
| 41 |
+
self.relu2 = nn.ReLU(inplace=True)
|
| 42 |
+
self.conv2 = nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)
|
| 43 |
+
|
| 44 |
+
self.drop_rate = float(drop_rate)
|
| 45 |
+
self.memory_efficient = memory_efficient
|
| 46 |
+
|
| 47 |
+
def bn_function(self, inputs: List[Tensor]) -> Tensor:
|
| 48 |
+
concated_features = torch.cat(inputs, 1)
|
| 49 |
+
bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features))) # noqa: T484
|
| 50 |
+
return bottleneck_output
|
| 51 |
+
|
| 52 |
+
# todo: rewrite when torchscript supports any
|
| 53 |
+
def any_requires_grad(self, input: List[Tensor]) -> bool:
|
| 54 |
+
for tensor in input:
|
| 55 |
+
if tensor.requires_grad:
|
| 56 |
+
return True
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
@torch.jit.unused # noqa: T484
|
| 60 |
+
def call_checkpoint_bottleneck(self, input: List[Tensor]) -> Tensor:
|
| 61 |
+
def closure(*inputs):
|
| 62 |
+
return self.bn_function(inputs)
|
| 63 |
+
|
| 64 |
+
return cp.checkpoint(closure, *input)
|
| 65 |
+
|
| 66 |
+
@torch.jit._overload_method # noqa: F811
|
| 67 |
+
def forward(self, input: List[Tensor]) -> Tensor: # noqa: F811
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
@torch.jit._overload_method # noqa: F811
|
| 71 |
+
def forward(self, input: Tensor) -> Tensor: # noqa: F811
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
# torchscript does not yet support *args, so we overload method
|
| 75 |
+
# allowing it to take either a List[Tensor] or single Tensor
|
| 76 |
+
def forward(self, input: Tensor) -> Tensor: # noqa: F811
|
| 77 |
+
if isinstance(input, Tensor):
|
| 78 |
+
prev_features = [input]
|
| 79 |
+
else:
|
| 80 |
+
prev_features = input
|
| 81 |
+
|
| 82 |
+
if self.memory_efficient and self.any_requires_grad(prev_features):
|
| 83 |
+
if torch.jit.is_scripting():
|
| 84 |
+
raise Exception("Memory Efficient not supported in JIT")
|
| 85 |
+
|
| 86 |
+
bottleneck_output = self.call_checkpoint_bottleneck(prev_features)
|
| 87 |
+
else:
|
| 88 |
+
bottleneck_output = self.bn_function(prev_features)
|
| 89 |
+
|
| 90 |
+
new_features = self.conv2(self.relu2(self.norm2(bottleneck_output)))
|
| 91 |
+
if self.drop_rate > 0:
|
| 92 |
+
new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)
|
| 93 |
+
return new_features
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class _DenseBlock(nn.ModuleDict):
|
| 97 |
+
_version = 2
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
num_layers: int,
|
| 102 |
+
num_input_features: int,
|
| 103 |
+
bn_size: int,
|
| 104 |
+
growth_rate: int,
|
| 105 |
+
drop_rate: float,
|
| 106 |
+
memory_efficient: bool = False,
|
| 107 |
+
) -> None:
|
| 108 |
+
super().__init__()
|
| 109 |
+
for i in range(num_layers):
|
| 110 |
+
layer = _DenseLayer(
|
| 111 |
+
num_input_features + i * growth_rate,
|
| 112 |
+
growth_rate=growth_rate,
|
| 113 |
+
bn_size=bn_size,
|
| 114 |
+
drop_rate=drop_rate,
|
| 115 |
+
memory_efficient=memory_efficient,
|
| 116 |
+
)
|
| 117 |
+
self.add_module("denselayer%d" % (i + 1), layer)
|
| 118 |
+
|
| 119 |
+
def forward(self, init_features: Tensor) -> Tensor:
|
| 120 |
+
features = [init_features]
|
| 121 |
+
for name, layer in self.items():
|
| 122 |
+
new_features = layer(features)
|
| 123 |
+
features.append(new_features)
|
| 124 |
+
return torch.cat(features, 1)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class _Transition(nn.Sequential):
|
| 128 |
+
def __init__(self, num_input_features: int, num_output_features: int) -> None:
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.norm = nn.BatchNorm2d(num_input_features)
|
| 131 |
+
self.relu = nn.ReLU(inplace=True)
|
| 132 |
+
self.conv = nn.Conv2d(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)
|
| 133 |
+
self.pool = nn.AvgPool2d(kernel_size=2, stride=2)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class DenseNet(nn.Module):
|
| 137 |
+
r"""Densenet-BC model class, based on
|
| 138 |
+
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
growth_rate (int) - how many filters to add each layer (`k` in paper)
|
| 142 |
+
block_config (list of 4 ints) - how many layers in each pooling block
|
| 143 |
+
num_init_features (int) - the number of filters to learn in the first convolution layer
|
| 144 |
+
bn_size (int) - multiplicative factor for number of bottle neck layers
|
| 145 |
+
(i.e. bn_size * k features in the bottleneck layer)
|
| 146 |
+
drop_rate (float) - dropout rate after each dense layer
|
| 147 |
+
num_classes (int) - number of classification classes
|
| 148 |
+
memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,
|
| 149 |
+
but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
growth_rate: int = 32,
|
| 155 |
+
block_config: Tuple[int, int, int, int] = (6, 12, 24, 16),
|
| 156 |
+
num_init_features: int = 64,
|
| 157 |
+
bn_size: int = 4,
|
| 158 |
+
drop_rate: float = 0,
|
| 159 |
+
num_classes: int = 1000,
|
| 160 |
+
memory_efficient: bool = False,
|
| 161 |
+
) -> None:
|
| 162 |
+
|
| 163 |
+
super().__init__()
|
| 164 |
+
_log_api_usage_once(self)
|
| 165 |
+
|
| 166 |
+
# First convolution
|
| 167 |
+
self.features = nn.Sequential(
|
| 168 |
+
OrderedDict(
|
| 169 |
+
[
|
| 170 |
+
("conv0", nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),
|
| 171 |
+
("norm0", nn.BatchNorm2d(num_init_features)),
|
| 172 |
+
("relu0", nn.ReLU(inplace=True)),
|
| 173 |
+
("pool0", nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
|
| 174 |
+
]
|
| 175 |
+
)
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Each denseblock
|
| 179 |
+
num_features = num_init_features
|
| 180 |
+
for i, num_layers in enumerate(block_config):
|
| 181 |
+
block = _DenseBlock(
|
| 182 |
+
num_layers=num_layers,
|
| 183 |
+
num_input_features=num_features,
|
| 184 |
+
bn_size=bn_size,
|
| 185 |
+
growth_rate=growth_rate,
|
| 186 |
+
drop_rate=drop_rate,
|
| 187 |
+
memory_efficient=memory_efficient,
|
| 188 |
+
)
|
| 189 |
+
self.features.add_module("denseblock%d" % (i + 1), block)
|
| 190 |
+
num_features = num_features + num_layers * growth_rate
|
| 191 |
+
if i != len(block_config) - 1:
|
| 192 |
+
trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2)
|
| 193 |
+
self.features.add_module("transition%d" % (i + 1), trans)
|
| 194 |
+
num_features = num_features // 2
|
| 195 |
+
|
| 196 |
+
# Final batch norm
|
| 197 |
+
self.features.add_module("norm5", nn.BatchNorm2d(num_features))
|
| 198 |
+
|
| 199 |
+
# Linear layer
|
| 200 |
+
self.classifier = nn.Linear(num_features, num_classes)
|
| 201 |
+
|
| 202 |
+
# Official init from torch repo.
|
| 203 |
+
for m in self.modules():
|
| 204 |
+
if isinstance(m, nn.Conv2d):
|
| 205 |
+
nn.init.kaiming_normal_(m.weight)
|
| 206 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 207 |
+
nn.init.constant_(m.weight, 1)
|
| 208 |
+
nn.init.constant_(m.bias, 0)
|
| 209 |
+
elif isinstance(m, nn.Linear):
|
| 210 |
+
nn.init.constant_(m.bias, 0)
|
| 211 |
+
|
| 212 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 213 |
+
features = self.features(x)
|
| 214 |
+
out = F.relu(features, inplace=True)
|
| 215 |
+
out = F.adaptive_avg_pool2d(out, (1, 1))
|
| 216 |
+
out = torch.flatten(out, 1)
|
| 217 |
+
out = self.classifier(out)
|
| 218 |
+
return out
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _load_state_dict(model: nn.Module, weights: WeightsEnum, progress: bool) -> None:
|
| 222 |
+
# '.'s are no longer allowed in module names, but previous _DenseLayer
|
| 223 |
+
# has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.
|
| 224 |
+
# They are also in the checkpoints in model_urls. This pattern is used
|
| 225 |
+
# to find such keys.
|
| 226 |
+
pattern = re.compile(
|
| 227 |
+
r"^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$"
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
state_dict = weights.get_state_dict(progress=progress)
|
| 231 |
+
for key in list(state_dict.keys()):
|
| 232 |
+
res = pattern.match(key)
|
| 233 |
+
if res:
|
| 234 |
+
new_key = res.group(1) + res.group(2)
|
| 235 |
+
state_dict[new_key] = state_dict[key]
|
| 236 |
+
del state_dict[key]
|
| 237 |
+
model.load_state_dict(state_dict)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _densenet(
|
| 241 |
+
growth_rate: int,
|
| 242 |
+
block_config: Tuple[int, int, int, int],
|
| 243 |
+
num_init_features: int,
|
| 244 |
+
weights: Optional[WeightsEnum],
|
| 245 |
+
progress: bool,
|
| 246 |
+
**kwargs: Any,
|
| 247 |
+
) -> DenseNet:
|
| 248 |
+
if weights is not None:
|
| 249 |
+
_ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
|
| 250 |
+
|
| 251 |
+
model = DenseNet(growth_rate, block_config, num_init_features, **kwargs)
|
| 252 |
+
|
| 253 |
+
if weights is not None:
|
| 254 |
+
_load_state_dict(model=model, weights=weights, progress=progress)
|
| 255 |
+
|
| 256 |
+
return model
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
_COMMON_META = {
|
| 260 |
+
"min_size": (29, 29),
|
| 261 |
+
"categories": _IMAGENET_CATEGORIES,
|
| 262 |
+
"recipe": "https://github.com/pytorch/vision/pull/116",
|
| 263 |
+
"_docs": """These weights are ported from LuaTorch.""",
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class DenseNet121_Weights(WeightsEnum):
|
| 268 |
+
IMAGENET1K_V1 = Weights(
|
| 269 |
+
url="https://download.pytorch.org/models/densenet121-a639ec97.pth",
|
| 270 |
+
transforms=partial(ImageClassification, crop_size=224),
|
| 271 |
+
meta={
|
| 272 |
+
**_COMMON_META,
|
| 273 |
+
"num_params": 7978856,
|
| 274 |
+
"_metrics": {
|
| 275 |
+
"ImageNet-1K": {
|
| 276 |
+
"acc@1": 74.434,
|
| 277 |
+
"acc@5": 91.972,
|
| 278 |
+
}
|
| 279 |
+
},
|
| 280 |
+
"_ops": 2.834,
|
| 281 |
+
"_file_size": 30.845,
|
| 282 |
+
},
|
| 283 |
+
)
|
| 284 |
+
DEFAULT = IMAGENET1K_V1
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class DenseNet161_Weights(WeightsEnum):
|
| 288 |
+
IMAGENET1K_V1 = Weights(
|
| 289 |
+
url="https://download.pytorch.org/models/densenet161-8d451a50.pth",
|
| 290 |
+
transforms=partial(ImageClassification, crop_size=224),
|
| 291 |
+
meta={
|
| 292 |
+
**_COMMON_META,
|
| 293 |
+
"num_params": 28681000,
|
| 294 |
+
"_metrics": {
|
| 295 |
+
"ImageNet-1K": {
|
| 296 |
+
"acc@1": 77.138,
|
| 297 |
+
"acc@5": 93.560,
|
| 298 |
+
}
|
| 299 |
+
},
|
| 300 |
+
"_ops": 7.728,
|
| 301 |
+
"_file_size": 110.369,
|
| 302 |
+
},
|
| 303 |
+
)
|
| 304 |
+
DEFAULT = IMAGENET1K_V1
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class DenseNet169_Weights(WeightsEnum):
|
| 308 |
+
IMAGENET1K_V1 = Weights(
|
| 309 |
+
url="https://download.pytorch.org/models/densenet169-b2777c0a.pth",
|
| 310 |
+
transforms=partial(ImageClassification, crop_size=224),
|
| 311 |
+
meta={
|
| 312 |
+
**_COMMON_META,
|
| 313 |
+
"num_params": 14149480,
|
| 314 |
+
"_metrics": {
|
| 315 |
+
"ImageNet-1K": {
|
| 316 |
+
"acc@1": 75.600,
|
| 317 |
+
"acc@5": 92.806,
|
| 318 |
+
}
|
| 319 |
+
},
|
| 320 |
+
"_ops": 3.36,
|
| 321 |
+
"_file_size": 54.708,
|
| 322 |
+
},
|
| 323 |
+
)
|
| 324 |
+
DEFAULT = IMAGENET1K_V1
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class DenseNet201_Weights(WeightsEnum):
|
| 328 |
+
IMAGENET1K_V1 = Weights(
|
| 329 |
+
url="https://download.pytorch.org/models/densenet201-c1103571.pth",
|
| 330 |
+
transforms=partial(ImageClassification, crop_size=224),
|
| 331 |
+
meta={
|
| 332 |
+
**_COMMON_META,
|
| 333 |
+
"num_params": 20013928,
|
| 334 |
+
"_metrics": {
|
| 335 |
+
"ImageNet-1K": {
|
| 336 |
+
"acc@1": 76.896,
|
| 337 |
+
"acc@5": 93.370,
|
| 338 |
+
}
|
| 339 |
+
},
|
| 340 |
+
"_ops": 4.291,
|
| 341 |
+
"_file_size": 77.373,
|
| 342 |
+
},
|
| 343 |
+
)
|
| 344 |
+
DEFAULT = IMAGENET1K_V1
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@register_model()
|
| 348 |
+
@handle_legacy_interface(weights=("pretrained", DenseNet121_Weights.IMAGENET1K_V1))
|
| 349 |
+
def densenet121(*, weights: Optional[DenseNet121_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
|
| 350 |
+
r"""Densenet-121 model from
|
| 351 |
+
`Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
|
| 352 |
+
|
| 353 |
+
Args:
|
| 354 |
+
weights (:class:`~torchvision.models.DenseNet121_Weights`, optional): The
|
| 355 |
+
pretrained weights to use. See
|
| 356 |
+
:class:`~torchvision.models.DenseNet121_Weights` below for
|
| 357 |
+
more details, and possible values. By default, no pre-trained
|
| 358 |
+
weights are used.
|
| 359 |
+
progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
|
| 360 |
+
**kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
|
| 361 |
+
base class. Please refer to the `source code
|
| 362 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
|
| 363 |
+
for more details about this class.
|
| 364 |
+
|
| 365 |
+
.. autoclass:: torchvision.models.DenseNet121_Weights
|
| 366 |
+
:members:
|
| 367 |
+
"""
|
| 368 |
+
weights = DenseNet121_Weights.verify(weights)
|
| 369 |
+
|
| 370 |
+
return _densenet(32, (6, 12, 24, 16), 64, weights, progress, **kwargs)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
@register_model()
|
| 374 |
+
@handle_legacy_interface(weights=("pretrained", DenseNet161_Weights.IMAGENET1K_V1))
|
| 375 |
+
def densenet161(*, weights: Optional[DenseNet161_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
|
| 376 |
+
r"""Densenet-161 model from
|
| 377 |
+
`Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
|
| 378 |
+
|
| 379 |
+
Args:
|
| 380 |
+
weights (:class:`~torchvision.models.DenseNet161_Weights`, optional): The
|
| 381 |
+
pretrained weights to use. See
|
| 382 |
+
:class:`~torchvision.models.DenseNet161_Weights` below for
|
| 383 |
+
more details, and possible values. By default, no pre-trained
|
| 384 |
+
weights are used.
|
| 385 |
+
progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
|
| 386 |
+
**kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
|
| 387 |
+
base class. Please refer to the `source code
|
| 388 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
|
| 389 |
+
for more details about this class.
|
| 390 |
+
|
| 391 |
+
.. autoclass:: torchvision.models.DenseNet161_Weights
|
| 392 |
+
:members:
|
| 393 |
+
"""
|
| 394 |
+
weights = DenseNet161_Weights.verify(weights)
|
| 395 |
+
|
| 396 |
+
return _densenet(48, (6, 12, 36, 24), 96, weights, progress, **kwargs)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
@register_model()
|
| 400 |
+
@handle_legacy_interface(weights=("pretrained", DenseNet169_Weights.IMAGENET1K_V1))
|
| 401 |
+
def densenet169(*, weights: Optional[DenseNet169_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
|
| 402 |
+
r"""Densenet-169 model from
|
| 403 |
+
`Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
|
| 404 |
+
|
| 405 |
+
Args:
|
| 406 |
+
weights (:class:`~torchvision.models.DenseNet169_Weights`, optional): The
|
| 407 |
+
pretrained weights to use. See
|
| 408 |
+
:class:`~torchvision.models.DenseNet169_Weights` below for
|
| 409 |
+
more details, and possible values. By default, no pre-trained
|
| 410 |
+
weights are used.
|
| 411 |
+
progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
|
| 412 |
+
**kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
|
| 413 |
+
base class. Please refer to the `source code
|
| 414 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
|
| 415 |
+
for more details about this class.
|
| 416 |
+
|
| 417 |
+
.. autoclass:: torchvision.models.DenseNet169_Weights
|
| 418 |
+
:members:
|
| 419 |
+
"""
|
| 420 |
+
weights = DenseNet169_Weights.verify(weights)
|
| 421 |
+
|
| 422 |
+
return _densenet(32, (6, 12, 32, 32), 64, weights, progress, **kwargs)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
@register_model()
|
| 426 |
+
@handle_legacy_interface(weights=("pretrained", DenseNet201_Weights.IMAGENET1K_V1))
|
| 427 |
+
def densenet201(*, weights: Optional[DenseNet201_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet:
|
| 428 |
+
r"""Densenet-201 model from
|
| 429 |
+
`Densely Connected Convolutional Networks <https://arxiv.org/abs/1608.06993>`_.
|
| 430 |
+
|
| 431 |
+
Args:
|
| 432 |
+
weights (:class:`~torchvision.models.DenseNet201_Weights`, optional): The
|
| 433 |
+
pretrained weights to use. See
|
| 434 |
+
:class:`~torchvision.models.DenseNet201_Weights` below for
|
| 435 |
+
more details, and possible values. By default, no pre-trained
|
| 436 |
+
weights are used.
|
| 437 |
+
progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
|
| 438 |
+
**kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet``
|
| 439 |
+
base class. Please refer to the `source code
|
| 440 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/densenet.py>`_
|
| 441 |
+
for more details about this class.
|
| 442 |
+
|
| 443 |
+
.. autoclass:: torchvision.models.DenseNet201_Weights
|
| 444 |
+
:members:
|
| 445 |
+
"""
|
| 446 |
+
weights = DenseNet201_Weights.verify(weights)
|
| 447 |
+
|
| 448 |
+
return _densenet(32, (6, 12, 48, 32), 64, weights, progress, **kwargs)
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (323 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/anchor_utils.cpython-310.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/backbone_utils.cpython-310.pyc
ADDED
|
Binary file (9.23 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/image_list.cpython-310.pyc
ADDED
|
Binary file (1.25 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/mask_rcnn.cpython-310.pyc
ADDED
|
Binary file (22.6 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/__pycache__/transform.cpython-310.pyc
ADDED
|
Binary file (9.88 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/_utils.py
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, 39796],
|
| 412 |
+
# [ 1, 32055],
|
| 413 |
+
# [ 1, 32070],
|
| 414 |
+
# [ 2, 39190],
|
| 415 |
+
# [ 2, 40255],
|
| 416 |
+
# [ 3, 40390],
|
| 417 |
+
# [ 3, 41455],
|
| 418 |
+
# [ 4, 45470],
|
| 419 |
+
# [ 5, 45325],
|
| 420 |
+
# [ 5, 46390]])
|
| 421 |
+
# Each row is a (gt index, prediction index)
|
| 422 |
+
# Note how gt items 1, 2, 3, and 5 each have two ties
|
| 423 |
+
|
| 424 |
+
pred_inds_to_update = gt_pred_pairs_of_highest_quality[1]
|
| 425 |
+
matches[pred_inds_to_update] = all_matches[pred_inds_to_update]
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class SSDMatcher(Matcher):
|
| 429 |
+
def __init__(self, threshold: float) -> None:
|
| 430 |
+
super().__init__(threshold, threshold, allow_low_quality_matches=False)
|
| 431 |
+
|
| 432 |
+
def __call__(self, match_quality_matrix: Tensor) -> Tensor:
|
| 433 |
+
matches = super().__call__(match_quality_matrix)
|
| 434 |
+
|
| 435 |
+
# For each gt, find the prediction with which it has the highest quality
|
| 436 |
+
_, highest_quality_pred_foreach_gt = match_quality_matrix.max(dim=1)
|
| 437 |
+
matches[highest_quality_pred_foreach_gt] = torch.arange(
|
| 438 |
+
highest_quality_pred_foreach_gt.size(0), dtype=torch.int64, device=highest_quality_pred_foreach_gt.device
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
return matches
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def overwrite_eps(model: nn.Module, eps: float) -> None:
|
| 445 |
+
"""
|
| 446 |
+
This method overwrites the default eps values of all the
|
| 447 |
+
FrozenBatchNorm2d layers of the model with the provided value.
|
| 448 |
+
This is necessary to address the BC-breaking change introduced
|
| 449 |
+
by the bug-fix at pytorch/vision#2933. The overwrite is applied
|
| 450 |
+
only when the pretrained weights are loaded to maintain compatibility
|
| 451 |
+
with previous versions.
|
| 452 |
+
|
| 453 |
+
Args:
|
| 454 |
+
model (nn.Module): The model on which we perform the overwrite.
|
| 455 |
+
eps (float): The new value of eps.
|
| 456 |
+
"""
|
| 457 |
+
for module in model.modules():
|
| 458 |
+
if isinstance(module, FrozenBatchNorm2d):
|
| 459 |
+
module.eps = eps
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def retrieve_out_channels(model: nn.Module, size: Tuple[int, int]) -> List[int]:
|
| 463 |
+
"""
|
| 464 |
+
This method retrieves the number of output channels of a specific model.
|
| 465 |
+
|
| 466 |
+
Args:
|
| 467 |
+
model (nn.Module): The model for which we estimate the out_channels.
|
| 468 |
+
It should return a single Tensor or an OrderedDict[Tensor].
|
| 469 |
+
size (Tuple[int, int]): The size (wxh) of the input.
|
| 470 |
+
|
| 471 |
+
Returns:
|
| 472 |
+
out_channels (List[int]): A list of the output channels of the model.
|
| 473 |
+
"""
|
| 474 |
+
in_training = model.training
|
| 475 |
+
model.eval()
|
| 476 |
+
|
| 477 |
+
with torch.no_grad():
|
| 478 |
+
# Use dummy data to retrieve the feature map sizes to avoid hard-coding their values
|
| 479 |
+
device = next(model.parameters()).device
|
| 480 |
+
tmp_img = torch.zeros((1, 3, size[1], size[0]), device=device)
|
| 481 |
+
features = model(tmp_img)
|
| 482 |
+
if isinstance(features, torch.Tensor):
|
| 483 |
+
features = OrderedDict([("0", features)])
|
| 484 |
+
out_channels = [x.size(1) for x in features.values()]
|
| 485 |
+
|
| 486 |
+
if in_training:
|
| 487 |
+
model.train()
|
| 488 |
+
|
| 489 |
+
return out_channels
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
@torch.jit.unused
|
| 493 |
+
def _fake_cast_onnx(v: Tensor) -> int:
|
| 494 |
+
return v # type: ignore[return-value]
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def _topk_min(input: Tensor, orig_kval: int, axis: int) -> int:
|
| 498 |
+
"""
|
| 499 |
+
ONNX spec requires the k-value to be less than or equal to the number of inputs along
|
| 500 |
+
provided dim. Certain models use the number of elements along a particular axis instead of K
|
| 501 |
+
if K exceeds the number of elements along that axis. Previously, python's min() function was
|
| 502 |
+
used to determine whether to use the provided k-value or the specified dim axis value.
|
| 503 |
+
|
| 504 |
+
However, in cases where the model is being exported in tracing mode, python min() is
|
| 505 |
+
static causing the model to be traced incorrectly and eventually fail at the topk node.
|
| 506 |
+
In order to avoid this situation, in tracing mode, torch.min() is used instead.
|
| 507 |
+
|
| 508 |
+
Args:
|
| 509 |
+
input (Tensor): The original input tensor.
|
| 510 |
+
orig_kval (int): The provided k-value.
|
| 511 |
+
axis(int): Axis along which we retrieve the input size.
|
| 512 |
+
|
| 513 |
+
Returns:
|
| 514 |
+
min_kval (int): Appropriately selected k-value.
|
| 515 |
+
"""
|
| 516 |
+
if not torch.jit.is_tracing():
|
| 517 |
+
return min(orig_kval, input.size(axis))
|
| 518 |
+
axis_dim_val = torch._shape_as_tensor(input)[axis].unsqueeze(0)
|
| 519 |
+
min_kval = torch.min(torch.cat((torch.tensor([orig_kval], dtype=axis_dim_val.dtype), axis_dim_val), 0))
|
| 520 |
+
return _fake_cast_onnx(min_kval)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def _box_loss(
|
| 524 |
+
type: str,
|
| 525 |
+
box_coder: BoxCoder,
|
| 526 |
+
anchors_per_image: Tensor,
|
| 527 |
+
matched_gt_boxes_per_image: Tensor,
|
| 528 |
+
bbox_regression_per_image: Tensor,
|
| 529 |
+
cnf: Optional[Dict[str, float]] = None,
|
| 530 |
+
) -> Tensor:
|
| 531 |
+
torch._assert(type in ["l1", "smooth_l1", "ciou", "diou", "giou"], f"Unsupported loss: {type}")
|
| 532 |
+
|
| 533 |
+
if type == "l1":
|
| 534 |
+
target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image)
|
| 535 |
+
return F.l1_loss(bbox_regression_per_image, target_regression, reduction="sum")
|
| 536 |
+
elif type == "smooth_l1":
|
| 537 |
+
target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image)
|
| 538 |
+
beta = cnf["beta"] if cnf is not None and "beta" in cnf else 1.0
|
| 539 |
+
return F.smooth_l1_loss(bbox_regression_per_image, target_regression, reduction="sum", beta=beta)
|
| 540 |
+
else:
|
| 541 |
+
bbox_per_image = box_coder.decode_single(bbox_regression_per_image, anchors_per_image)
|
| 542 |
+
eps = cnf["eps"] if cnf is not None and "eps" in cnf else 1e-7
|
| 543 |
+
if type == "ciou":
|
| 544 |
+
return complete_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps)
|
| 545 |
+
if type == "diou":
|
| 546 |
+
return distance_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps)
|
| 547 |
+
# otherwise giou
|
| 548 |
+
return generalized_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps)
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/backbone_utils.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
>>> from torchvision.models.detection.backbone_utils import resnet_fpn_backbone
|
| 83 |
+
>>> backbone = resnet_fpn_backbone('resnet50', weights=ResNet50_Weights.DEFAULT, trainable_layers=3)
|
| 84 |
+
>>> # get some dummy image
|
| 85 |
+
>>> x = torch.rand(1,3,64,64)
|
| 86 |
+
>>> # compute the output
|
| 87 |
+
>>> output = backbone(x)
|
| 88 |
+
>>> print([(k, v.shape) for k, v in output.items()])
|
| 89 |
+
>>> # returns
|
| 90 |
+
>>> [('0', torch.Size([1, 256, 16, 16])),
|
| 91 |
+
>>> ('1', torch.Size([1, 256, 8, 8])),
|
| 92 |
+
>>> ('2', torch.Size([1, 256, 4, 4])),
|
| 93 |
+
>>> ('3', torch.Size([1, 256, 2, 2])),
|
| 94 |
+
>>> ('pool', torch.Size([1, 256, 1, 1]))]
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
backbone_name (string): resnet architecture. Possible values are 'resnet18', 'resnet34', 'resnet50',
|
| 98 |
+
'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2'
|
| 99 |
+
weights (WeightsEnum, optional): The pretrained weights for the model
|
| 100 |
+
norm_layer (callable): it is recommended to use the default value. For details visit:
|
| 101 |
+
(https://github.com/facebookresearch/maskrcnn-benchmark/issues/267)
|
| 102 |
+
trainable_layers (int): number of trainable (not frozen) layers starting from final block.
|
| 103 |
+
Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable.
|
| 104 |
+
returned_layers (list of int): The layers of the network to return. Each entry must be in ``[1, 4]``.
|
| 105 |
+
By default, all layers are returned.
|
| 106 |
+
extra_blocks (ExtraFPNBlock or None): if provided, extra operations will
|
| 107 |
+
be performed. It is expected to take the fpn features, the original
|
| 108 |
+
features and the names of the original features as input, and returns
|
| 109 |
+
a new list of feature maps and their corresponding names. By
|
| 110 |
+
default, a ``LastLevelMaxPool`` is used.
|
| 111 |
+
"""
|
| 112 |
+
backbone = resnet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer)
|
| 113 |
+
return _resnet_fpn_extractor(backbone, trainable_layers, returned_layers, extra_blocks)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _resnet_fpn_extractor(
|
| 117 |
+
backbone: resnet.ResNet,
|
| 118 |
+
trainable_layers: int,
|
| 119 |
+
returned_layers: Optional[List[int]] = None,
|
| 120 |
+
extra_blocks: Optional[ExtraFPNBlock] = None,
|
| 121 |
+
norm_layer: Optional[Callable[..., nn.Module]] = None,
|
| 122 |
+
) -> BackboneWithFPN:
|
| 123 |
+
|
| 124 |
+
# select layers that won't be frozen
|
| 125 |
+
if trainable_layers < 0 or trainable_layers > 5:
|
| 126 |
+
raise ValueError(f"Trainable layers should be in the range [0,5], got {trainable_layers}")
|
| 127 |
+
layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers]
|
| 128 |
+
if trainable_layers == 5:
|
| 129 |
+
layers_to_train.append("bn1")
|
| 130 |
+
for name, parameter in backbone.named_parameters():
|
| 131 |
+
if all([not name.startswith(layer) for layer in layers_to_train]):
|
| 132 |
+
parameter.requires_grad_(False)
|
| 133 |
+
|
| 134 |
+
if extra_blocks is None:
|
| 135 |
+
extra_blocks = LastLevelMaxPool()
|
| 136 |
+
|
| 137 |
+
if returned_layers is None:
|
| 138 |
+
returned_layers = [1, 2, 3, 4]
|
| 139 |
+
if min(returned_layers) <= 0 or max(returned_layers) >= 5:
|
| 140 |
+
raise ValueError(f"Each returned layer should be in the range [1,4]. Got {returned_layers}")
|
| 141 |
+
return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)}
|
| 142 |
+
|
| 143 |
+
in_channels_stage2 = backbone.inplanes // 8
|
| 144 |
+
in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers]
|
| 145 |
+
out_channels = 256
|
| 146 |
+
return BackboneWithFPN(
|
| 147 |
+
backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _validate_trainable_layers(
|
| 152 |
+
is_trained: bool,
|
| 153 |
+
trainable_backbone_layers: Optional[int],
|
| 154 |
+
max_value: int,
|
| 155 |
+
default_value: int,
|
| 156 |
+
) -> int:
|
| 157 |
+
# don't freeze any layers if pretrained model or backbone is not used
|
| 158 |
+
if not is_trained:
|
| 159 |
+
if trainable_backbone_layers is not None:
|
| 160 |
+
warnings.warn(
|
| 161 |
+
"Changing trainable_backbone_layers has not effect if "
|
| 162 |
+
"neither pretrained nor pretrained_backbone have been set to True, "
|
| 163 |
+
f"falling back to trainable_backbone_layers={max_value} so that all layers are trainable"
|
| 164 |
+
)
|
| 165 |
+
trainable_backbone_layers = max_value
|
| 166 |
+
|
| 167 |
+
# by default freeze first blocks
|
| 168 |
+
if trainable_backbone_layers is None:
|
| 169 |
+
trainable_backbone_layers = default_value
|
| 170 |
+
if trainable_backbone_layers < 0 or trainable_backbone_layers > max_value:
|
| 171 |
+
raise ValueError(
|
| 172 |
+
f"Trainable backbone layers should be in the range [0,{max_value}], got {trainable_backbone_layers} "
|
| 173 |
+
)
|
| 174 |
+
return trainable_backbone_layers
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@handle_legacy_interface(
|
| 178 |
+
weights=(
|
| 179 |
+
"pretrained",
|
| 180 |
+
lambda kwargs: _get_enum_from_fn(mobilenet.__dict__[kwargs["backbone_name"]])["IMAGENET1K_V1"],
|
| 181 |
+
),
|
| 182 |
+
)
|
| 183 |
+
def mobilenet_backbone(
|
| 184 |
+
*,
|
| 185 |
+
backbone_name: str,
|
| 186 |
+
weights: Optional[WeightsEnum],
|
| 187 |
+
fpn: bool,
|
| 188 |
+
norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d,
|
| 189 |
+
trainable_layers: int = 2,
|
| 190 |
+
returned_layers: Optional[List[int]] = None,
|
| 191 |
+
extra_blocks: Optional[ExtraFPNBlock] = None,
|
| 192 |
+
) -> nn.Module:
|
| 193 |
+
backbone = mobilenet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer)
|
| 194 |
+
return _mobilenet_extractor(backbone, fpn, trainable_layers, returned_layers, extra_blocks)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _mobilenet_extractor(
|
| 198 |
+
backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3],
|
| 199 |
+
fpn: bool,
|
| 200 |
+
trainable_layers: int,
|
| 201 |
+
returned_layers: Optional[List[int]] = None,
|
| 202 |
+
extra_blocks: Optional[ExtraFPNBlock] = None,
|
| 203 |
+
norm_layer: Optional[Callable[..., nn.Module]] = None,
|
| 204 |
+
) -> nn.Module:
|
| 205 |
+
backbone = backbone.features
|
| 206 |
+
# Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks.
|
| 207 |
+
# The first and last blocks are always included because they are the C0 (conv1) and Cn.
|
| 208 |
+
stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1]
|
| 209 |
+
num_stages = len(stage_indices)
|
| 210 |
+
|
| 211 |
+
# find the index of the layer from which we won't freeze
|
| 212 |
+
if trainable_layers < 0 or trainable_layers > num_stages:
|
| 213 |
+
raise ValueError(f"Trainable layers should be in the range [0,{num_stages}], got {trainable_layers} ")
|
| 214 |
+
freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers]
|
| 215 |
+
|
| 216 |
+
for b in backbone[:freeze_before]:
|
| 217 |
+
for parameter in b.parameters():
|
| 218 |
+
parameter.requires_grad_(False)
|
| 219 |
+
|
| 220 |
+
out_channels = 256
|
| 221 |
+
if fpn:
|
| 222 |
+
if extra_blocks is None:
|
| 223 |
+
extra_blocks = LastLevelMaxPool()
|
| 224 |
+
|
| 225 |
+
if returned_layers is None:
|
| 226 |
+
returned_layers = [num_stages - 2, num_stages - 1]
|
| 227 |
+
if min(returned_layers) < 0 or max(returned_layers) >= num_stages:
|
| 228 |
+
raise ValueError(f"Each returned layer should be in the range [0,{num_stages - 1}], got {returned_layers} ")
|
| 229 |
+
return_layers = {f"{stage_indices[k]}": str(v) for v, k in enumerate(returned_layers)}
|
| 230 |
+
|
| 231 |
+
in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers]
|
| 232 |
+
return BackboneWithFPN(
|
| 233 |
+
backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer
|
| 234 |
+
)
|
| 235 |
+
else:
|
| 236 |
+
m = nn.Sequential(
|
| 237 |
+
backbone,
|
| 238 |
+
# depthwise linear combination of channels to reduce their size
|
| 239 |
+
nn.Conv2d(backbone[-1].out_channels, out_channels, 1),
|
| 240 |
+
)
|
| 241 |
+
m.out_channels = out_channels # type: ignore[assignment]
|
| 242 |
+
return m
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/fcos.py
ADDED
|
@@ -0,0 +1,771 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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): minimum size of the image to be rescaled before feeding it to the backbone
|
| 303 |
+
max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
|
| 304 |
+
image_mean (Tuple[float, float, float]): mean values used for input normalization.
|
| 305 |
+
They are generally the mean values of the dataset on which the backbone has been trained
|
| 306 |
+
on
|
| 307 |
+
image_std (Tuple[float, float, float]): std values used for input normalization.
|
| 308 |
+
They are generally the std values of the dataset on which the backbone has been trained on
|
| 309 |
+
anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
|
| 310 |
+
maps. For FCOS, only set one anchor for per position of each level, the width and height equal to
|
| 311 |
+
the stride of feature map, and set aspect ratio = 1.0, so the center of anchor is equivalent to the point
|
| 312 |
+
in FCOS paper.
|
| 313 |
+
head (nn.Module): Module run on top of the feature pyramid.
|
| 314 |
+
Defaults to a module containing a classification and regression module.
|
| 315 |
+
center_sampling_radius (int): radius of the "center" of a groundtruth box,
|
| 316 |
+
within which all anchor points are labeled positive.
|
| 317 |
+
score_thresh (float): Score threshold used for postprocessing the detections.
|
| 318 |
+
nms_thresh (float): NMS threshold used for postprocessing the detections.
|
| 319 |
+
detections_per_img (int): Number of best detections to keep after NMS.
|
| 320 |
+
topk_candidates (int): Number of best detections to keep before NMS.
|
| 321 |
+
|
| 322 |
+
Example:
|
| 323 |
+
|
| 324 |
+
>>> import torch
|
| 325 |
+
>>> import torchvision
|
| 326 |
+
>>> from torchvision.models.detection import FCOS
|
| 327 |
+
>>> from torchvision.models.detection.anchor_utils import AnchorGenerator
|
| 328 |
+
>>> # load a pre-trained model for classification and return
|
| 329 |
+
>>> # only the features
|
| 330 |
+
>>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features
|
| 331 |
+
>>> # FCOS needs to know the number of
|
| 332 |
+
>>> # output channels in a backbone. For mobilenet_v2, it's 1280,
|
| 333 |
+
>>> # so we need to add it here
|
| 334 |
+
>>> backbone.out_channels = 1280
|
| 335 |
+
>>>
|
| 336 |
+
>>> # let's make the network generate 5 x 3 anchors per spatial
|
| 337 |
+
>>> # location, with 5 different sizes and 3 different aspect
|
| 338 |
+
>>> # ratios. We have a Tuple[Tuple[int]] because each feature
|
| 339 |
+
>>> # map could potentially have different sizes and
|
| 340 |
+
>>> # aspect ratios
|
| 341 |
+
>>> anchor_generator = AnchorGenerator(
|
| 342 |
+
>>> sizes=((8,), (16,), (32,), (64,), (128,)),
|
| 343 |
+
>>> aspect_ratios=((1.0,),)
|
| 344 |
+
>>> )
|
| 345 |
+
>>>
|
| 346 |
+
>>> # put the pieces together inside a FCOS model
|
| 347 |
+
>>> model = FCOS(
|
| 348 |
+
>>> backbone,
|
| 349 |
+
>>> num_classes=80,
|
| 350 |
+
>>> anchor_generator=anchor_generator,
|
| 351 |
+
>>> )
|
| 352 |
+
>>> model.eval()
|
| 353 |
+
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
|
| 354 |
+
>>> predictions = model(x)
|
| 355 |
+
"""
|
| 356 |
+
|
| 357 |
+
__annotations__ = {
|
| 358 |
+
"box_coder": det_utils.BoxLinearCoder,
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
def __init__(
|
| 362 |
+
self,
|
| 363 |
+
backbone: nn.Module,
|
| 364 |
+
num_classes: int,
|
| 365 |
+
# transform parameters
|
| 366 |
+
min_size: int = 800,
|
| 367 |
+
max_size: int = 1333,
|
| 368 |
+
image_mean: Optional[List[float]] = None,
|
| 369 |
+
image_std: Optional[List[float]] = None,
|
| 370 |
+
# Anchor parameters
|
| 371 |
+
anchor_generator: Optional[AnchorGenerator] = None,
|
| 372 |
+
head: Optional[nn.Module] = None,
|
| 373 |
+
center_sampling_radius: float = 1.5,
|
| 374 |
+
score_thresh: float = 0.2,
|
| 375 |
+
nms_thresh: float = 0.6,
|
| 376 |
+
detections_per_img: int = 100,
|
| 377 |
+
topk_candidates: int = 1000,
|
| 378 |
+
**kwargs,
|
| 379 |
+
):
|
| 380 |
+
super().__init__()
|
| 381 |
+
_log_api_usage_once(self)
|
| 382 |
+
|
| 383 |
+
if not hasattr(backbone, "out_channels"):
|
| 384 |
+
raise ValueError(
|
| 385 |
+
"backbone should contain an attribute out_channels "
|
| 386 |
+
"specifying the number of output channels (assumed to be the "
|
| 387 |
+
"same for all the levels)"
|
| 388 |
+
)
|
| 389 |
+
self.backbone = backbone
|
| 390 |
+
|
| 391 |
+
if not isinstance(anchor_generator, (AnchorGenerator, type(None))):
|
| 392 |
+
raise TypeError(
|
| 393 |
+
f"anchor_generator should be of type AnchorGenerator or None, instead got {type(anchor_generator)}"
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
if anchor_generator is None:
|
| 397 |
+
anchor_sizes = ((8,), (16,), (32,), (64,), (128,)) # equal to strides of multi-level feature map
|
| 398 |
+
aspect_ratios = ((1.0,),) * len(anchor_sizes) # set only one anchor
|
| 399 |
+
anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios)
|
| 400 |
+
self.anchor_generator = anchor_generator
|
| 401 |
+
if self.anchor_generator.num_anchors_per_location()[0] != 1:
|
| 402 |
+
raise ValueError(
|
| 403 |
+
f"anchor_generator.num_anchors_per_location()[0] should be 1 instead of {anchor_generator.num_anchors_per_location()[0]}"
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
if head is None:
|
| 407 |
+
head = FCOSHead(backbone.out_channels, anchor_generator.num_anchors_per_location()[0], num_classes)
|
| 408 |
+
self.head = head
|
| 409 |
+
|
| 410 |
+
self.box_coder = det_utils.BoxLinearCoder(normalize_by_size=True)
|
| 411 |
+
|
| 412 |
+
if image_mean is None:
|
| 413 |
+
image_mean = [0.485, 0.456, 0.406]
|
| 414 |
+
if image_std is None:
|
| 415 |
+
image_std = [0.229, 0.224, 0.225]
|
| 416 |
+
self.transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs)
|
| 417 |
+
|
| 418 |
+
self.center_sampling_radius = center_sampling_radius
|
| 419 |
+
self.score_thresh = score_thresh
|
| 420 |
+
self.nms_thresh = nms_thresh
|
| 421 |
+
self.detections_per_img = detections_per_img
|
| 422 |
+
self.topk_candidates = topk_candidates
|
| 423 |
+
|
| 424 |
+
# used only on torchscript mode
|
| 425 |
+
self._has_warned = False
|
| 426 |
+
|
| 427 |
+
@torch.jit.unused
|
| 428 |
+
def eager_outputs(
|
| 429 |
+
self, losses: Dict[str, Tensor], detections: List[Dict[str, Tensor]]
|
| 430 |
+
) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]:
|
| 431 |
+
if self.training:
|
| 432 |
+
return losses
|
| 433 |
+
|
| 434 |
+
return detections
|
| 435 |
+
|
| 436 |
+
def compute_loss(
|
| 437 |
+
self,
|
| 438 |
+
targets: List[Dict[str, Tensor]],
|
| 439 |
+
head_outputs: Dict[str, Tensor],
|
| 440 |
+
anchors: List[Tensor],
|
| 441 |
+
num_anchors_per_level: List[int],
|
| 442 |
+
) -> Dict[str, Tensor]:
|
| 443 |
+
matched_idxs = []
|
| 444 |
+
for anchors_per_image, targets_per_image in zip(anchors, targets):
|
| 445 |
+
if targets_per_image["boxes"].numel() == 0:
|
| 446 |
+
matched_idxs.append(
|
| 447 |
+
torch.full((anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device)
|
| 448 |
+
)
|
| 449 |
+
continue
|
| 450 |
+
|
| 451 |
+
gt_boxes = targets_per_image["boxes"]
|
| 452 |
+
gt_centers = (gt_boxes[:, :2] + gt_boxes[:, 2:]) / 2 # Nx2
|
| 453 |
+
anchor_centers = (anchors_per_image[:, :2] + anchors_per_image[:, 2:]) / 2 # N
|
| 454 |
+
anchor_sizes = anchors_per_image[:, 2] - anchors_per_image[:, 0]
|
| 455 |
+
# center sampling: anchor point must be close enough to gt center.
|
| 456 |
+
pairwise_match = (anchor_centers[:, None, :] - gt_centers[None, :, :]).abs_().max(
|
| 457 |
+
dim=2
|
| 458 |
+
).values < self.center_sampling_radius * anchor_sizes[:, None]
|
| 459 |
+
# compute pairwise distance between N points and M boxes
|
| 460 |
+
x, y = anchor_centers.unsqueeze(dim=2).unbind(dim=1) # (N, 1)
|
| 461 |
+
x0, y0, x1, y1 = gt_boxes.unsqueeze(dim=0).unbind(dim=2) # (1, M)
|
| 462 |
+
pairwise_dist = torch.stack([x - x0, y - y0, x1 - x, y1 - y], dim=2) # (N, M)
|
| 463 |
+
|
| 464 |
+
# anchor point must be inside gt
|
| 465 |
+
pairwise_match &= pairwise_dist.min(dim=2).values > 0
|
| 466 |
+
|
| 467 |
+
# each anchor is only responsible for certain scale range.
|
| 468 |
+
lower_bound = anchor_sizes * 4
|
| 469 |
+
lower_bound[: num_anchors_per_level[0]] = 0
|
| 470 |
+
upper_bound = anchor_sizes * 8
|
| 471 |
+
upper_bound[-num_anchors_per_level[-1] :] = float("inf")
|
| 472 |
+
pairwise_dist = pairwise_dist.max(dim=2).values
|
| 473 |
+
pairwise_match &= (pairwise_dist > lower_bound[:, None]) & (pairwise_dist < upper_bound[:, None])
|
| 474 |
+
|
| 475 |
+
# match the GT box with minimum area, if there are multiple GT matches
|
| 476 |
+
gt_areas = (gt_boxes[:, 2] - gt_boxes[:, 0]) * (gt_boxes[:, 3] - gt_boxes[:, 1]) # N
|
| 477 |
+
pairwise_match = pairwise_match.to(torch.float32) * (1e8 - gt_areas[None, :])
|
| 478 |
+
min_values, matched_idx = pairwise_match.max(dim=1) # R, per-anchor match
|
| 479 |
+
matched_idx[min_values < 1e-5] = -1 # unmatched anchors are assigned -1
|
| 480 |
+
|
| 481 |
+
matched_idxs.append(matched_idx)
|
| 482 |
+
|
| 483 |
+
return self.head.compute_loss(targets, head_outputs, anchors, matched_idxs)
|
| 484 |
+
|
| 485 |
+
def postprocess_detections(
|
| 486 |
+
self, head_outputs: Dict[str, List[Tensor]], anchors: List[List[Tensor]], image_shapes: List[Tuple[int, int]]
|
| 487 |
+
) -> List[Dict[str, Tensor]]:
|
| 488 |
+
class_logits = head_outputs["cls_logits"]
|
| 489 |
+
box_regression = head_outputs["bbox_regression"]
|
| 490 |
+
box_ctrness = head_outputs["bbox_ctrness"]
|
| 491 |
+
|
| 492 |
+
num_images = len(image_shapes)
|
| 493 |
+
|
| 494 |
+
detections: List[Dict[str, Tensor]] = []
|
| 495 |
+
|
| 496 |
+
for index in range(num_images):
|
| 497 |
+
box_regression_per_image = [br[index] for br in box_regression]
|
| 498 |
+
logits_per_image = [cl[index] for cl in class_logits]
|
| 499 |
+
box_ctrness_per_image = [bc[index] for bc in box_ctrness]
|
| 500 |
+
anchors_per_image, image_shape = anchors[index], image_shapes[index]
|
| 501 |
+
|
| 502 |
+
image_boxes = []
|
| 503 |
+
image_scores = []
|
| 504 |
+
image_labels = []
|
| 505 |
+
|
| 506 |
+
for box_regression_per_level, logits_per_level, box_ctrness_per_level, anchors_per_level in zip(
|
| 507 |
+
box_regression_per_image, logits_per_image, box_ctrness_per_image, anchors_per_image
|
| 508 |
+
):
|
| 509 |
+
num_classes = logits_per_level.shape[-1]
|
| 510 |
+
|
| 511 |
+
# remove low scoring boxes
|
| 512 |
+
scores_per_level = torch.sqrt(
|
| 513 |
+
torch.sigmoid(logits_per_level) * torch.sigmoid(box_ctrness_per_level)
|
| 514 |
+
).flatten()
|
| 515 |
+
keep_idxs = scores_per_level > self.score_thresh
|
| 516 |
+
scores_per_level = scores_per_level[keep_idxs]
|
| 517 |
+
topk_idxs = torch.where(keep_idxs)[0]
|
| 518 |
+
|
| 519 |
+
# keep only topk scoring predictions
|
| 520 |
+
num_topk = det_utils._topk_min(topk_idxs, self.topk_candidates, 0)
|
| 521 |
+
scores_per_level, idxs = scores_per_level.topk(num_topk)
|
| 522 |
+
topk_idxs = topk_idxs[idxs]
|
| 523 |
+
|
| 524 |
+
anchor_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor")
|
| 525 |
+
labels_per_level = topk_idxs % num_classes
|
| 526 |
+
|
| 527 |
+
boxes_per_level = self.box_coder.decode(
|
| 528 |
+
box_regression_per_level[anchor_idxs], anchors_per_level[anchor_idxs]
|
| 529 |
+
)
|
| 530 |
+
boxes_per_level = box_ops.clip_boxes_to_image(boxes_per_level, image_shape)
|
| 531 |
+
|
| 532 |
+
image_boxes.append(boxes_per_level)
|
| 533 |
+
image_scores.append(scores_per_level)
|
| 534 |
+
image_labels.append(labels_per_level)
|
| 535 |
+
|
| 536 |
+
image_boxes = torch.cat(image_boxes, dim=0)
|
| 537 |
+
image_scores = torch.cat(image_scores, dim=0)
|
| 538 |
+
image_labels = torch.cat(image_labels, dim=0)
|
| 539 |
+
|
| 540 |
+
# non-maximum suppression
|
| 541 |
+
keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh)
|
| 542 |
+
keep = keep[: self.detections_per_img]
|
| 543 |
+
|
| 544 |
+
detections.append(
|
| 545 |
+
{
|
| 546 |
+
"boxes": image_boxes[keep],
|
| 547 |
+
"scores": image_scores[keep],
|
| 548 |
+
"labels": image_labels[keep],
|
| 549 |
+
}
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
return detections
|
| 553 |
+
|
| 554 |
+
def forward(
|
| 555 |
+
self,
|
| 556 |
+
images: List[Tensor],
|
| 557 |
+
targets: Optional[List[Dict[str, Tensor]]] = None,
|
| 558 |
+
) -> Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]]:
|
| 559 |
+
"""
|
| 560 |
+
Args:
|
| 561 |
+
images (list[Tensor]): images to be processed
|
| 562 |
+
targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)
|
| 563 |
+
|
| 564 |
+
Returns:
|
| 565 |
+
result (list[BoxList] or dict[Tensor]): the output from the model.
|
| 566 |
+
During training, it returns a dict[Tensor] which contains the losses.
|
| 567 |
+
During testing, it returns list[BoxList] contains additional fields
|
| 568 |
+
like `scores`, `labels` and `mask` (for Mask R-CNN models).
|
| 569 |
+
"""
|
| 570 |
+
if self.training:
|
| 571 |
+
|
| 572 |
+
if targets is None:
|
| 573 |
+
torch._assert(False, "targets should not be none when in training mode")
|
| 574 |
+
else:
|
| 575 |
+
for target in targets:
|
| 576 |
+
boxes = target["boxes"]
|
| 577 |
+
torch._assert(isinstance(boxes, torch.Tensor), "Expected target boxes to be of type Tensor.")
|
| 578 |
+
torch._assert(
|
| 579 |
+
len(boxes.shape) == 2 and boxes.shape[-1] == 4,
|
| 580 |
+
f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.",
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
original_image_sizes: List[Tuple[int, int]] = []
|
| 584 |
+
for img in images:
|
| 585 |
+
val = img.shape[-2:]
|
| 586 |
+
torch._assert(
|
| 587 |
+
len(val) == 2,
|
| 588 |
+
f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}",
|
| 589 |
+
)
|
| 590 |
+
original_image_sizes.append((val[0], val[1]))
|
| 591 |
+
|
| 592 |
+
# transform the input
|
| 593 |
+
images, targets = self.transform(images, targets)
|
| 594 |
+
|
| 595 |
+
# Check for degenerate boxes
|
| 596 |
+
if targets is not None:
|
| 597 |
+
for target_idx, target in enumerate(targets):
|
| 598 |
+
boxes = target["boxes"]
|
| 599 |
+
degenerate_boxes = boxes[:, 2:] <= boxes[:, :2]
|
| 600 |
+
if degenerate_boxes.any():
|
| 601 |
+
# print the first degenerate box
|
| 602 |
+
bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0]
|
| 603 |
+
degen_bb: List[float] = boxes[bb_idx].tolist()
|
| 604 |
+
torch._assert(
|
| 605 |
+
False,
|
| 606 |
+
f"All bounding boxes should have positive height and width. Found invalid box {degen_bb} for target at index {target_idx}.",
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
# get the features from the backbone
|
| 610 |
+
features = self.backbone(images.tensors)
|
| 611 |
+
if isinstance(features, torch.Tensor):
|
| 612 |
+
features = OrderedDict([("0", features)])
|
| 613 |
+
|
| 614 |
+
features = list(features.values())
|
| 615 |
+
|
| 616 |
+
# compute the fcos heads outputs using the features
|
| 617 |
+
head_outputs = self.head(features)
|
| 618 |
+
|
| 619 |
+
# create the set of anchors
|
| 620 |
+
anchors = self.anchor_generator(images, features)
|
| 621 |
+
# recover level sizes
|
| 622 |
+
num_anchors_per_level = [x.size(2) * x.size(3) for x in features]
|
| 623 |
+
|
| 624 |
+
losses = {}
|
| 625 |
+
detections: List[Dict[str, Tensor]] = []
|
| 626 |
+
if self.training:
|
| 627 |
+
if targets is None:
|
| 628 |
+
torch._assert(False, "targets should not be none when in training mode")
|
| 629 |
+
else:
|
| 630 |
+
# compute the losses
|
| 631 |
+
losses = self.compute_loss(targets, head_outputs, anchors, num_anchors_per_level)
|
| 632 |
+
else:
|
| 633 |
+
# split outputs per level
|
| 634 |
+
split_head_outputs: Dict[str, List[Tensor]] = {}
|
| 635 |
+
for k in head_outputs:
|
| 636 |
+
split_head_outputs[k] = list(head_outputs[k].split(num_anchors_per_level, dim=1))
|
| 637 |
+
split_anchors = [list(a.split(num_anchors_per_level)) for a in anchors]
|
| 638 |
+
|
| 639 |
+
# compute the detections
|
| 640 |
+
detections = self.postprocess_detections(split_head_outputs, split_anchors, images.image_sizes)
|
| 641 |
+
detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes)
|
| 642 |
+
|
| 643 |
+
if torch.jit.is_scripting():
|
| 644 |
+
if not self._has_warned:
|
| 645 |
+
warnings.warn("FCOS always returns a (Losses, Detections) tuple in scripting")
|
| 646 |
+
self._has_warned = True
|
| 647 |
+
return losses, detections
|
| 648 |
+
return self.eager_outputs(losses, detections)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class FCOS_ResNet50_FPN_Weights(WeightsEnum):
|
| 652 |
+
COCO_V1 = Weights(
|
| 653 |
+
url="https://download.pytorch.org/models/fcos_resnet50_fpn_coco-99b0c9b7.pth",
|
| 654 |
+
transforms=ObjectDetection,
|
| 655 |
+
meta={
|
| 656 |
+
"num_params": 32269600,
|
| 657 |
+
"categories": _COCO_CATEGORIES,
|
| 658 |
+
"min_size": (1, 1),
|
| 659 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/detection#fcos-resnet-50-fpn",
|
| 660 |
+
"_metrics": {
|
| 661 |
+
"COCO-val2017": {
|
| 662 |
+
"box_map": 39.2,
|
| 663 |
+
}
|
| 664 |
+
},
|
| 665 |
+
"_ops": 128.207,
|
| 666 |
+
"_file_size": 123.608,
|
| 667 |
+
"_docs": """These weights were produced by following a similar training recipe as on the paper.""",
|
| 668 |
+
},
|
| 669 |
+
)
|
| 670 |
+
DEFAULT = COCO_V1
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
@register_model()
|
| 674 |
+
@handle_legacy_interface(
|
| 675 |
+
weights=("pretrained", FCOS_ResNet50_FPN_Weights.COCO_V1),
|
| 676 |
+
weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
|
| 677 |
+
)
|
| 678 |
+
def fcos_resnet50_fpn(
|
| 679 |
+
*,
|
| 680 |
+
weights: Optional[FCOS_ResNet50_FPN_Weights] = None,
|
| 681 |
+
progress: bool = True,
|
| 682 |
+
num_classes: Optional[int] = None,
|
| 683 |
+
weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
|
| 684 |
+
trainable_backbone_layers: Optional[int] = None,
|
| 685 |
+
**kwargs: Any,
|
| 686 |
+
) -> FCOS:
|
| 687 |
+
"""
|
| 688 |
+
Constructs a FCOS model with a ResNet-50-FPN backbone.
|
| 689 |
+
|
| 690 |
+
.. betastatus:: detection module
|
| 691 |
+
|
| 692 |
+
Reference: `FCOS: Fully Convolutional One-Stage Object Detection <https://arxiv.org/abs/1904.01355>`_.
|
| 693 |
+
`FCOS: A simple and strong anchor-free object detector <https://arxiv.org/abs/2006.09214>`_.
|
| 694 |
+
|
| 695 |
+
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
|
| 696 |
+
image, and should be in ``0-1`` range. Different images can have different sizes.
|
| 697 |
+
|
| 698 |
+
The behavior of the model changes depending on if it is in training or evaluation mode.
|
| 699 |
+
|
| 700 |
+
During training, the model expects both the input tensors and targets (list of dictionary),
|
| 701 |
+
containing:
|
| 702 |
+
|
| 703 |
+
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
|
| 704 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 705 |
+
- labels (``Int64Tensor[N]``): the class label for each ground-truth box
|
| 706 |
+
|
| 707 |
+
The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
|
| 708 |
+
losses.
|
| 709 |
+
|
| 710 |
+
During inference, the model requires only the input tensors, and returns the post-processed
|
| 711 |
+
predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
|
| 712 |
+
follows, where ``N`` is the number of detections:
|
| 713 |
+
|
| 714 |
+
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
|
| 715 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 716 |
+
- labels (``Int64Tensor[N]``): the predicted labels for each detection
|
| 717 |
+
- scores (``Tensor[N]``): the scores of each detection
|
| 718 |
+
|
| 719 |
+
For more details on the output, you may refer to :ref:`instance_seg_output`.
|
| 720 |
+
|
| 721 |
+
Example:
|
| 722 |
+
|
| 723 |
+
>>> model = torchvision.models.detection.fcos_resnet50_fpn(weights=FCOS_ResNet50_FPN_Weights.DEFAULT)
|
| 724 |
+
>>> model.eval()
|
| 725 |
+
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
|
| 726 |
+
>>> predictions = model(x)
|
| 727 |
+
|
| 728 |
+
Args:
|
| 729 |
+
weights (:class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights`, optional): The
|
| 730 |
+
pretrained weights to use. See
|
| 731 |
+
:class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights`
|
| 732 |
+
below for more details, and possible values. By default, no
|
| 733 |
+
pre-trained weights are used.
|
| 734 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 735 |
+
num_classes (int, optional): number of output classes of the model (including the background)
|
| 736 |
+
weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for
|
| 737 |
+
the backbone.
|
| 738 |
+
trainable_backbone_layers (int, optional): number of trainable (not frozen) resnet layers starting
|
| 739 |
+
from final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
|
| 740 |
+
trainable. If ``None`` is passed (the default) this value is set to 3. Default: None
|
| 741 |
+
**kwargs: parameters passed to the ``torchvision.models.detection.FCOS``
|
| 742 |
+
base class. Please refer to the `source code
|
| 743 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/detection/fcos.py>`_
|
| 744 |
+
for more details about this class.
|
| 745 |
+
|
| 746 |
+
.. autoclass:: torchvision.models.detection.FCOS_ResNet50_FPN_Weights
|
| 747 |
+
:members:
|
| 748 |
+
"""
|
| 749 |
+
weights = FCOS_ResNet50_FPN_Weights.verify(weights)
|
| 750 |
+
weights_backbone = ResNet50_Weights.verify(weights_backbone)
|
| 751 |
+
|
| 752 |
+
if weights is not None:
|
| 753 |
+
weights_backbone = None
|
| 754 |
+
num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
|
| 755 |
+
elif num_classes is None:
|
| 756 |
+
num_classes = 91
|
| 757 |
+
|
| 758 |
+
is_trained = weights is not None or weights_backbone is not None
|
| 759 |
+
trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
|
| 760 |
+
norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
|
| 761 |
+
|
| 762 |
+
backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
|
| 763 |
+
backbone = _resnet_fpn_extractor(
|
| 764 |
+
backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(256, 256)
|
| 765 |
+
)
|
| 766 |
+
model = FCOS(backbone, num_classes, **kwargs)
|
| 767 |
+
|
| 768 |
+
if weights is not None:
|
| 769 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 770 |
+
|
| 771 |
+
return model
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/keypoint_rcnn.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torchvision.ops import MultiScaleRoIAlign
|
| 6 |
+
|
| 7 |
+
from ...ops import misc as misc_nn_ops
|
| 8 |
+
from ...transforms._presets import ObjectDetection
|
| 9 |
+
from .._api import register_model, Weights, WeightsEnum
|
| 10 |
+
from .._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES
|
| 11 |
+
from .._utils import _ovewrite_value_param, handle_legacy_interface
|
| 12 |
+
from ..resnet import resnet50, ResNet50_Weights
|
| 13 |
+
from ._utils import overwrite_eps
|
| 14 |
+
from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
|
| 15 |
+
from .faster_rcnn import FasterRCNN
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"KeypointRCNN",
|
| 20 |
+
"KeypointRCNN_ResNet50_FPN_Weights",
|
| 21 |
+
"keypointrcnn_resnet50_fpn",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class KeypointRCNN(FasterRCNN):
|
| 26 |
+
"""
|
| 27 |
+
Implements Keypoint R-CNN.
|
| 28 |
+
|
| 29 |
+
The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
|
| 30 |
+
image, and should be in 0-1 range. Different images can have different sizes.
|
| 31 |
+
|
| 32 |
+
The behavior of the model changes depending on if it is in training or evaluation mode.
|
| 33 |
+
|
| 34 |
+
During training, the model expects both the input tensors and targets (list of dictionary),
|
| 35 |
+
containing:
|
| 36 |
+
|
| 37 |
+
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
|
| 38 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 39 |
+
- labels (Int64Tensor[N]): the class label for each ground-truth box
|
| 40 |
+
- keypoints (FloatTensor[N, K, 3]): the K keypoints location for each of the N instances, in the
|
| 41 |
+
format [x, y, visibility], where visibility=0 means that the keypoint is not visible.
|
| 42 |
+
|
| 43 |
+
The model returns a Dict[Tensor] during training, containing the classification and regression
|
| 44 |
+
losses for both the RPN and the R-CNN, and the keypoint loss.
|
| 45 |
+
|
| 46 |
+
During inference, the model requires only the input tensors, and returns the post-processed
|
| 47 |
+
predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
|
| 48 |
+
follows:
|
| 49 |
+
|
| 50 |
+
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
|
| 51 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 52 |
+
- labels (Int64Tensor[N]): the predicted labels for each image
|
| 53 |
+
- scores (Tensor[N]): the scores or each prediction
|
| 54 |
+
- keypoints (FloatTensor[N, K, 3]): the locations of the predicted keypoints, in [x, y, v] format.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
backbone (nn.Module): the network used to compute the features for the model.
|
| 58 |
+
It should contain an out_channels attribute, which indicates the number of output
|
| 59 |
+
channels that each feature map has (and it should be the same for all feature maps).
|
| 60 |
+
The backbone should return a single Tensor or and OrderedDict[Tensor].
|
| 61 |
+
num_classes (int): number of output classes of the model (including the background).
|
| 62 |
+
If box_predictor is specified, num_classes should be None.
|
| 63 |
+
min_size (int): minimum size of the image to be rescaled before feeding it to the backbone
|
| 64 |
+
max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
|
| 65 |
+
image_mean (Tuple[float, float, float]): mean values used for input normalization.
|
| 66 |
+
They are generally the mean values of the dataset on which the backbone has been trained
|
| 67 |
+
on
|
| 68 |
+
image_std (Tuple[float, float, float]): std values used for input normalization.
|
| 69 |
+
They are generally the std values of the dataset on which the backbone has been trained on
|
| 70 |
+
rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
|
| 71 |
+
maps.
|
| 72 |
+
rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
|
| 73 |
+
rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
|
| 74 |
+
rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
|
| 75 |
+
rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
|
| 76 |
+
rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
|
| 77 |
+
rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
|
| 78 |
+
rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
|
| 79 |
+
considered as positive during training of the RPN.
|
| 80 |
+
rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
|
| 81 |
+
considered as negative during training of the RPN.
|
| 82 |
+
rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
|
| 83 |
+
for computing the loss
|
| 84 |
+
rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
|
| 85 |
+
of the RPN
|
| 86 |
+
rpn_score_thresh (float): during inference, only return proposals with a classification score
|
| 87 |
+
greater than rpn_score_thresh
|
| 88 |
+
box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
|
| 89 |
+
the locations indicated by the bounding boxes
|
| 90 |
+
box_head (nn.Module): module that takes the cropped feature maps as input
|
| 91 |
+
box_predictor (nn.Module): module that takes the output of box_head and returns the
|
| 92 |
+
classification logits and box regression deltas.
|
| 93 |
+
box_score_thresh (float): during inference, only return proposals with a classification score
|
| 94 |
+
greater than box_score_thresh
|
| 95 |
+
box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
|
| 96 |
+
box_detections_per_img (int): maximum number of detections per image, for all classes.
|
| 97 |
+
box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
|
| 98 |
+
considered as positive during training of the classification head
|
| 99 |
+
box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
|
| 100 |
+
considered as negative during training of the classification head
|
| 101 |
+
box_batch_size_per_image (int): number of proposals that are sampled during training of the
|
| 102 |
+
classification head
|
| 103 |
+
box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
|
| 104 |
+
of the classification head
|
| 105 |
+
bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
|
| 106 |
+
bounding boxes
|
| 107 |
+
keypoint_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
|
| 108 |
+
the locations indicated by the bounding boxes, which will be used for the keypoint head.
|
| 109 |
+
keypoint_head (nn.Module): module that takes the cropped feature maps as input
|
| 110 |
+
keypoint_predictor (nn.Module): module that takes the output of the keypoint_head and returns the
|
| 111 |
+
heatmap logits
|
| 112 |
+
|
| 113 |
+
Example::
|
| 114 |
+
|
| 115 |
+
>>> import torch
|
| 116 |
+
>>> import torchvision
|
| 117 |
+
>>> from torchvision.models.detection import KeypointRCNN
|
| 118 |
+
>>> from torchvision.models.detection.anchor_utils import AnchorGenerator
|
| 119 |
+
>>>
|
| 120 |
+
>>> # load a pre-trained model for classification and return
|
| 121 |
+
>>> # only the features
|
| 122 |
+
>>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features
|
| 123 |
+
>>> # KeypointRCNN needs to know the number of
|
| 124 |
+
>>> # output channels in a backbone. For mobilenet_v2, it's 1280,
|
| 125 |
+
>>> # so we need to add it here
|
| 126 |
+
>>> backbone.out_channels = 1280
|
| 127 |
+
>>>
|
| 128 |
+
>>> # let's make the RPN generate 5 x 3 anchors per spatial
|
| 129 |
+
>>> # location, with 5 different sizes and 3 different aspect
|
| 130 |
+
>>> # ratios. We have a Tuple[Tuple[int]] because each feature
|
| 131 |
+
>>> # map could potentially have different sizes and
|
| 132 |
+
>>> # aspect ratios
|
| 133 |
+
>>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
|
| 134 |
+
>>> aspect_ratios=((0.5, 1.0, 2.0),))
|
| 135 |
+
>>>
|
| 136 |
+
>>> # let's define what are the feature maps that we will
|
| 137 |
+
>>> # use to perform the region of interest cropping, as well as
|
| 138 |
+
>>> # the size of the crop after rescaling.
|
| 139 |
+
>>> # if your backbone returns a Tensor, featmap_names is expected to
|
| 140 |
+
>>> # be ['0']. More generally, the backbone should return an
|
| 141 |
+
>>> # OrderedDict[Tensor], and in featmap_names you can choose which
|
| 142 |
+
>>> # feature maps to use.
|
| 143 |
+
>>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
|
| 144 |
+
>>> output_size=7,
|
| 145 |
+
>>> sampling_ratio=2)
|
| 146 |
+
>>>
|
| 147 |
+
>>> keypoint_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
|
| 148 |
+
>>> output_size=14,
|
| 149 |
+
>>> sampling_ratio=2)
|
| 150 |
+
>>> # put the pieces together inside a KeypointRCNN model
|
| 151 |
+
>>> model = KeypointRCNN(backbone,
|
| 152 |
+
>>> num_classes=2,
|
| 153 |
+
>>> rpn_anchor_generator=anchor_generator,
|
| 154 |
+
>>> box_roi_pool=roi_pooler,
|
| 155 |
+
>>> keypoint_roi_pool=keypoint_roi_pooler)
|
| 156 |
+
>>> model.eval()
|
| 157 |
+
>>> model.eval()
|
| 158 |
+
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
|
| 159 |
+
>>> predictions = model(x)
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def __init__(
|
| 163 |
+
self,
|
| 164 |
+
backbone,
|
| 165 |
+
num_classes=None,
|
| 166 |
+
# transform parameters
|
| 167 |
+
min_size=None,
|
| 168 |
+
max_size=1333,
|
| 169 |
+
image_mean=None,
|
| 170 |
+
image_std=None,
|
| 171 |
+
# RPN parameters
|
| 172 |
+
rpn_anchor_generator=None,
|
| 173 |
+
rpn_head=None,
|
| 174 |
+
rpn_pre_nms_top_n_train=2000,
|
| 175 |
+
rpn_pre_nms_top_n_test=1000,
|
| 176 |
+
rpn_post_nms_top_n_train=2000,
|
| 177 |
+
rpn_post_nms_top_n_test=1000,
|
| 178 |
+
rpn_nms_thresh=0.7,
|
| 179 |
+
rpn_fg_iou_thresh=0.7,
|
| 180 |
+
rpn_bg_iou_thresh=0.3,
|
| 181 |
+
rpn_batch_size_per_image=256,
|
| 182 |
+
rpn_positive_fraction=0.5,
|
| 183 |
+
rpn_score_thresh=0.0,
|
| 184 |
+
# Box parameters
|
| 185 |
+
box_roi_pool=None,
|
| 186 |
+
box_head=None,
|
| 187 |
+
box_predictor=None,
|
| 188 |
+
box_score_thresh=0.05,
|
| 189 |
+
box_nms_thresh=0.5,
|
| 190 |
+
box_detections_per_img=100,
|
| 191 |
+
box_fg_iou_thresh=0.5,
|
| 192 |
+
box_bg_iou_thresh=0.5,
|
| 193 |
+
box_batch_size_per_image=512,
|
| 194 |
+
box_positive_fraction=0.25,
|
| 195 |
+
bbox_reg_weights=None,
|
| 196 |
+
# keypoint parameters
|
| 197 |
+
keypoint_roi_pool=None,
|
| 198 |
+
keypoint_head=None,
|
| 199 |
+
keypoint_predictor=None,
|
| 200 |
+
num_keypoints=None,
|
| 201 |
+
**kwargs,
|
| 202 |
+
):
|
| 203 |
+
|
| 204 |
+
if not isinstance(keypoint_roi_pool, (MultiScaleRoIAlign, type(None))):
|
| 205 |
+
raise TypeError(
|
| 206 |
+
"keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}"
|
| 207 |
+
)
|
| 208 |
+
if min_size is None:
|
| 209 |
+
min_size = (640, 672, 704, 736, 768, 800)
|
| 210 |
+
|
| 211 |
+
if num_keypoints is not None:
|
| 212 |
+
if keypoint_predictor is not None:
|
| 213 |
+
raise ValueError("num_keypoints should be None when keypoint_predictor is specified")
|
| 214 |
+
else:
|
| 215 |
+
num_keypoints = 17
|
| 216 |
+
|
| 217 |
+
out_channels = backbone.out_channels
|
| 218 |
+
|
| 219 |
+
if keypoint_roi_pool is None:
|
| 220 |
+
keypoint_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2)
|
| 221 |
+
|
| 222 |
+
if keypoint_head is None:
|
| 223 |
+
keypoint_layers = tuple(512 for _ in range(8))
|
| 224 |
+
keypoint_head = KeypointRCNNHeads(out_channels, keypoint_layers)
|
| 225 |
+
|
| 226 |
+
if keypoint_predictor is None:
|
| 227 |
+
keypoint_dim_reduced = 512 # == keypoint_layers[-1]
|
| 228 |
+
keypoint_predictor = KeypointRCNNPredictor(keypoint_dim_reduced, num_keypoints)
|
| 229 |
+
|
| 230 |
+
super().__init__(
|
| 231 |
+
backbone,
|
| 232 |
+
num_classes,
|
| 233 |
+
# transform parameters
|
| 234 |
+
min_size,
|
| 235 |
+
max_size,
|
| 236 |
+
image_mean,
|
| 237 |
+
image_std,
|
| 238 |
+
# RPN-specific parameters
|
| 239 |
+
rpn_anchor_generator,
|
| 240 |
+
rpn_head,
|
| 241 |
+
rpn_pre_nms_top_n_train,
|
| 242 |
+
rpn_pre_nms_top_n_test,
|
| 243 |
+
rpn_post_nms_top_n_train,
|
| 244 |
+
rpn_post_nms_top_n_test,
|
| 245 |
+
rpn_nms_thresh,
|
| 246 |
+
rpn_fg_iou_thresh,
|
| 247 |
+
rpn_bg_iou_thresh,
|
| 248 |
+
rpn_batch_size_per_image,
|
| 249 |
+
rpn_positive_fraction,
|
| 250 |
+
rpn_score_thresh,
|
| 251 |
+
# Box parameters
|
| 252 |
+
box_roi_pool,
|
| 253 |
+
box_head,
|
| 254 |
+
box_predictor,
|
| 255 |
+
box_score_thresh,
|
| 256 |
+
box_nms_thresh,
|
| 257 |
+
box_detections_per_img,
|
| 258 |
+
box_fg_iou_thresh,
|
| 259 |
+
box_bg_iou_thresh,
|
| 260 |
+
box_batch_size_per_image,
|
| 261 |
+
box_positive_fraction,
|
| 262 |
+
bbox_reg_weights,
|
| 263 |
+
**kwargs,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
self.roi_heads.keypoint_roi_pool = keypoint_roi_pool
|
| 267 |
+
self.roi_heads.keypoint_head = keypoint_head
|
| 268 |
+
self.roi_heads.keypoint_predictor = keypoint_predictor
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class KeypointRCNNHeads(nn.Sequential):
|
| 272 |
+
def __init__(self, in_channels, layers):
|
| 273 |
+
d = []
|
| 274 |
+
next_feature = in_channels
|
| 275 |
+
for out_channels in layers:
|
| 276 |
+
d.append(nn.Conv2d(next_feature, out_channels, 3, stride=1, padding=1))
|
| 277 |
+
d.append(nn.ReLU(inplace=True))
|
| 278 |
+
next_feature = out_channels
|
| 279 |
+
super().__init__(*d)
|
| 280 |
+
for m in self.children():
|
| 281 |
+
if isinstance(m, nn.Conv2d):
|
| 282 |
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
| 283 |
+
nn.init.constant_(m.bias, 0)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class KeypointRCNNPredictor(nn.Module):
|
| 287 |
+
def __init__(self, in_channels, num_keypoints):
|
| 288 |
+
super().__init__()
|
| 289 |
+
input_features = in_channels
|
| 290 |
+
deconv_kernel = 4
|
| 291 |
+
self.kps_score_lowres = nn.ConvTranspose2d(
|
| 292 |
+
input_features,
|
| 293 |
+
num_keypoints,
|
| 294 |
+
deconv_kernel,
|
| 295 |
+
stride=2,
|
| 296 |
+
padding=deconv_kernel // 2 - 1,
|
| 297 |
+
)
|
| 298 |
+
nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu")
|
| 299 |
+
nn.init.constant_(self.kps_score_lowres.bias, 0)
|
| 300 |
+
self.up_scale = 2
|
| 301 |
+
self.out_channels = num_keypoints
|
| 302 |
+
|
| 303 |
+
def forward(self, x):
|
| 304 |
+
x = self.kps_score_lowres(x)
|
| 305 |
+
return torch.nn.functional.interpolate(
|
| 306 |
+
x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
_COMMON_META = {
|
| 311 |
+
"categories": _COCO_PERSON_CATEGORIES,
|
| 312 |
+
"keypoint_names": _COCO_PERSON_KEYPOINT_NAMES,
|
| 313 |
+
"min_size": (1, 1),
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class KeypointRCNN_ResNet50_FPN_Weights(WeightsEnum):
|
| 318 |
+
COCO_LEGACY = Weights(
|
| 319 |
+
url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-9f466800.pth",
|
| 320 |
+
transforms=ObjectDetection,
|
| 321 |
+
meta={
|
| 322 |
+
**_COMMON_META,
|
| 323 |
+
"num_params": 59137258,
|
| 324 |
+
"recipe": "https://github.com/pytorch/vision/issues/1606",
|
| 325 |
+
"_metrics": {
|
| 326 |
+
"COCO-val2017": {
|
| 327 |
+
"box_map": 50.6,
|
| 328 |
+
"kp_map": 61.1,
|
| 329 |
+
}
|
| 330 |
+
},
|
| 331 |
+
"_ops": 133.924,
|
| 332 |
+
"_file_size": 226.054,
|
| 333 |
+
"_docs": """
|
| 334 |
+
These weights were produced by following a similar training recipe as on the paper but use a checkpoint
|
| 335 |
+
from an early epoch.
|
| 336 |
+
""",
|
| 337 |
+
},
|
| 338 |
+
)
|
| 339 |
+
COCO_V1 = Weights(
|
| 340 |
+
url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-fc266e95.pth",
|
| 341 |
+
transforms=ObjectDetection,
|
| 342 |
+
meta={
|
| 343 |
+
**_COMMON_META,
|
| 344 |
+
"num_params": 59137258,
|
| 345 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/detection#keypoint-r-cnn",
|
| 346 |
+
"_metrics": {
|
| 347 |
+
"COCO-val2017": {
|
| 348 |
+
"box_map": 54.6,
|
| 349 |
+
"kp_map": 65.0,
|
| 350 |
+
}
|
| 351 |
+
},
|
| 352 |
+
"_ops": 137.42,
|
| 353 |
+
"_file_size": 226.054,
|
| 354 |
+
"_docs": """These weights were produced by following a similar training recipe as on the paper.""",
|
| 355 |
+
},
|
| 356 |
+
)
|
| 357 |
+
DEFAULT = COCO_V1
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
@register_model()
|
| 361 |
+
@handle_legacy_interface(
|
| 362 |
+
weights=(
|
| 363 |
+
"pretrained",
|
| 364 |
+
lambda kwargs: KeypointRCNN_ResNet50_FPN_Weights.COCO_LEGACY
|
| 365 |
+
if kwargs["pretrained"] == "legacy"
|
| 366 |
+
else KeypointRCNN_ResNet50_FPN_Weights.COCO_V1,
|
| 367 |
+
),
|
| 368 |
+
weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
|
| 369 |
+
)
|
| 370 |
+
def keypointrcnn_resnet50_fpn(
|
| 371 |
+
*,
|
| 372 |
+
weights: Optional[KeypointRCNN_ResNet50_FPN_Weights] = None,
|
| 373 |
+
progress: bool = True,
|
| 374 |
+
num_classes: Optional[int] = None,
|
| 375 |
+
num_keypoints: Optional[int] = None,
|
| 376 |
+
weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
|
| 377 |
+
trainable_backbone_layers: Optional[int] = None,
|
| 378 |
+
**kwargs: Any,
|
| 379 |
+
) -> KeypointRCNN:
|
| 380 |
+
"""
|
| 381 |
+
Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone.
|
| 382 |
+
|
| 383 |
+
.. betastatus:: detection module
|
| 384 |
+
|
| 385 |
+
Reference: `Mask R-CNN <https://arxiv.org/abs/1703.06870>`__.
|
| 386 |
+
|
| 387 |
+
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
|
| 388 |
+
image, and should be in ``0-1`` range. Different images can have different sizes.
|
| 389 |
+
|
| 390 |
+
The behavior of the model changes depending on if it is in training or evaluation mode.
|
| 391 |
+
|
| 392 |
+
During training, the model expects both the input tensors and targets (list of dictionary),
|
| 393 |
+
containing:
|
| 394 |
+
|
| 395 |
+
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
|
| 396 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 397 |
+
- labels (``Int64Tensor[N]``): the class label for each ground-truth box
|
| 398 |
+
- keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the
|
| 399 |
+
format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible.
|
| 400 |
+
|
| 401 |
+
The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
|
| 402 |
+
losses for both the RPN and the R-CNN, and the keypoint loss.
|
| 403 |
+
|
| 404 |
+
During inference, the model requires only the input tensors, and returns the post-processed
|
| 405 |
+
predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
|
| 406 |
+
follows, where ``N`` is the number of detected instances:
|
| 407 |
+
|
| 408 |
+
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
|
| 409 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 410 |
+
- labels (``Int64Tensor[N]``): the predicted labels for each instance
|
| 411 |
+
- scores (``Tensor[N]``): the scores or each instance
|
| 412 |
+
- keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format.
|
| 413 |
+
|
| 414 |
+
For more details on the output, you may refer to :ref:`instance_seg_output`.
|
| 415 |
+
|
| 416 |
+
Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
|
| 417 |
+
|
| 418 |
+
Example::
|
| 419 |
+
|
| 420 |
+
>>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(weights=KeypointRCNN_ResNet50_FPN_Weights.DEFAULT)
|
| 421 |
+
>>> model.eval()
|
| 422 |
+
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
|
| 423 |
+
>>> predictions = model(x)
|
| 424 |
+
>>>
|
| 425 |
+
>>> # optionally, if you want to export the model to ONNX:
|
| 426 |
+
>>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11)
|
| 427 |
+
|
| 428 |
+
Args:
|
| 429 |
+
weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The
|
| 430 |
+
pretrained weights to use. See
|
| 431 |
+
:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`
|
| 432 |
+
below for more details, and possible values. By default, no
|
| 433 |
+
pre-trained weights are used.
|
| 434 |
+
progress (bool): If True, displays a progress bar of the download to stderr
|
| 435 |
+
num_classes (int, optional): number of output classes of the model (including the background)
|
| 436 |
+
num_keypoints (int, optional): number of keypoints
|
| 437 |
+
weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
|
| 438 |
+
pretrained weights for the backbone.
|
| 439 |
+
trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block.
|
| 440 |
+
Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
|
| 441 |
+
passed (the default) this value is set to 3.
|
| 442 |
+
|
| 443 |
+
.. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights
|
| 444 |
+
:members:
|
| 445 |
+
"""
|
| 446 |
+
weights = KeypointRCNN_ResNet50_FPN_Weights.verify(weights)
|
| 447 |
+
weights_backbone = ResNet50_Weights.verify(weights_backbone)
|
| 448 |
+
|
| 449 |
+
if weights is not None:
|
| 450 |
+
weights_backbone = None
|
| 451 |
+
num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
|
| 452 |
+
num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"]))
|
| 453 |
+
else:
|
| 454 |
+
if num_classes is None:
|
| 455 |
+
num_classes = 2
|
| 456 |
+
if num_keypoints is None:
|
| 457 |
+
num_keypoints = 17
|
| 458 |
+
|
| 459 |
+
is_trained = weights is not None or weights_backbone is not None
|
| 460 |
+
trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
|
| 461 |
+
norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
|
| 462 |
+
|
| 463 |
+
backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
|
| 464 |
+
backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
|
| 465 |
+
model = KeypointRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs)
|
| 466 |
+
|
| 467 |
+
if weights is not None:
|
| 468 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 469 |
+
if weights == KeypointRCN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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
from typing import Any, Callable, Optional
|
| 3 |
+
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torchvision.ops import MultiScaleRoIAlign
|
| 6 |
+
|
| 7 |
+
from ...ops import misc as misc_nn_ops
|
| 8 |
+
from ...transforms._presets import ObjectDetection
|
| 9 |
+
from .._api import register_model, Weights, WeightsEnum
|
| 10 |
+
from .._meta import _COCO_CATEGORIES
|
| 11 |
+
from .._utils import _ovewrite_value_param, handle_legacy_interface
|
| 12 |
+
from ..resnet import resnet50, ResNet50_Weights
|
| 13 |
+
from ._utils import overwrite_eps
|
| 14 |
+
from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
|
| 15 |
+
from .faster_rcnn import _default_anchorgen, FasterRCNN, FastRCNNConvFCHead, RPNHead
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"MaskRCNN",
|
| 20 |
+
"MaskRCNN_ResNet50_FPN_Weights",
|
| 21 |
+
"MaskRCNN_ResNet50_FPN_V2_Weights",
|
| 22 |
+
"maskrcnn_resnet50_fpn",
|
| 23 |
+
"maskrcnn_resnet50_fpn_v2",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class MaskRCNN(FasterRCNN):
|
| 28 |
+
"""
|
| 29 |
+
Implements Mask R-CNN.
|
| 30 |
+
|
| 31 |
+
The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
|
| 32 |
+
image, and should be in 0-1 range. Different images can have different sizes.
|
| 33 |
+
|
| 34 |
+
The behavior of the model changes depending on if it is in training or evaluation mode.
|
| 35 |
+
|
| 36 |
+
During training, the model expects both the input tensors and targets (list of dictionary),
|
| 37 |
+
containing:
|
| 38 |
+
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
|
| 39 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 40 |
+
- labels (Int64Tensor[N]): the class label for each ground-truth box
|
| 41 |
+
- masks (UInt8Tensor[N, H, W]): the segmentation binary masks for each instance
|
| 42 |
+
|
| 43 |
+
The model returns a Dict[Tensor] during training, containing the classification and regression
|
| 44 |
+
losses for both the RPN and the R-CNN, and the mask loss.
|
| 45 |
+
|
| 46 |
+
During inference, the model requires only the input tensors, and returns the post-processed
|
| 47 |
+
predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
|
| 48 |
+
follows:
|
| 49 |
+
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
|
| 50 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 51 |
+
- labels (Int64Tensor[N]): the predicted labels for each image
|
| 52 |
+
- scores (Tensor[N]): the scores or each prediction
|
| 53 |
+
- masks (UInt8Tensor[N, 1, H, W]): the predicted masks for each instance, in 0-1 range. In order to
|
| 54 |
+
obtain the final segmentation masks, the soft masks can be thresholded, generally
|
| 55 |
+
with a value of 0.5 (mask >= 0.5)
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
backbone (nn.Module): the network used to compute the features for the model.
|
| 59 |
+
It should contain an out_channels attribute, which indicates the number of output
|
| 60 |
+
channels that each feature map has (and it should be the same for all feature maps).
|
| 61 |
+
The backbone should return a single Tensor or and OrderedDict[Tensor].
|
| 62 |
+
num_classes (int): number of output classes of the model (including the background).
|
| 63 |
+
If box_predictor is specified, num_classes should be None.
|
| 64 |
+
min_size (int): minimum size of the image to be rescaled before feeding it to the backbone
|
| 65 |
+
max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
|
| 66 |
+
image_mean (Tuple[float, float, float]): mean values used for input normalization.
|
| 67 |
+
They are generally the mean values of the dataset on which the backbone has been trained
|
| 68 |
+
on
|
| 69 |
+
image_std (Tuple[float, float, float]): std values used for input normalization.
|
| 70 |
+
They are generally the std values of the dataset on which the backbone has been trained on
|
| 71 |
+
rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
|
| 72 |
+
maps.
|
| 73 |
+
rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
|
| 74 |
+
rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
|
| 75 |
+
rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
|
| 76 |
+
rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
|
| 77 |
+
rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
|
| 78 |
+
rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
|
| 79 |
+
rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
|
| 80 |
+
considered as positive during training of the RPN.
|
| 81 |
+
rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
|
| 82 |
+
considered as negative during training of the RPN.
|
| 83 |
+
rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
|
| 84 |
+
for computing the loss
|
| 85 |
+
rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
|
| 86 |
+
of the RPN
|
| 87 |
+
rpn_score_thresh (float): during inference, only return proposals with a classification score
|
| 88 |
+
greater than rpn_score_thresh
|
| 89 |
+
box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
|
| 90 |
+
the locations indicated by the bounding boxes
|
| 91 |
+
box_head (nn.Module): module that takes the cropped feature maps as input
|
| 92 |
+
box_predictor (nn.Module): module that takes the output of box_head and returns the
|
| 93 |
+
classification logits and box regression deltas.
|
| 94 |
+
box_score_thresh (float): during inference, only return proposals with a classification score
|
| 95 |
+
greater than box_score_thresh
|
| 96 |
+
box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
|
| 97 |
+
box_detections_per_img (int): maximum number of detections per image, for all classes.
|
| 98 |
+
box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
|
| 99 |
+
considered as positive during training of the classification head
|
| 100 |
+
box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
|
| 101 |
+
considered as negative during training of the classification head
|
| 102 |
+
box_batch_size_per_image (int): number of proposals that are sampled during training of the
|
| 103 |
+
classification head
|
| 104 |
+
box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
|
| 105 |
+
of the classification head
|
| 106 |
+
bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
|
| 107 |
+
bounding boxes
|
| 108 |
+
mask_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
|
| 109 |
+
the locations indicated by the bounding boxes, which will be used for the mask head.
|
| 110 |
+
mask_head (nn.Module): module that takes the cropped feature maps as input
|
| 111 |
+
mask_predictor (nn.Module): module that takes the output of the mask_head and returns the
|
| 112 |
+
segmentation mask logits
|
| 113 |
+
|
| 114 |
+
Example::
|
| 115 |
+
|
| 116 |
+
>>> import torch
|
| 117 |
+
>>> import torchvision
|
| 118 |
+
>>> from torchvision.models.detection import MaskRCNN
|
| 119 |
+
>>> from torchvision.models.detection.anchor_utils import AnchorGenerator
|
| 120 |
+
>>>
|
| 121 |
+
>>> # load a pre-trained model for classification and return
|
| 122 |
+
>>> # only the features
|
| 123 |
+
>>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features
|
| 124 |
+
>>> # MaskRCNN needs to know the number of
|
| 125 |
+
>>> # output channels in a backbone. For mobilenet_v2, it's 1280
|
| 126 |
+
>>> # so we need to add it here,
|
| 127 |
+
>>> backbone.out_channels = 1280
|
| 128 |
+
>>>
|
| 129 |
+
>>> # let's make the RPN generate 5 x 3 anchors per spatial
|
| 130 |
+
>>> # location, with 5 different sizes and 3 different aspect
|
| 131 |
+
>>> # ratios. We have a Tuple[Tuple[int]] because each feature
|
| 132 |
+
>>> # map could potentially have different sizes and
|
| 133 |
+
>>> # aspect ratios
|
| 134 |
+
>>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
|
| 135 |
+
>>> aspect_ratios=((0.5, 1.0, 2.0),))
|
| 136 |
+
>>>
|
| 137 |
+
>>> # let's define what are the feature maps that we will
|
| 138 |
+
>>> # use to perform the region of interest cropping, as well as
|
| 139 |
+
>>> # the size of the crop after rescaling.
|
| 140 |
+
>>> # if your backbone returns a Tensor, featmap_names is expected to
|
| 141 |
+
>>> # be ['0']. More generally, the backbone should return an
|
| 142 |
+
>>> # OrderedDict[Tensor], and in featmap_names you can choose which
|
| 143 |
+
>>> # feature maps to use.
|
| 144 |
+
>>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
|
| 145 |
+
>>> output_size=7,
|
| 146 |
+
>>> sampling_ratio=2)
|
| 147 |
+
>>>
|
| 148 |
+
>>> mask_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
|
| 149 |
+
>>> output_size=14,
|
| 150 |
+
>>> sampling_ratio=2)
|
| 151 |
+
>>> # put the pieces together inside a MaskRCNN model
|
| 152 |
+
>>> model = MaskRCNN(backbone,
|
| 153 |
+
>>> num_classes=2,
|
| 154 |
+
>>> rpn_anchor_generator=anchor_generator,
|
| 155 |
+
>>> box_roi_pool=roi_pooler,
|
| 156 |
+
>>> mask_roi_pool=mask_roi_pooler)
|
| 157 |
+
>>> model.eval()
|
| 158 |
+
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
|
| 159 |
+
>>> predictions = model(x)
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def __init__(
|
| 163 |
+
self,
|
| 164 |
+
backbone,
|
| 165 |
+
num_classes=None,
|
| 166 |
+
# transform parameters
|
| 167 |
+
min_size=800,
|
| 168 |
+
max_size=1333,
|
| 169 |
+
image_mean=None,
|
| 170 |
+
image_std=None,
|
| 171 |
+
# RPN parameters
|
| 172 |
+
rpn_anchor_generator=None,
|
| 173 |
+
rpn_head=None,
|
| 174 |
+
rpn_pre_nms_top_n_train=2000,
|
| 175 |
+
rpn_pre_nms_top_n_test=1000,
|
| 176 |
+
rpn_post_nms_top_n_train=2000,
|
| 177 |
+
rpn_post_nms_top_n_test=1000,
|
| 178 |
+
rpn_nms_thresh=0.7,
|
| 179 |
+
rpn_fg_iou_thresh=0.7,
|
| 180 |
+
rpn_bg_iou_thresh=0.3,
|
| 181 |
+
rpn_batch_size_per_image=256,
|
| 182 |
+
rpn_positive_fraction=0.5,
|
| 183 |
+
rpn_score_thresh=0.0,
|
| 184 |
+
# Box parameters
|
| 185 |
+
box_roi_pool=None,
|
| 186 |
+
box_head=None,
|
| 187 |
+
box_predictor=None,
|
| 188 |
+
box_score_thresh=0.05,
|
| 189 |
+
box_nms_thresh=0.5,
|
| 190 |
+
box_detections_per_img=100,
|
| 191 |
+
box_fg_iou_thresh=0.5,
|
| 192 |
+
box_bg_iou_thresh=0.5,
|
| 193 |
+
box_batch_size_per_image=512,
|
| 194 |
+
box_positive_fraction=0.25,
|
| 195 |
+
bbox_reg_weights=None,
|
| 196 |
+
# Mask parameters
|
| 197 |
+
mask_roi_pool=None,
|
| 198 |
+
mask_head=None,
|
| 199 |
+
mask_predictor=None,
|
| 200 |
+
**kwargs,
|
| 201 |
+
):
|
| 202 |
+
|
| 203 |
+
if not isinstance(mask_roi_pool, (MultiScaleRoIAlign, type(None))):
|
| 204 |
+
raise TypeError(
|
| 205 |
+
f"mask_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(mask_roi_pool)}"
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
if num_classes is not None:
|
| 209 |
+
if mask_predictor is not None:
|
| 210 |
+
raise ValueError("num_classes should be None when mask_predictor is specified")
|
| 211 |
+
|
| 212 |
+
out_channels = backbone.out_channels
|
| 213 |
+
|
| 214 |
+
if mask_roi_pool is None:
|
| 215 |
+
mask_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2)
|
| 216 |
+
|
| 217 |
+
if mask_head is None:
|
| 218 |
+
mask_layers = (256, 256, 256, 256)
|
| 219 |
+
mask_dilation = 1
|
| 220 |
+
mask_head = MaskRCNNHeads(out_channels, mask_layers, mask_dilation)
|
| 221 |
+
|
| 222 |
+
if mask_predictor is None:
|
| 223 |
+
mask_predictor_in_channels = 256 # == mask_layers[-1]
|
| 224 |
+
mask_dim_reduced = 256
|
| 225 |
+
mask_predictor = MaskRCNNPredictor(mask_predictor_in_channels, mask_dim_reduced, num_classes)
|
| 226 |
+
|
| 227 |
+
super().__init__(
|
| 228 |
+
backbone,
|
| 229 |
+
num_classes,
|
| 230 |
+
# transform parameters
|
| 231 |
+
min_size,
|
| 232 |
+
max_size,
|
| 233 |
+
image_mean,
|
| 234 |
+
image_std,
|
| 235 |
+
# RPN-specific parameters
|
| 236 |
+
rpn_anchor_generator,
|
| 237 |
+
rpn_head,
|
| 238 |
+
rpn_pre_nms_top_n_train,
|
| 239 |
+
rpn_pre_nms_top_n_test,
|
| 240 |
+
rpn_post_nms_top_n_train,
|
| 241 |
+
rpn_post_nms_top_n_test,
|
| 242 |
+
rpn_nms_thresh,
|
| 243 |
+
rpn_fg_iou_thresh,
|
| 244 |
+
rpn_bg_iou_thresh,
|
| 245 |
+
rpn_batch_size_per_image,
|
| 246 |
+
rpn_positive_fraction,
|
| 247 |
+
rpn_score_thresh,
|
| 248 |
+
# Box parameters
|
| 249 |
+
box_roi_pool,
|
| 250 |
+
box_head,
|
| 251 |
+
box_predictor,
|
| 252 |
+
box_score_thresh,
|
| 253 |
+
box_nms_thresh,
|
| 254 |
+
box_detections_per_img,
|
| 255 |
+
box_fg_iou_thresh,
|
| 256 |
+
box_bg_iou_thresh,
|
| 257 |
+
box_batch_size_per_image,
|
| 258 |
+
box_positive_fraction,
|
| 259 |
+
bbox_reg_weights,
|
| 260 |
+
**kwargs,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
self.roi_heads.mask_roi_pool = mask_roi_pool
|
| 264 |
+
self.roi_heads.mask_head = mask_head
|
| 265 |
+
self.roi_heads.mask_predictor = mask_predictor
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class MaskRCNNHeads(nn.Sequential):
|
| 269 |
+
_version = 2
|
| 270 |
+
|
| 271 |
+
def __init__(self, in_channels, layers, dilation, norm_layer: Optional[Callable[..., nn.Module]] = None):
|
| 272 |
+
"""
|
| 273 |
+
Args:
|
| 274 |
+
in_channels (int): number of input channels
|
| 275 |
+
layers (list): feature dimensions of each FCN layer
|
| 276 |
+
dilation (int): dilation rate of kernel
|
| 277 |
+
norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
|
| 278 |
+
"""
|
| 279 |
+
blocks = []
|
| 280 |
+
next_feature = in_channels
|
| 281 |
+
for layer_features in layers:
|
| 282 |
+
blocks.append(
|
| 283 |
+
misc_nn_ops.Conv2dNormActivation(
|
| 284 |
+
next_feature,
|
| 285 |
+
layer_features,
|
| 286 |
+
kernel_size=3,
|
| 287 |
+
stride=1,
|
| 288 |
+
padding=dilation,
|
| 289 |
+
dilation=dilation,
|
| 290 |
+
norm_layer=norm_layer,
|
| 291 |
+
)
|
| 292 |
+
)
|
| 293 |
+
next_feature = layer_features
|
| 294 |
+
|
| 295 |
+
super().__init__(*blocks)
|
| 296 |
+
for layer in self.modules():
|
| 297 |
+
if isinstance(layer, nn.Conv2d):
|
| 298 |
+
nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu")
|
| 299 |
+
if layer.bias is not None:
|
| 300 |
+
nn.init.zeros_(layer.bias)
|
| 301 |
+
|
| 302 |
+
def _load_from_state_dict(
|
| 303 |
+
self,
|
| 304 |
+
state_dict,
|
| 305 |
+
prefix,
|
| 306 |
+
local_metadata,
|
| 307 |
+
strict,
|
| 308 |
+
missing_keys,
|
| 309 |
+
unexpected_keys,
|
| 310 |
+
error_msgs,
|
| 311 |
+
):
|
| 312 |
+
version = local_metadata.get("version", None)
|
| 313 |
+
|
| 314 |
+
if version is None or version < 2:
|
| 315 |
+
num_blocks = len(self)
|
| 316 |
+
for i in range(num_blocks):
|
| 317 |
+
for type in ["weight", "bias"]:
|
| 318 |
+
old_key = f"{prefix}mask_fcn{i+1}.{type}"
|
| 319 |
+
new_key = f"{prefix}{i}.0.{type}"
|
| 320 |
+
if old_key in state_dict:
|
| 321 |
+
state_dict[new_key] = state_dict.pop(old_key)
|
| 322 |
+
|
| 323 |
+
super()._load_from_state_dict(
|
| 324 |
+
state_dict,
|
| 325 |
+
prefix,
|
| 326 |
+
local_metadata,
|
| 327 |
+
strict,
|
| 328 |
+
missing_keys,
|
| 329 |
+
unexpected_keys,
|
| 330 |
+
error_msgs,
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
class MaskRCNNPredictor(nn.Sequential):
|
| 335 |
+
def __init__(self, in_channels, dim_reduced, num_classes):
|
| 336 |
+
super().__init__(
|
| 337 |
+
OrderedDict(
|
| 338 |
+
[
|
| 339 |
+
("conv5_mask", nn.ConvTranspose2d(in_channels, dim_reduced, 2, 2, 0)),
|
| 340 |
+
("relu", nn.ReLU(inplace=True)),
|
| 341 |
+
("mask_fcn_logits", nn.Conv2d(dim_reduced, num_classes, 1, 1, 0)),
|
| 342 |
+
]
|
| 343 |
+
)
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
for name, param in self.named_parameters():
|
| 347 |
+
if "weight" in name:
|
| 348 |
+
nn.init.kaiming_normal_(param, mode="fan_out", nonlinearity="relu")
|
| 349 |
+
# elif "bias" in name:
|
| 350 |
+
# nn.init.constant_(param, 0)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
_COMMON_META = {
|
| 354 |
+
"categories": _COCO_CATEGORIES,
|
| 355 |
+
"min_size": (1, 1),
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class MaskRCNN_ResNet50_FPN_Weights(WeightsEnum):
|
| 360 |
+
COCO_V1 = Weights(
|
| 361 |
+
url="https://download.pytorch.org/models/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth",
|
| 362 |
+
transforms=ObjectDetection,
|
| 363 |
+
meta={
|
| 364 |
+
**_COMMON_META,
|
| 365 |
+
"num_params": 44401393,
|
| 366 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/detection#mask-r-cnn",
|
| 367 |
+
"_metrics": {
|
| 368 |
+
"COCO-val2017": {
|
| 369 |
+
"box_map": 37.9,
|
| 370 |
+
"mask_map": 34.6,
|
| 371 |
+
}
|
| 372 |
+
},
|
| 373 |
+
"_ops": 134.38,
|
| 374 |
+
"_file_size": 169.84,
|
| 375 |
+
"_docs": """These weights were produced by following a similar training recipe as on the paper.""",
|
| 376 |
+
},
|
| 377 |
+
)
|
| 378 |
+
DEFAULT = COCO_V1
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class MaskRCNN_ResNet50_FPN_V2_Weights(WeightsEnum):
|
| 382 |
+
COCO_V1 = Weights(
|
| 383 |
+
url="https://download.pytorch.org/models/maskrcnn_resnet50_fpn_v2_coco-73cbd019.pth",
|
| 384 |
+
transforms=ObjectDetection,
|
| 385 |
+
meta={
|
| 386 |
+
**_COMMON_META,
|
| 387 |
+
"num_params": 46359409,
|
| 388 |
+
"recipe": "https://github.com/pytorch/vision/pull/5773",
|
| 389 |
+
"_metrics": {
|
| 390 |
+
"COCO-val2017": {
|
| 391 |
+
"box_map": 47.4,
|
| 392 |
+
"mask_map": 41.8,
|
| 393 |
+
}
|
| 394 |
+
},
|
| 395 |
+
"_ops": 333.577,
|
| 396 |
+
"_file_size": 177.219,
|
| 397 |
+
"_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""",
|
| 398 |
+
},
|
| 399 |
+
)
|
| 400 |
+
DEFAULT = COCO_V1
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
@register_model()
|
| 404 |
+
@handle_legacy_interface(
|
| 405 |
+
weights=("pretrained", MaskRCNN_ResNet50_FPN_Weights.COCO_V1),
|
| 406 |
+
weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
|
| 407 |
+
)
|
| 408 |
+
def maskrcnn_resnet50_fpn(
|
| 409 |
+
*,
|
| 410 |
+
weights: Optional[MaskRCNN_ResNet50_FPN_Weights] = None,
|
| 411 |
+
progress: bool = True,
|
| 412 |
+
num_classes: Optional[int] = None,
|
| 413 |
+
weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
|
| 414 |
+
trainable_backbone_layers: Optional[int] = None,
|
| 415 |
+
**kwargs: Any,
|
| 416 |
+
) -> MaskRCNN:
|
| 417 |
+
"""Mask R-CNN model with a ResNet-50-FPN backbone from the `Mask R-CNN
|
| 418 |
+
<https://arxiv.org/abs/1703.06870>`_ paper.
|
| 419 |
+
|
| 420 |
+
.. betastatus:: detection module
|
| 421 |
+
|
| 422 |
+
The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
|
| 423 |
+
image, and should be in ``0-1`` range. Different images can have different sizes.
|
| 424 |
+
|
| 425 |
+
The behavior of the model changes depending on if it is in training or evaluation mode.
|
| 426 |
+
|
| 427 |
+
During training, the model expects both the input tensors and targets (list of dictionary),
|
| 428 |
+
containing:
|
| 429 |
+
|
| 430 |
+
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
|
| 431 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 432 |
+
- labels (``Int64Tensor[N]``): the class label for each ground-truth box
|
| 433 |
+
- masks (``UInt8Tensor[N, H, W]``): the segmentation binary masks for each instance
|
| 434 |
+
|
| 435 |
+
The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
|
| 436 |
+
losses for both the RPN and the R-CNN, and the mask loss.
|
| 437 |
+
|
| 438 |
+
During inference, the model requires only the input tensors, and returns the post-processed
|
| 439 |
+
predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
|
| 440 |
+
follows, where ``N`` is the number of detected instances:
|
| 441 |
+
|
| 442 |
+
- boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
|
| 443 |
+
``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
|
| 444 |
+
- labels (``Int64Tensor[N]``): the predicted labels for each instance
|
| 445 |
+
- scores (``Tensor[N]``): the scores or each instance
|
| 446 |
+
- masks (``UInt8Tensor[N, 1, H, W]``): the predicted masks for each instance, in ``0-1`` range. In order to
|
| 447 |
+
obtain the final segmentation masks, the soft masks can be thresholded, generally
|
| 448 |
+
with a value of 0.5 (``mask >= 0.5``)
|
| 449 |
+
|
| 450 |
+
For more details on the output and on how to plot the masks, you may refer to :ref:`instance_seg_output`.
|
| 451 |
+
|
| 452 |
+
Mask R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
|
| 453 |
+
|
| 454 |
+
Example::
|
| 455 |
+
|
| 456 |
+
>>> model = torchvision.models.detection.maskrcnn_resnet50_fpn(weights=MaskRCNN_ResNet50_FPN_Weights.DEFAULT)
|
| 457 |
+
>>> model.eval()
|
| 458 |
+
>>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
|
| 459 |
+
>>> predictions = model(x)
|
| 460 |
+
>>>
|
| 461 |
+
>>> # optionally, if you want to export the model to ONNX:
|
| 462 |
+
>>> torch.onnx.export(model, x, "mask_rcnn.onnx", opset_version = 11)
|
| 463 |
+
|
| 464 |
+
Args:
|
| 465 |
+
weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights`, optional): The
|
| 466 |
+
pretrained weights to use. See
|
| 467 |
+
:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights` below for
|
| 468 |
+
more details, and possible values. By default, no pre-trained
|
| 469 |
+
weights are used.
|
| 470 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 471 |
+
download to stderr. Default is True.
|
| 472 |
+
num_classes (int, optional): number of output classes of the model (including the background)
|
| 473 |
+
weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
|
| 474 |
+
pretrained weights for the backbone.
|
| 475 |
+
trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
|
| 476 |
+
final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
|
| 477 |
+
trainable. If ``None`` is passed (the default) this value is set to 3.
|
| 478 |
+
**kwargs: parameters passed to the ``torchvision.models.detection.mask_rcnn.MaskRCNN``
|
| 479 |
+
base class. Please refer to the `source code
|
| 480 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/detection/mask_rcnn.py>`_
|
| 481 |
+
for more details about this class.
|
| 482 |
+
|
| 483 |
+
.. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights
|
| 484 |
+
:members:
|
| 485 |
+
"""
|
| 486 |
+
weights = MaskRCNN_ResNet50_FPN_Weights.verify(weights)
|
| 487 |
+
weights_backbone = ResNet50_Weights.verify(weights_backbone)
|
| 488 |
+
|
| 489 |
+
if weights is not None:
|
| 490 |
+
weights_backbone = None
|
| 491 |
+
num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
|
| 492 |
+
elif num_classes is None:
|
| 493 |
+
num_classes = 91
|
| 494 |
+
|
| 495 |
+
is_trained = weights is not None or weights_backbone is not None
|
| 496 |
+
trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
|
| 497 |
+
norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
|
| 498 |
+
|
| 499 |
+
backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
|
| 500 |
+
backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
|
| 501 |
+
model = MaskRCNN(backbone, num_classes=num_classes, **kwargs)
|
| 502 |
+
|
| 503 |
+
if weights is not None:
|
| 504 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 505 |
+
if weights == MaskRCNN_ResNet50_FPN_Weights.COCO_V1:
|
| 506 |
+
overwrite_eps(model, 0.0)
|
| 507 |
+
|
| 508 |
+
return model
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
@register_model()
|
| 512 |
+
@handle_legacy_interface(
|
| 513 |
+
weights=("pretrained", MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1),
|
| 514 |
+
weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
|
| 515 |
+
)
|
| 516 |
+
def maskrcnn_resnet50_fpn_v2(
|
| 517 |
+
*,
|
| 518 |
+
weights: Optional[MaskRCNN_ResNet50_FPN_V2_Weights] = None,
|
| 519 |
+
progress: bool = True,
|
| 520 |
+
num_classes: Optional[int] = None,
|
| 521 |
+
weights_backbone: Optional[ResNet50_Weights] = None,
|
| 522 |
+
trainable_backbone_layers: Optional[int] = None,
|
| 523 |
+
**kwargs: Any,
|
| 524 |
+
) -> MaskRCNN:
|
| 525 |
+
"""Improved Mask R-CNN model with a ResNet-50-FPN backbone from the `Benchmarking Detection Transfer
|
| 526 |
+
Learning with Vision Transformers <https://arxiv.org/abs/2111.11429>`_ paper.
|
| 527 |
+
|
| 528 |
+
.. betastatus:: detection module
|
| 529 |
+
|
| 530 |
+
:func:`~torchvision.models.detection.maskrcnn_resnet50_fpn` for more details.
|
| 531 |
+
|
| 532 |
+
Args:
|
| 533 |
+
weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights`, optional): The
|
| 534 |
+
pretrained weights to use. See
|
| 535 |
+
:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights` below for
|
| 536 |
+
more details, and possible values. By default, no pre-trained
|
| 537 |
+
weights are used.
|
| 538 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 539 |
+
download to stderr. Default is True.
|
| 540 |
+
num_classes (int, optional): number of output classes of the model (including the background)
|
| 541 |
+
weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
|
| 542 |
+
pretrained weights for the backbone.
|
| 543 |
+
trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
|
| 544 |
+
final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
|
| 545 |
+
trainable. If ``None`` is passed (the default) this value is set to 3.
|
| 546 |
+
**kwargs: parameters passed to the ``torchvision.models.detection.mask_rcnn.MaskRCNN``
|
| 547 |
+
base class. Please refer to the `source code
|
| 548 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/detection/mask_rcnn.py>`_
|
| 549 |
+
for more details about this class.
|
| 550 |
+
|
| 551 |
+
.. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights
|
| 552 |
+
:members:
|
| 553 |
+
"""
|
| 554 |
+
weights = MaskRCNN_ResNet50_FPN_V2_Weights.verify(weights)
|
| 555 |
+
weights_backbone = ResNet50_Weights.verify(weights_backbone)
|
| 556 |
+
|
| 557 |
+
if weights is not None:
|
| 558 |
+
weights_backbone = None
|
| 559 |
+
num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
|
| 560 |
+
elif num_classes is None:
|
| 561 |
+
num_classes = 91
|
| 562 |
+
|
| 563 |
+
is_trained = weights is not None or weights_backbone is not None
|
| 564 |
+
trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
|
| 565 |
+
|
| 566 |
+
backbone = resnet50(weights=weights_backbone, progress=progress)
|
| 567 |
+
backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d)
|
| 568 |
+
rpn_anchor_generator = _default_anchorgen()
|
| 569 |
+
rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2)
|
| 570 |
+
box_head = FastRCNNConvFCHead(
|
| 571 |
+
(backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d
|
| 572 |
+
)
|
| 573 |
+
mask_head = MaskRCNNHeads(backbone.out_channels, [256, 256, 256, 256], 1, norm_layer=nn.BatchNorm2d)
|
| 574 |
+
model = MaskRCNN(
|
| 575 |
+
backbone,
|
| 576 |
+
num_classes=num_classes,
|
| 577 |
+
rpn_anchor_generator=rpn_anchor_generator,
|
| 578 |
+
rpn_head=rpn_head,
|
| 579 |
+
box_head=box_head,
|
| 580 |
+
mask_head=mask_head,
|
| 581 |
+
**kwargs,
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
if weights is not None:
|
| 585 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 586 |
+
|
| 587 |
+
return model
|
wemm/lib/python3.10/site-packages/torchvision/models/detection/rpn.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn, Tensor
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
from torchvision.ops import boxes as box_ops, Conv2dNormActivation
|
| 7 |
+
|
| 8 |
+
from . import _utils as det_utils
|
| 9 |
+
|
| 10 |
+
# Import AnchorGenerator to keep compatibility.
|
| 11 |
+
from .anchor_utils import AnchorGenerator # noqa: 401
|
| 12 |
+
from .image_list import ImageList
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class RPNHead(nn.Module):
|
| 16 |
+
"""
|
| 17 |
+
Adds a simple RPN Head with classification and regression heads
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
in_channels (int): number of channels of the input feature
|
| 21 |
+
num_anchors (int): number of anchors to be predicted
|
| 22 |
+
conv_depth (int, optional): number of convolutions
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
_version = 2
|
| 26 |
+
|
| 27 |
+
def __init__(self, in_channels: int, num_anchors: int, conv_depth=1) -> None:
|
| 28 |
+
super().__init__()
|
| 29 |
+
convs = []
|
| 30 |
+
for _ in range(conv_depth):
|
| 31 |
+
convs.append(Conv2dNormActivation(in_channels, in_channels, kernel_size=3, norm_layer=None))
|
| 32 |
+
self.conv = nn.Sequential(*convs)
|
| 33 |
+
self.cls_logits = nn.Conv2d(in_channels, num_anchors, kernel_size=1, stride=1)
|
| 34 |
+
self.bbox_pred = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=1, stride=1)
|
| 35 |
+
|
| 36 |
+
for layer in self.modules():
|
| 37 |
+
if isinstance(layer, nn.Conv2d):
|
| 38 |
+
torch.nn.init.normal_(layer.weight, std=0.01) # type: ignore[arg-type]
|
| 39 |
+
if layer.bias is not None:
|
| 40 |
+
torch.nn.init.constant_(layer.bias, 0) # type: ignore[arg-type]
|
| 41 |
+
|
| 42 |
+
def _load_from_state_dict(
|
| 43 |
+
self,
|
| 44 |
+
state_dict,
|
| 45 |
+
prefix,
|
| 46 |
+
local_metadata,
|
| 47 |
+
strict,
|
| 48 |
+
missing_keys,
|
| 49 |
+
unexpected_keys,
|
| 50 |
+
error_msgs,
|
| 51 |
+
):
|
| 52 |
+
version = local_metadata.get("version", None)
|
| 53 |
+
|
| 54 |
+
if version is None or version < 2:
|
| 55 |
+
for type in ["weight", "bias"]:
|
| 56 |
+
old_key = f"{prefix}conv.{type}"
|
| 57 |
+
new_key = f"{prefix}conv.0.0.{type}"
|
| 58 |
+
if old_key in state_dict:
|
| 59 |
+
state_dict[new_key] = state_dict.pop(old_key)
|
| 60 |
+
|
| 61 |
+
super()._load_from_state_dict(
|
| 62 |
+
state_dict,
|
| 63 |
+
prefix,
|
| 64 |
+
local_metadata,
|
| 65 |
+
strict,
|
| 66 |
+
missing_keys,
|
| 67 |
+
unexpected_keys,
|
| 68 |
+
error_msgs,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def forward(self, x: List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]:
|
| 72 |
+
logits = []
|
| 73 |
+
bbox_reg = []
|
| 74 |
+
for feature in x:
|
| 75 |
+
t = self.conv(feature)
|
| 76 |
+
logits.append(self.cls_logits(t))
|
| 77 |
+
bbox_reg.append(self.bbox_pred(t))
|
| 78 |
+
return logits, bbox_reg
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def permute_and_flatten(layer: Tensor, N: int, A: int, C: int, H: int, W: int) -> Tensor:
|
| 82 |
+
layer = layer.view(N, -1, C, H, W)
|
| 83 |
+
layer = layer.permute(0, 3, 4, 1, 2)
|
| 84 |
+
layer = layer.reshape(N, -1, C)
|
| 85 |
+
return layer
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def concat_box_prediction_layers(box_cls: List[Tensor], box_regression: List[Tensor]) -> Tuple[Tensor, Tensor]:
|
| 89 |
+
box_cls_flattened = []
|
| 90 |
+
box_regression_flattened = []
|
| 91 |
+
# for each feature level, permute the outputs to make them be in the
|
| 92 |
+
# same format as the labels. Note that the labels are computed for
|
| 93 |
+
# all feature levels concatenated, so we keep the same representation
|
| 94 |
+
# for the objectness and the box_regression
|
| 95 |
+
for box_cls_per_level, box_regression_per_level in zip(box_cls, box_regression):
|
| 96 |
+
N, AxC, H, W = box_cls_per_level.shape
|
| 97 |
+
Ax4 = box_regression_per_level.shape[1]
|
| 98 |
+
A = Ax4 // 4
|
| 99 |
+
C = AxC // A
|
| 100 |
+
box_cls_per_level = permute_and_flatten(box_cls_per_level, N, A, C, H, W)
|
| 101 |
+
box_cls_flattened.append(box_cls_per_level)
|
| 102 |
+
|
| 103 |
+
box_regression_per_level = permute_and_flatten(box_regression_per_level, N, A, 4, H, W)
|
| 104 |
+
box_regression_flattened.append(box_regression_per_level)
|
| 105 |
+
# concatenate on the first dimension (representing the feature levels), to
|
| 106 |
+
# take into account the way the labels were generated (with all feature maps
|
| 107 |
+
# being concatenated as well)
|
| 108 |
+
box_cls = torch.cat(box_cls_flattened, dim=1).flatten(0, -2)
|
| 109 |
+
box_regression = torch.cat(box_regression_flattened, dim=1).reshape(-1, 4)
|
| 110 |
+
return box_cls, box_regression
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class RegionProposalNetwork(torch.nn.Module):
|
| 114 |
+
"""
|
| 115 |
+
Implements Region Proposal Network (RPN).
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
|
| 119 |
+
maps.
|
| 120 |
+
head (nn.Module): module that computes the objectness and regression deltas
|
| 121 |
+
fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
|
| 122 |
+
considered as positive during training of the RPN.
|
| 123 |
+
bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
|
| 124 |
+
considered as negative during training of the RPN.
|
| 125 |
+
batch_size_per_image (int): number of anchors that are sampled during training of the RPN
|
| 126 |
+
for computing the loss
|
| 127 |
+
positive_fraction (float): proportion of positive anchors in a mini-batch during training
|
| 128 |
+
of the RPN
|
| 129 |
+
pre_nms_top_n (Dict[str, int]): number of proposals to keep before applying NMS. It should
|
| 130 |
+
contain two fields: training and testing, to allow for different values depending
|
| 131 |
+
on training or evaluation
|
| 132 |
+
post_nms_top_n (Dict[str, int]): number of proposals to keep after applying NMS. It should
|
| 133 |
+
contain two fields: training and testing, to allow for different values depending
|
| 134 |
+
on training or evaluation
|
| 135 |
+
nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
__annotations__ = {
|
| 140 |
+
"box_coder": det_utils.BoxCoder,
|
| 141 |
+
"proposal_matcher": det_utils.Matcher,
|
| 142 |
+
"fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
def __init__(
|
| 146 |
+
self,
|
| 147 |
+
anchor_generator: AnchorGenerator,
|
| 148 |
+
head: nn.Module,
|
| 149 |
+
# Faster-RCNN Training
|
| 150 |
+
fg_iou_thresh: float,
|
| 151 |
+
bg_iou_thresh: float,
|
| 152 |
+
batch_size_per_image: int,
|
| 153 |
+
positive_fraction: float,
|
| 154 |
+
# Faster-RCNN Inference
|
| 155 |
+
pre_nms_top_n: Dict[str, int],
|
| 156 |
+
post_nms_top_n: Dict[str, int],
|
| 157 |
+
nms_thresh: float,
|
| 158 |
+
score_thresh: float = 0.0,
|
| 159 |
+
) -> None:
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.anchor_generator = anchor_generator
|
| 162 |
+
self.head = head
|
| 163 |
+
self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0))
|
| 164 |
+
|
| 165 |
+
# used during training
|
| 166 |
+
self.box_similarity = box_ops.box_iou
|
| 167 |
+
|
| 168 |
+
self.proposal_matcher = det_utils.Matcher(
|
| 169 |
+
fg_iou_thresh,
|
| 170 |
+
bg_iou_thresh,
|
| 171 |
+
allow_low_quality_matches=True,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction)
|
| 175 |
+
# used during testing
|
| 176 |
+
self._pre_nms_top_n = pre_nms_top_n
|
| 177 |
+
self._post_nms_top_n = post_nms_top_n
|
| 178 |
+
self.nms_thresh = nms_thresh
|
| 179 |
+
self.score_thresh = score_thresh
|
| 180 |
+
self.min_size = 1e-3
|
| 181 |
+
|
| 182 |
+
def pre_nms_top_n(self) -> int:
|
| 183 |
+
if self.training:
|
| 184 |
+
return self._pre_nms_top_n["training"]
|
| 185 |
+
return self._pre_nms_top_n["testing"]
|
| 186 |
+
|
| 187 |
+
def post_nms_top_n(self) -> int:
|
| 188 |
+
if self.training:
|
| 189 |
+
return self._post_nms_top_n["training"]
|
| 190 |
+
return self._post_nms_top_n["testing"]
|
| 191 |
+
|
| 192 |
+
def assign_targets_to_anchors(
|
| 193 |
+
self, anchors: List[Tensor], targets: List[Dict[str, Tensor]]
|
| 194 |
+
) -> Tuple[List[Tensor], List[Tensor]]:
|
| 195 |
+
|
| 196 |
+
labels = []
|
| 197 |
+
matched_gt_boxes = []
|
| 198 |
+
for anchors_per_image, targets_per_image in zip(anchors, targets):
|
| 199 |
+
gt_boxes = targets_per_image["boxes"]
|
| 200 |
+
|
| 201 |
+
if gt_boxes.numel() == 0:
|
| 202 |
+
# Background image (negative example)
|
| 203 |
+
device = anchors_per_image.device
|
| 204 |
+
matched_gt_boxes_per_image = torch.zeros(anchors_per_image.shape, dtype=torch.float32, device=device)
|
| 205 |
+
labels_per_image = torch.zeros((anchors_per_image.shape[0],), dtype=torch.float32, device=device)
|
| 206 |
+
else:
|
| 207 |
+
match_quality_matrix = self.box_similarity(gt_boxes, anchors_per_image)
|
| 208 |
+
matched_idxs = self.proposal_matcher(match_quality_matrix)
|
| 209 |
+
# get the targets corresponding GT for each proposal
|
| 210 |
+
# NB: need to clamp the indices because we can have a single
|
| 211 |
+
# GT in the image, and matched_idxs can be -2, which goes
|
| 212 |
+
# out of bounds
|
| 213 |
+
matched_gt_boxes_per_image = gt_boxes[matched_idxs.clamp(min=0)]
|
| 214 |
+
|
| 215 |
+
labels_per_image = matched_idxs >= 0
|
| 216 |
+
labels_per_image = labels_per_image.to(dtype=torch.float32)
|
| 217 |
+
|
| 218 |
+
# Background (negative examples)
|
| 219 |
+
bg_indices = matched_idxs == self.proposal_matcher.BELOW_LOW_THRESHOLD
|
| 220 |
+
labels_per_image[bg_indices] = 0.0
|
| 221 |
+
|
| 222 |
+
# discard indices that are between thresholds
|
| 223 |
+
inds_to_discard = matched_idxs == self.proposal_matcher.BETWEEN_THRESHOLDS
|
| 224 |
+
labels_per_image[inds_to_discard] = -1.0
|
| 225 |
+
|
| 226 |
+
labels.append(labels_per_image)
|
| 227 |
+
matched_gt_boxes.append(matched_gt_boxes_per_image)
|
| 228 |
+
return labels, matched_gt_boxes
|
| 229 |
+
|
| 230 |
+
def _get_top_n_idx(self, objectness: Tensor, num_anchors_per_level: List[int]) -> Tensor:
|
| 231 |
+
r = []
|
| 232 |
+
offset = 0
|
| 233 |
+
for ob in objectness.split(num_anchors_per_level, 1):
|
| 234 |
+
num_anchors = ob.shape[1]
|
| 235 |
+
pre_nms_top_n = det_utils._topk_min(ob, self.pre_nms_top_n(), 1)
|
| 236 |
+
_, top_n_idx = ob.topk(pre_nms_top_n, dim=1)
|
| 237 |
+
r.append(top_n_idx + offset)
|
| 238 |
+
offset += num_anchors
|
| 239 |
+
return torch.cat(r, dim=1)
|
| 240 |
+
|
| 241 |
+
def filter_proposals(
|
| 242 |
+
self,
|
| 243 |
+
proposals: Tensor,
|
| 244 |
+
objectness: Tensor,
|
| 245 |
+
image_shapes: List[Tuple[int, int]],
|
| 246 |
+
num_anchors_per_level: List[int],
|
| 247 |
+
) -> Tuple[List[Tensor], List[Tensor]]:
|
| 248 |
+
|
| 249 |
+
num_images = proposals.shape[0]
|
| 250 |
+
device = proposals.device
|
| 251 |
+
# do not backprop through objectness
|
| 252 |
+
objectness = objectness.detach()
|
| 253 |
+
objectness = objectness.reshape(num_images, -1)
|
| 254 |
+
|
| 255 |
+
levels = [
|
| 256 |
+
torch.full((n,), idx, dtype=torch.int64, device=device) for idx, n in enumerate(num_anchors_per_level)
|
| 257 |
+
]
|
| 258 |
+
levels = torch.cat(levels, 0)
|
| 259 |
+
levels = levels.reshape(1, -1).expand_as(objectness)
|
| 260 |
+
|
| 261 |
+
# select top_n boxes independently per level before applying nms
|
| 262 |
+
top_n_idx = self._get_top_n_idx(objectness, num_anchors_per_level)
|
| 263 |
+
|
| 264 |
+
image_range = torch.arange(num_images, device=device)
|
| 265 |
+
batch_idx = image_range[:, None]
|
| 266 |
+
|
| 267 |
+
objectness = objectness[batch_idx, top_n_idx]
|
| 268 |
+
levels = levels[batch_idx, top_n_idx]
|
| 269 |
+
proposals = proposals[batch_idx, top_n_idx]
|
| 270 |
+
|
| 271 |
+
objectness_prob = torch.sigmoid(objectness)
|
| 272 |
+
|
| 273 |
+
final_boxes = []
|
| 274 |
+
final_scores = []
|
| 275 |
+
for boxes, scores, lvl, img_shape in zip(proposals, objectness_prob, levels, image_shapes):
|
| 276 |
+
boxes = box_ops.clip_boxes_to_image(boxes, img_shape)
|
| 277 |
+
|
| 278 |
+
# remove small boxes
|
| 279 |
+
keep = box_ops.remove_small_boxes(boxes, self.min_size)
|
| 280 |
+
boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep]
|
| 281 |
+
|
| 282 |
+
# remove low scoring boxes
|
| 283 |
+
# use >= for Backwards compatibility
|
| 284 |
+
keep = torch.where(scores >= self.score_thresh)[0]
|
| 285 |
+
boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep]
|
| 286 |
+
|
| 287 |
+
# non-maximum suppression, independently done per level
|
| 288 |
+
keep = box_ops.batched_nms(boxes, scores, lvl, self.nms_thresh)
|
| 289 |
+
|
| 290 |
+
# keep only topk scoring predictions
|
| 291 |
+
keep = keep[: self.post_nms_top_n()]
|
| 292 |
+
boxes, scores = boxes[keep], scores[keep]
|
| 293 |
+
|
| 294 |
+
final_boxes.append(boxes)
|
| 295 |
+
final_scores.append(scores)
|
| 296 |
+
return final_boxes, final_scores
|
| 297 |
+
|
| 298 |
+
def compute_loss(
|
| 299 |
+
self, objectness: Tensor, pred_bbox_deltas: Tensor, labels: List[Tensor], regression_targets: List[Tensor]
|
| 300 |
+
) -> Tuple[Tensor, Tensor]:
|
| 301 |
+
"""
|
| 302 |
+
Args:
|
| 303 |
+
objectness (Tensor)
|
| 304 |
+
pred_bbox_deltas (Tensor)
|
| 305 |
+
labels (List[Tensor])
|
| 306 |
+
regression_targets (List[Tensor])
|
| 307 |
+
|
| 308 |
+
Returns:
|
| 309 |
+
objectness_loss (Tensor)
|
| 310 |
+
box_loss (Tensor)
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
|
| 314 |
+
sampled_pos_inds = torch.where(torch.cat(sampled_pos_inds, dim=0))[0]
|
| 315 |
+
sampled_neg_inds = torch.where(torch.cat(sampled_neg_inds, dim=0))[0]
|
| 316 |
+
|
| 317 |
+
sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0)
|
| 318 |
+
|
| 319 |
+
objectness = objectness.flatten()
|
| 320 |
+
|
| 321 |
+
labels = torch.cat(labels, dim=0)
|
| 322 |
+
regression_targets = torch.cat(regression_targets, dim=0)
|
| 323 |
+
|
| 324 |
+
box_loss = F.smooth_l1_loss(
|
| 325 |
+
pred_bbox_deltas[sampled_pos_inds],
|
| 326 |
+
regression_targets[sampled_pos_inds],
|
| 327 |
+
beta=1 / 9,
|
| 328 |
+
reduction="sum",
|
| 329 |
+
) / (sampled_inds.numel())
|
| 330 |
+
|
| 331 |
+
objectness_loss = F.binary_cross_entropy_with_logits(objectness[sampled_inds], labels[sampled_inds])
|
| 332 |
+
|
| 333 |
+
return objectness_loss, box_loss
|
| 334 |
+
|
| 335 |
+
def forward(
|
| 336 |
+
self,
|
| 337 |
+
images: ImageList,
|
| 338 |
+
features: Dict[str, Tensor],
|
| 339 |
+
targets: Optional[List[Dict[str, Tensor]]] = None,
|
| 340 |
+
) -> Tuple[List[Tensor], Dict[str, Tensor]]:
|
| 341 |
+
|
| 342 |
+
"""
|
| 343 |
+
Args:
|
| 344 |
+
images (ImageList): images for which we want to compute the predictions
|
| 345 |
+
features (Dict[str, Tensor]): features computed from the images that are
|
| 346 |
+
used for computing the predictions. Each tensor in the list
|
| 347 |
+
correspond to different feature levels
|
| 348 |
+
targets (List[Dict[str, Tensor]]): ground-truth boxes present in the image (optional).
|
| 349 |
+
If provided, each element in the dict should contain a field `boxes`,
|
| 350 |
+
with the locations of the ground-truth boxes.
|
| 351 |
+
|
| 352 |
+
Returns:
|
| 353 |
+
boxes (List[Tensor]): the predicted boxes from the RPN, one Tensor per
|
| 354 |
+
image.
|
| 355 |
+
losses (Dict[str, Tensor]): the losses for the model during training. During
|
| 356 |
+
testing, it is an empty dict.
|
| 357 |
+
"""
|
| 358 |
+
# RPN uses all feature maps that are available
|
| 359 |
+
features = list(features.values())
|
| 360 |
+
objectness, pred_bbox_deltas = self.head(features)
|
| 361 |
+
anchors = self.anchor_generator(images, features)
|
| 362 |
+
|
| 363 |
+
num_images = len(anchors)
|
| 364 |
+
num_anchors_per_level_shape_tensors = [o[0].shape for o in objectness]
|
| 365 |
+
num_anchors_per_level = [s[0] * s[1] * s[2] for s in num_anchors_per_level_shape_tensors]
|
| 366 |
+
objectness, pred_bbox_deltas = concat_box_prediction_layers(objectness, pred_bbox_deltas)
|
| 367 |
+
# apply pred_bbox_deltas to anchors to obtain the decoded proposals
|
| 368 |
+
# note that we detach the deltas because Faster R-CNN do not backprop through
|
| 369 |
+
# the proposals
|
| 370 |
+
proposals = self.box_coder.decode(pred_bbox_deltas.detach(), anchors)
|
| 371 |
+
proposals = proposals.view(num_images, -1, 4)
|
| 372 |
+
boxes, scores = self.filter_proposals(proposals, objectness, images.image_sizes, num_anchors_per_level)
|
| 373 |
+
|
| 374 |
+
losses = {}
|
| 375 |
+
if self.training:
|
| 376 |
+
if targets is None:
|
| 377 |
+
raise ValueError("targets should not be None")
|
| 378 |
+
labels, matched_gt_boxes = self.assign_targets_to_anchors(anchors, targets)
|
| 379 |
+
regression_targets = self.box_coder.encode(matched_gt_boxes, anchors)
|
| 380 |
+
loss_objectness, loss_rpn_box_reg = self.compute_loss(
|
| 381 |
+
objectness, pred_bbox_deltas, labels, regression_targets
|
| 382 |
+
)
|
| 383 |
+
losses = {
|
| 384 |
+
"loss_objectness": loss_objectness,
|
| 385 |
+
"loss_rpn_box_reg": loss_rpn_box_reg,
|
| 386 |
+
}
|
| 387 |
+
return boxes, losses
|
wemm/lib/python3.10/site-packages/torchvision/models/inception.py
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from collections import namedtuple
|
| 3 |
+
from functools import partial
|
| 4 |
+
from typing import Any, Callable, List, Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch import nn, Tensor
|
| 9 |
+
|
| 10 |
+
from ..transforms._presets import ImageClassification
|
| 11 |
+
from ..utils import _log_api_usage_once
|
| 12 |
+
from ._api import register_model, Weights, WeightsEnum
|
| 13 |
+
from ._meta import _IMAGENET_CATEGORIES
|
| 14 |
+
from ._utils import _ovewrite_named_param, handle_legacy_interface
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__all__ = ["Inception3", "InceptionOutputs", "_InceptionOutputs", "Inception_V3_Weights", "inception_v3"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
InceptionOutputs = namedtuple("InceptionOutputs", ["logits", "aux_logits"])
|
| 21 |
+
InceptionOutputs.__annotations__ = {"logits": Tensor, "aux_logits": Optional[Tensor]}
|
| 22 |
+
|
| 23 |
+
# Script annotations failed with _GoogleNetOutputs = namedtuple ...
|
| 24 |
+
# _InceptionOutputs set here for backwards compat
|
| 25 |
+
_InceptionOutputs = InceptionOutputs
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Inception3(nn.Module):
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
num_classes: int = 1000,
|
| 32 |
+
aux_logits: bool = True,
|
| 33 |
+
transform_input: bool = False,
|
| 34 |
+
inception_blocks: Optional[List[Callable[..., nn.Module]]] = None,
|
| 35 |
+
init_weights: Optional[bool] = None,
|
| 36 |
+
dropout: float = 0.5,
|
| 37 |
+
) -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
_log_api_usage_once(self)
|
| 40 |
+
if inception_blocks is None:
|
| 41 |
+
inception_blocks = [BasicConv2d, InceptionA, InceptionB, InceptionC, InceptionD, InceptionE, InceptionAux]
|
| 42 |
+
if init_weights is None:
|
| 43 |
+
warnings.warn(
|
| 44 |
+
"The default weight initialization of inception_v3 will be changed in future releases of "
|
| 45 |
+
"torchvision. If you wish to keep the old behavior (which leads to long initialization times"
|
| 46 |
+
" due to scipy/scipy#11299), please set init_weights=True.",
|
| 47 |
+
FutureWarning,
|
| 48 |
+
)
|
| 49 |
+
init_weights = True
|
| 50 |
+
if len(inception_blocks) != 7:
|
| 51 |
+
raise ValueError(f"length of inception_blocks should be 7 instead of {len(inception_blocks)}")
|
| 52 |
+
conv_block = inception_blocks[0]
|
| 53 |
+
inception_a = inception_blocks[1]
|
| 54 |
+
inception_b = inception_blocks[2]
|
| 55 |
+
inception_c = inception_blocks[3]
|
| 56 |
+
inception_d = inception_blocks[4]
|
| 57 |
+
inception_e = inception_blocks[5]
|
| 58 |
+
inception_aux = inception_blocks[6]
|
| 59 |
+
|
| 60 |
+
self.aux_logits = aux_logits
|
| 61 |
+
self.transform_input = transform_input
|
| 62 |
+
self.Conv2d_1a_3x3 = conv_block(3, 32, kernel_size=3, stride=2)
|
| 63 |
+
self.Conv2d_2a_3x3 = conv_block(32, 32, kernel_size=3)
|
| 64 |
+
self.Conv2d_2b_3x3 = conv_block(32, 64, kernel_size=3, padding=1)
|
| 65 |
+
self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2)
|
| 66 |
+
self.Conv2d_3b_1x1 = conv_block(64, 80, kernel_size=1)
|
| 67 |
+
self.Conv2d_4a_3x3 = conv_block(80, 192, kernel_size=3)
|
| 68 |
+
self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=2)
|
| 69 |
+
self.Mixed_5b = inception_a(192, pool_features=32)
|
| 70 |
+
self.Mixed_5c = inception_a(256, pool_features=64)
|
| 71 |
+
self.Mixed_5d = inception_a(288, pool_features=64)
|
| 72 |
+
self.Mixed_6a = inception_b(288)
|
| 73 |
+
self.Mixed_6b = inception_c(768, channels_7x7=128)
|
| 74 |
+
self.Mixed_6c = inception_c(768, channels_7x7=160)
|
| 75 |
+
self.Mixed_6d = inception_c(768, channels_7x7=160)
|
| 76 |
+
self.Mixed_6e = inception_c(768, channels_7x7=192)
|
| 77 |
+
self.AuxLogits: Optional[nn.Module] = None
|
| 78 |
+
if aux_logits:
|
| 79 |
+
self.AuxLogits = inception_aux(768, num_classes)
|
| 80 |
+
self.Mixed_7a = inception_d(768)
|
| 81 |
+
self.Mixed_7b = inception_e(1280)
|
| 82 |
+
self.Mixed_7c = inception_e(2048)
|
| 83 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
| 84 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 85 |
+
self.fc = nn.Linear(2048, num_classes)
|
| 86 |
+
if init_weights:
|
| 87 |
+
for m in self.modules():
|
| 88 |
+
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
|
| 89 |
+
stddev = float(m.stddev) if hasattr(m, "stddev") else 0.1 # type: ignore
|
| 90 |
+
torch.nn.init.trunc_normal_(m.weight, mean=0.0, std=stddev, a=-2, b=2)
|
| 91 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 92 |
+
nn.init.constant_(m.weight, 1)
|
| 93 |
+
nn.init.constant_(m.bias, 0)
|
| 94 |
+
|
| 95 |
+
def _transform_input(self, x: Tensor) -> Tensor:
|
| 96 |
+
if self.transform_input:
|
| 97 |
+
x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5
|
| 98 |
+
x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5
|
| 99 |
+
x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5
|
| 100 |
+
x = torch.cat((x_ch0, x_ch1, x_ch2), 1)
|
| 101 |
+
return x
|
| 102 |
+
|
| 103 |
+
def _forward(self, x: Tensor) -> Tuple[Tensor, Optional[Tensor]]:
|
| 104 |
+
# N x 3 x 299 x 299
|
| 105 |
+
x = self.Conv2d_1a_3x3(x)
|
| 106 |
+
# N x 32 x 149 x 149
|
| 107 |
+
x = self.Conv2d_2a_3x3(x)
|
| 108 |
+
# N x 32 x 147 x 147
|
| 109 |
+
x = self.Conv2d_2b_3x3(x)
|
| 110 |
+
# N x 64 x 147 x 147
|
| 111 |
+
x = self.maxpool1(x)
|
| 112 |
+
# N x 64 x 73 x 73
|
| 113 |
+
x = self.Conv2d_3b_1x1(x)
|
| 114 |
+
# N x 80 x 73 x 73
|
| 115 |
+
x = self.Conv2d_4a_3x3(x)
|
| 116 |
+
# N x 192 x 71 x 71
|
| 117 |
+
x = self.maxpool2(x)
|
| 118 |
+
# N x 192 x 35 x 35
|
| 119 |
+
x = self.Mixed_5b(x)
|
| 120 |
+
# N x 256 x 35 x 35
|
| 121 |
+
x = self.Mixed_5c(x)
|
| 122 |
+
# N x 288 x 35 x 35
|
| 123 |
+
x = self.Mixed_5d(x)
|
| 124 |
+
# N x 288 x 35 x 35
|
| 125 |
+
x = self.Mixed_6a(x)
|
| 126 |
+
# N x 768 x 17 x 17
|
| 127 |
+
x = self.Mixed_6b(x)
|
| 128 |
+
# N x 768 x 17 x 17
|
| 129 |
+
x = self.Mixed_6c(x)
|
| 130 |
+
# N x 768 x 17 x 17
|
| 131 |
+
x = self.Mixed_6d(x)
|
| 132 |
+
# N x 768 x 17 x 17
|
| 133 |
+
x = self.Mixed_6e(x)
|
| 134 |
+
# N x 768 x 17 x 17
|
| 135 |
+
aux: Optional[Tensor] = None
|
| 136 |
+
if self.AuxLogits is not None:
|
| 137 |
+
if self.training:
|
| 138 |
+
aux = self.AuxLogits(x)
|
| 139 |
+
# N x 768 x 17 x 17
|
| 140 |
+
x = self.Mixed_7a(x)
|
| 141 |
+
# N x 1280 x 8 x 8
|
| 142 |
+
x = self.Mixed_7b(x)
|
| 143 |
+
# N x 2048 x 8 x 8
|
| 144 |
+
x = self.Mixed_7c(x)
|
| 145 |
+
# N x 2048 x 8 x 8
|
| 146 |
+
# Adaptive average pooling
|
| 147 |
+
x = self.avgpool(x)
|
| 148 |
+
# N x 2048 x 1 x 1
|
| 149 |
+
x = self.dropout(x)
|
| 150 |
+
# N x 2048 x 1 x 1
|
| 151 |
+
x = torch.flatten(x, 1)
|
| 152 |
+
# N x 2048
|
| 153 |
+
x = self.fc(x)
|
| 154 |
+
# N x 1000 (num_classes)
|
| 155 |
+
return x, aux
|
| 156 |
+
|
| 157 |
+
@torch.jit.unused
|
| 158 |
+
def eager_outputs(self, x: Tensor, aux: Optional[Tensor]) -> InceptionOutputs:
|
| 159 |
+
if self.training and self.aux_logits:
|
| 160 |
+
return InceptionOutputs(x, aux)
|
| 161 |
+
else:
|
| 162 |
+
return x # type: ignore[return-value]
|
| 163 |
+
|
| 164 |
+
def forward(self, x: Tensor) -> InceptionOutputs:
|
| 165 |
+
x = self._transform_input(x)
|
| 166 |
+
x, aux = self._forward(x)
|
| 167 |
+
aux_defined = self.training and self.aux_logits
|
| 168 |
+
if torch.jit.is_scripting():
|
| 169 |
+
if not aux_defined:
|
| 170 |
+
warnings.warn("Scripted Inception3 always returns Inception3 Tuple")
|
| 171 |
+
return InceptionOutputs(x, aux)
|
| 172 |
+
else:
|
| 173 |
+
return self.eager_outputs(x, aux)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class InceptionA(nn.Module):
|
| 177 |
+
def __init__(
|
| 178 |
+
self, in_channels: int, pool_features: int, conv_block: Optional[Callable[..., nn.Module]] = None
|
| 179 |
+
) -> None:
|
| 180 |
+
super().__init__()
|
| 181 |
+
if conv_block is None:
|
| 182 |
+
conv_block = BasicConv2d
|
| 183 |
+
self.branch1x1 = conv_block(in_channels, 64, kernel_size=1)
|
| 184 |
+
|
| 185 |
+
self.branch5x5_1 = conv_block(in_channels, 48, kernel_size=1)
|
| 186 |
+
self.branch5x5_2 = conv_block(48, 64, kernel_size=5, padding=2)
|
| 187 |
+
|
| 188 |
+
self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1)
|
| 189 |
+
self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1)
|
| 190 |
+
self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, padding=1)
|
| 191 |
+
|
| 192 |
+
self.branch_pool = conv_block(in_channels, pool_features, kernel_size=1)
|
| 193 |
+
|
| 194 |
+
def _forward(self, x: Tensor) -> List[Tensor]:
|
| 195 |
+
branch1x1 = self.branch1x1(x)
|
| 196 |
+
|
| 197 |
+
branch5x5 = self.branch5x5_1(x)
|
| 198 |
+
branch5x5 = self.branch5x5_2(branch5x5)
|
| 199 |
+
|
| 200 |
+
branch3x3dbl = self.branch3x3dbl_1(x)
|
| 201 |
+
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
|
| 202 |
+
branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
|
| 203 |
+
|
| 204 |
+
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
|
| 205 |
+
branch_pool = self.branch_pool(branch_pool)
|
| 206 |
+
|
| 207 |
+
outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
|
| 208 |
+
return outputs
|
| 209 |
+
|
| 210 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 211 |
+
outputs = self._forward(x)
|
| 212 |
+
return torch.cat(outputs, 1)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class InceptionB(nn.Module):
|
| 216 |
+
def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None:
|
| 217 |
+
super().__init__()
|
| 218 |
+
if conv_block is None:
|
| 219 |
+
conv_block = BasicConv2d
|
| 220 |
+
self.branch3x3 = conv_block(in_channels, 384, kernel_size=3, stride=2)
|
| 221 |
+
|
| 222 |
+
self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1)
|
| 223 |
+
self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1)
|
| 224 |
+
self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, stride=2)
|
| 225 |
+
|
| 226 |
+
def _forward(self, x: Tensor) -> List[Tensor]:
|
| 227 |
+
branch3x3 = self.branch3x3(x)
|
| 228 |
+
|
| 229 |
+
branch3x3dbl = self.branch3x3dbl_1(x)
|
| 230 |
+
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
|
| 231 |
+
branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
|
| 232 |
+
|
| 233 |
+
branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)
|
| 234 |
+
|
| 235 |
+
outputs = [branch3x3, branch3x3dbl, branch_pool]
|
| 236 |
+
return outputs
|
| 237 |
+
|
| 238 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 239 |
+
outputs = self._forward(x)
|
| 240 |
+
return torch.cat(outputs, 1)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class InceptionC(nn.Module):
|
| 244 |
+
def __init__(
|
| 245 |
+
self, in_channels: int, channels_7x7: int, conv_block: Optional[Callable[..., nn.Module]] = None
|
| 246 |
+
) -> None:
|
| 247 |
+
super().__init__()
|
| 248 |
+
if conv_block is None:
|
| 249 |
+
conv_block = BasicConv2d
|
| 250 |
+
self.branch1x1 = conv_block(in_channels, 192, kernel_size=1)
|
| 251 |
+
|
| 252 |
+
c7 = channels_7x7
|
| 253 |
+
self.branch7x7_1 = conv_block(in_channels, c7, kernel_size=1)
|
| 254 |
+
self.branch7x7_2 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3))
|
| 255 |
+
self.branch7x7_3 = conv_block(c7, 192, kernel_size=(7, 1), padding=(3, 0))
|
| 256 |
+
|
| 257 |
+
self.branch7x7dbl_1 = conv_block(in_channels, c7, kernel_size=1)
|
| 258 |
+
self.branch7x7dbl_2 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0))
|
| 259 |
+
self.branch7x7dbl_3 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3))
|
| 260 |
+
self.branch7x7dbl_4 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0))
|
| 261 |
+
self.branch7x7dbl_5 = conv_block(c7, 192, kernel_size=(1, 7), padding=(0, 3))
|
| 262 |
+
|
| 263 |
+
self.branch_pool = conv_block(in_channels, 192, kernel_size=1)
|
| 264 |
+
|
| 265 |
+
def _forward(self, x: Tensor) -> List[Tensor]:
|
| 266 |
+
branch1x1 = self.branch1x1(x)
|
| 267 |
+
|
| 268 |
+
branch7x7 = self.branch7x7_1(x)
|
| 269 |
+
branch7x7 = self.branch7x7_2(branch7x7)
|
| 270 |
+
branch7x7 = self.branch7x7_3(branch7x7)
|
| 271 |
+
|
| 272 |
+
branch7x7dbl = self.branch7x7dbl_1(x)
|
| 273 |
+
branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
|
| 274 |
+
branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
|
| 275 |
+
branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
|
| 276 |
+
branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)
|
| 277 |
+
|
| 278 |
+
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
|
| 279 |
+
branch_pool = self.branch_pool(branch_pool)
|
| 280 |
+
|
| 281 |
+
outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
|
| 282 |
+
return outputs
|
| 283 |
+
|
| 284 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 285 |
+
outputs = self._forward(x)
|
| 286 |
+
return torch.cat(outputs, 1)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class InceptionD(nn.Module):
|
| 290 |
+
def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None:
|
| 291 |
+
super().__init__()
|
| 292 |
+
if conv_block is None:
|
| 293 |
+
conv_block = BasicConv2d
|
| 294 |
+
self.branch3x3_1 = conv_block(in_channels, 192, kernel_size=1)
|
| 295 |
+
self.branch3x3_2 = conv_block(192, 320, kernel_size=3, stride=2)
|
| 296 |
+
|
| 297 |
+
self.branch7x7x3_1 = conv_block(in_channels, 192, kernel_size=1)
|
| 298 |
+
self.branch7x7x3_2 = conv_block(192, 192, kernel_size=(1, 7), padding=(0, 3))
|
| 299 |
+
self.branch7x7x3_3 = conv_block(192, 192, kernel_size=(7, 1), padding=(3, 0))
|
| 300 |
+
self.branch7x7x3_4 = conv_block(192, 192, kernel_size=3, stride=2)
|
| 301 |
+
|
| 302 |
+
def _forward(self, x: Tensor) -> List[Tensor]:
|
| 303 |
+
branch3x3 = self.branch3x3_1(x)
|
| 304 |
+
branch3x3 = self.branch3x3_2(branch3x3)
|
| 305 |
+
|
| 306 |
+
branch7x7x3 = self.branch7x7x3_1(x)
|
| 307 |
+
branch7x7x3 = self.branch7x7x3_2(branch7x7x3)
|
| 308 |
+
branch7x7x3 = self.branch7x7x3_3(branch7x7x3)
|
| 309 |
+
branch7x7x3 = self.branch7x7x3_4(branch7x7x3)
|
| 310 |
+
|
| 311 |
+
branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)
|
| 312 |
+
outputs = [branch3x3, branch7x7x3, branch_pool]
|
| 313 |
+
return outputs
|
| 314 |
+
|
| 315 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 316 |
+
outputs = self._forward(x)
|
| 317 |
+
return torch.cat(outputs, 1)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class InceptionE(nn.Module):
|
| 321 |
+
def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None:
|
| 322 |
+
super().__init__()
|
| 323 |
+
if conv_block is None:
|
| 324 |
+
conv_block = BasicConv2d
|
| 325 |
+
self.branch1x1 = conv_block(in_channels, 320, kernel_size=1)
|
| 326 |
+
|
| 327 |
+
self.branch3x3_1 = conv_block(in_channels, 384, kernel_size=1)
|
| 328 |
+
self.branch3x3_2a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1))
|
| 329 |
+
self.branch3x3_2b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0))
|
| 330 |
+
|
| 331 |
+
self.branch3x3dbl_1 = conv_block(in_channels, 448, kernel_size=1)
|
| 332 |
+
self.branch3x3dbl_2 = conv_block(448, 384, kernel_size=3, padding=1)
|
| 333 |
+
self.branch3x3dbl_3a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1))
|
| 334 |
+
self.branch3x3dbl_3b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0))
|
| 335 |
+
|
| 336 |
+
self.branch_pool = conv_block(in_channels, 192, kernel_size=1)
|
| 337 |
+
|
| 338 |
+
def _forward(self, x: Tensor) -> List[Tensor]:
|
| 339 |
+
branch1x1 = self.branch1x1(x)
|
| 340 |
+
|
| 341 |
+
branch3x3 = self.branch3x3_1(x)
|
| 342 |
+
branch3x3 = [
|
| 343 |
+
self.branch3x3_2a(branch3x3),
|
| 344 |
+
self.branch3x3_2b(branch3x3),
|
| 345 |
+
]
|
| 346 |
+
branch3x3 = torch.cat(branch3x3, 1)
|
| 347 |
+
|
| 348 |
+
branch3x3dbl = self.branch3x3dbl_1(x)
|
| 349 |
+
branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
|
| 350 |
+
branch3x3dbl = [
|
| 351 |
+
self.branch3x3dbl_3a(branch3x3dbl),
|
| 352 |
+
self.branch3x3dbl_3b(branch3x3dbl),
|
| 353 |
+
]
|
| 354 |
+
branch3x3dbl = torch.cat(branch3x3dbl, 1)
|
| 355 |
+
|
| 356 |
+
branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
|
| 357 |
+
branch_pool = self.branch_pool(branch_pool)
|
| 358 |
+
|
| 359 |
+
outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
|
| 360 |
+
return outputs
|
| 361 |
+
|
| 362 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 363 |
+
outputs = self._forward(x)
|
| 364 |
+
return torch.cat(outputs, 1)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class InceptionAux(nn.Module):
|
| 368 |
+
def __init__(
|
| 369 |
+
self, in_channels: int, num_classes: int, conv_block: Optional[Callable[..., nn.Module]] = None
|
| 370 |
+
) -> None:
|
| 371 |
+
super().__init__()
|
| 372 |
+
if conv_block is None:
|
| 373 |
+
conv_block = BasicConv2d
|
| 374 |
+
self.conv0 = conv_block(in_channels, 128, kernel_size=1)
|
| 375 |
+
self.conv1 = conv_block(128, 768, kernel_size=5)
|
| 376 |
+
self.conv1.stddev = 0.01 # type: ignore[assignment]
|
| 377 |
+
self.fc = nn.Linear(768, num_classes)
|
| 378 |
+
self.fc.stddev = 0.001 # type: ignore[assignment]
|
| 379 |
+
|
| 380 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 381 |
+
# N x 768 x 17 x 17
|
| 382 |
+
x = F.avg_pool2d(x, kernel_size=5, stride=3)
|
| 383 |
+
# N x 768 x 5 x 5
|
| 384 |
+
x = self.conv0(x)
|
| 385 |
+
# N x 128 x 5 x 5
|
| 386 |
+
x = self.conv1(x)
|
| 387 |
+
# N x 768 x 1 x 1
|
| 388 |
+
# Adaptive average pooling
|
| 389 |
+
x = F.adaptive_avg_pool2d(x, (1, 1))
|
| 390 |
+
# N x 768 x 1 x 1
|
| 391 |
+
x = torch.flatten(x, 1)
|
| 392 |
+
# N x 768
|
| 393 |
+
x = self.fc(x)
|
| 394 |
+
# N x 1000
|
| 395 |
+
return x
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class BasicConv2d(nn.Module):
|
| 399 |
+
def __init__(self, in_channels: int, out_channels: int, **kwargs: Any) -> None:
|
| 400 |
+
super().__init__()
|
| 401 |
+
self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)
|
| 402 |
+
self.bn = nn.BatchNorm2d(out_channels, eps=0.001)
|
| 403 |
+
|
| 404 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 405 |
+
x = self.conv(x)
|
| 406 |
+
x = self.bn(x)
|
| 407 |
+
return F.relu(x, inplace=True)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class Inception_V3_Weights(WeightsEnum):
|
| 411 |
+
IMAGENET1K_V1 = Weights(
|
| 412 |
+
url="https://download.pytorch.org/models/inception_v3_google-0cc3c7bd.pth",
|
| 413 |
+
transforms=partial(ImageClassification, crop_size=299, resize_size=342),
|
| 414 |
+
meta={
|
| 415 |
+
"num_params": 27161264,
|
| 416 |
+
"min_size": (75, 75),
|
| 417 |
+
"categories": _IMAGENET_CATEGORIES,
|
| 418 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/classification#inception-v3",
|
| 419 |
+
"_metrics": {
|
| 420 |
+
"ImageNet-1K": {
|
| 421 |
+
"acc@1": 77.294,
|
| 422 |
+
"acc@5": 93.450,
|
| 423 |
+
}
|
| 424 |
+
},
|
| 425 |
+
"_ops": 5.713,
|
| 426 |
+
"_file_size": 103.903,
|
| 427 |
+
"_docs": """These weights are ported from the original paper.""",
|
| 428 |
+
},
|
| 429 |
+
)
|
| 430 |
+
DEFAULT = IMAGENET1K_V1
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
@register_model()
|
| 434 |
+
@handle_legacy_interface(weights=("pretrained", Inception_V3_Weights.IMAGENET1K_V1))
|
| 435 |
+
def inception_v3(*, weights: Optional[Inception_V3_Weights] = None, progress: bool = True, **kwargs: Any) -> Inception3:
|
| 436 |
+
"""
|
| 437 |
+
Inception v3 model architecture from
|
| 438 |
+
`Rethinking the Inception Architecture for Computer Vision <http://arxiv.org/abs/1512.00567>`_.
|
| 439 |
+
|
| 440 |
+
.. note::
|
| 441 |
+
**Important**: In contrast to the other models the inception_v3 expects tensors with a size of
|
| 442 |
+
N x 3 x 299 x 299, so ensure your images are sized accordingly.
|
| 443 |
+
|
| 444 |
+
Args:
|
| 445 |
+
weights (:class:`~torchvision.models.Inception_V3_Weights`, optional): The
|
| 446 |
+
pretrained weights for the model. See
|
| 447 |
+
:class:`~torchvision.models.Inception_V3_Weights` below for
|
| 448 |
+
more details, and possible values. By default, no pre-trained
|
| 449 |
+
weights are used.
|
| 450 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 451 |
+
download to stderr. Default is True.
|
| 452 |
+
**kwargs: parameters passed to the ``torchvision.models.Inception3``
|
| 453 |
+
base class. Please refer to the `source code
|
| 454 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/inception.py>`_
|
| 455 |
+
for more details about this class.
|
| 456 |
+
|
| 457 |
+
.. autoclass:: torchvision.models.Inception_V3_Weights
|
| 458 |
+
:members:
|
| 459 |
+
"""
|
| 460 |
+
weights = Inception_V3_Weights.verify(weights)
|
| 461 |
+
|
| 462 |
+
original_aux_logits = kwargs.get("aux_logits", True)
|
| 463 |
+
if weights is not None:
|
| 464 |
+
if "transform_input" not in kwargs:
|
| 465 |
+
_ovewrite_named_param(kwargs, "transform_input", True)
|
| 466 |
+
_ovewrite_named_param(kwargs, "aux_logits", True)
|
| 467 |
+
_ovewrite_named_param(kwargs, "init_weights", False)
|
| 468 |
+
_ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
|
| 469 |
+
|
| 470 |
+
model = Inception3(**kwargs)
|
| 471 |
+
|
| 472 |
+
if weights is not None:
|
| 473 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 474 |
+
if not original_aux_logits:
|
| 475 |
+
model.aux_logits = False
|
| 476 |
+
model.AuxLogits = None
|
| 477 |
+
|
| 478 |
+
return model
|
wemm/lib/python3.10/site-packages/torchvision/models/maxvit.py
ADDED
|
@@ -0,0 +1,832 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
from functools import partial
|
| 4 |
+
from typing import Any, Callable, List, Optional, Sequence, Tuple
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from torch import nn, Tensor
|
| 10 |
+
from torchvision.models._api import register_model, Weights, WeightsEnum
|
| 11 |
+
from torchvision.models._meta import _IMAGENET_CATEGORIES
|
| 12 |
+
from torchvision.models._utils import _ovewrite_named_param, handle_legacy_interface
|
| 13 |
+
from torchvision.ops.misc import Conv2dNormActivation, SqueezeExcitation
|
| 14 |
+
from torchvision.ops.stochastic_depth import StochasticDepth
|
| 15 |
+
from torchvision.transforms._presets import ImageClassification, InterpolationMode
|
| 16 |
+
from torchvision.utils import _log_api_usage_once
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"MaxVit",
|
| 20 |
+
"MaxVit_T_Weights",
|
| 21 |
+
"maxvit_t",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _get_conv_output_shape(input_size: Tuple[int, int], kernel_size: int, stride: int, padding: int) -> Tuple[int, int]:
|
| 26 |
+
return (
|
| 27 |
+
(input_size[0] - kernel_size + 2 * padding) // stride + 1,
|
| 28 |
+
(input_size[1] - kernel_size + 2 * padding) // stride + 1,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _make_block_input_shapes(input_size: Tuple[int, int], n_blocks: int) -> List[Tuple[int, int]]:
|
| 33 |
+
"""Util function to check that the input size is correct for a MaxVit configuration."""
|
| 34 |
+
shapes = []
|
| 35 |
+
block_input_shape = _get_conv_output_shape(input_size, 3, 2, 1)
|
| 36 |
+
for _ in range(n_blocks):
|
| 37 |
+
block_input_shape = _get_conv_output_shape(block_input_shape, 3, 2, 1)
|
| 38 |
+
shapes.append(block_input_shape)
|
| 39 |
+
return shapes
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _get_relative_position_index(height: int, width: int) -> torch.Tensor:
|
| 43 |
+
coords = torch.stack(torch.meshgrid([torch.arange(height), torch.arange(width)]))
|
| 44 |
+
coords_flat = torch.flatten(coords, 1)
|
| 45 |
+
relative_coords = coords_flat[:, :, None] - coords_flat[:, None, :]
|
| 46 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous()
|
| 47 |
+
relative_coords[:, :, 0] += height - 1
|
| 48 |
+
relative_coords[:, :, 1] += width - 1
|
| 49 |
+
relative_coords[:, :, 0] *= 2 * width - 1
|
| 50 |
+
return relative_coords.sum(-1)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class MBConv(nn.Module):
|
| 54 |
+
"""MBConv: Mobile Inverted Residual Bottleneck.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
in_channels (int): Number of input channels.
|
| 58 |
+
out_channels (int): Number of output channels.
|
| 59 |
+
expansion_ratio (float): Expansion ratio in the bottleneck.
|
| 60 |
+
squeeze_ratio (float): Squeeze ratio in the SE Layer.
|
| 61 |
+
stride (int): Stride of the depthwise convolution.
|
| 62 |
+
activation_layer (Callable[..., nn.Module]): Activation function.
|
| 63 |
+
norm_layer (Callable[..., nn.Module]): Normalization function.
|
| 64 |
+
p_stochastic_dropout (float): Probability of stochastic depth.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
in_channels: int,
|
| 70 |
+
out_channels: int,
|
| 71 |
+
expansion_ratio: float,
|
| 72 |
+
squeeze_ratio: float,
|
| 73 |
+
stride: int,
|
| 74 |
+
activation_layer: Callable[..., nn.Module],
|
| 75 |
+
norm_layer: Callable[..., nn.Module],
|
| 76 |
+
p_stochastic_dropout: float = 0.0,
|
| 77 |
+
) -> None:
|
| 78 |
+
super().__init__()
|
| 79 |
+
|
| 80 |
+
proj: Sequence[nn.Module]
|
| 81 |
+
self.proj: nn.Module
|
| 82 |
+
|
| 83 |
+
should_proj = stride != 1 or in_channels != out_channels
|
| 84 |
+
if should_proj:
|
| 85 |
+
proj = [nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, bias=True)]
|
| 86 |
+
if stride == 2:
|
| 87 |
+
proj = [nn.AvgPool2d(kernel_size=3, stride=stride, padding=1)] + proj # type: ignore
|
| 88 |
+
self.proj = nn.Sequential(*proj)
|
| 89 |
+
else:
|
| 90 |
+
self.proj = nn.Identity() # type: ignore
|
| 91 |
+
|
| 92 |
+
mid_channels = int(out_channels * expansion_ratio)
|
| 93 |
+
sqz_channels = int(out_channels * squeeze_ratio)
|
| 94 |
+
|
| 95 |
+
if p_stochastic_dropout:
|
| 96 |
+
self.stochastic_depth = StochasticDepth(p_stochastic_dropout, mode="row") # type: ignore
|
| 97 |
+
else:
|
| 98 |
+
self.stochastic_depth = nn.Identity() # type: ignore
|
| 99 |
+
|
| 100 |
+
_layers = OrderedDict()
|
| 101 |
+
_layers["pre_norm"] = norm_layer(in_channels)
|
| 102 |
+
_layers["conv_a"] = Conv2dNormActivation(
|
| 103 |
+
in_channels,
|
| 104 |
+
mid_channels,
|
| 105 |
+
kernel_size=1,
|
| 106 |
+
stride=1,
|
| 107 |
+
padding=0,
|
| 108 |
+
activation_layer=activation_layer,
|
| 109 |
+
norm_layer=norm_layer,
|
| 110 |
+
inplace=None,
|
| 111 |
+
)
|
| 112 |
+
_layers["conv_b"] = Conv2dNormActivation(
|
| 113 |
+
mid_channels,
|
| 114 |
+
mid_channels,
|
| 115 |
+
kernel_size=3,
|
| 116 |
+
stride=stride,
|
| 117 |
+
padding=1,
|
| 118 |
+
activation_layer=activation_layer,
|
| 119 |
+
norm_layer=norm_layer,
|
| 120 |
+
groups=mid_channels,
|
| 121 |
+
inplace=None,
|
| 122 |
+
)
|
| 123 |
+
_layers["squeeze_excitation"] = SqueezeExcitation(mid_channels, sqz_channels, activation=nn.SiLU)
|
| 124 |
+
_layers["conv_c"] = nn.Conv2d(in_channels=mid_channels, out_channels=out_channels, kernel_size=1, bias=True)
|
| 125 |
+
|
| 126 |
+
self.layers = nn.Sequential(_layers)
|
| 127 |
+
|
| 128 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 129 |
+
"""
|
| 130 |
+
Args:
|
| 131 |
+
x (Tensor): Input tensor with expected layout of [B, C, H, W].
|
| 132 |
+
Returns:
|
| 133 |
+
Tensor: Output tensor with expected layout of [B, C, H / stride, W / stride].
|
| 134 |
+
"""
|
| 135 |
+
res = self.proj(x)
|
| 136 |
+
x = self.stochastic_depth(self.layers(x))
|
| 137 |
+
return res + x
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class RelativePositionalMultiHeadAttention(nn.Module):
|
| 141 |
+
"""Relative Positional Multi-Head Attention.
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
feat_dim (int): Number of input features.
|
| 145 |
+
head_dim (int): Number of features per head.
|
| 146 |
+
max_seq_len (int): Maximum sequence length.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
def __init__(
|
| 150 |
+
self,
|
| 151 |
+
feat_dim: int,
|
| 152 |
+
head_dim: int,
|
| 153 |
+
max_seq_len: int,
|
| 154 |
+
) -> None:
|
| 155 |
+
super().__init__()
|
| 156 |
+
|
| 157 |
+
if feat_dim % head_dim != 0:
|
| 158 |
+
raise ValueError(f"feat_dim: {feat_dim} must be divisible by head_dim: {head_dim}")
|
| 159 |
+
|
| 160 |
+
self.n_heads = feat_dim // head_dim
|
| 161 |
+
self.head_dim = head_dim
|
| 162 |
+
self.size = int(math.sqrt(max_seq_len))
|
| 163 |
+
self.max_seq_len = max_seq_len
|
| 164 |
+
|
| 165 |
+
self.to_qkv = nn.Linear(feat_dim, self.n_heads * self.head_dim * 3)
|
| 166 |
+
self.scale_factor = feat_dim**-0.5
|
| 167 |
+
|
| 168 |
+
self.merge = nn.Linear(self.head_dim * self.n_heads, feat_dim)
|
| 169 |
+
self.relative_position_bias_table = nn.parameter.Parameter(
|
| 170 |
+
torch.empty(((2 * self.size - 1) * (2 * self.size - 1), self.n_heads), dtype=torch.float32),
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
self.register_buffer("relative_position_index", _get_relative_position_index(self.size, self.size))
|
| 174 |
+
# initialize with truncated normal the bias
|
| 175 |
+
torch.nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02)
|
| 176 |
+
|
| 177 |
+
def get_relative_positional_bias(self) -> torch.Tensor:
|
| 178 |
+
bias_index = self.relative_position_index.view(-1) # type: ignore
|
| 179 |
+
relative_bias = self.relative_position_bias_table[bias_index].view(self.max_seq_len, self.max_seq_len, -1) # type: ignore
|
| 180 |
+
relative_bias = relative_bias.permute(2, 0, 1).contiguous()
|
| 181 |
+
return relative_bias.unsqueeze(0)
|
| 182 |
+
|
| 183 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 184 |
+
"""
|
| 185 |
+
Args:
|
| 186 |
+
x (Tensor): Input tensor with expected layout of [B, G, P, D].
|
| 187 |
+
Returns:
|
| 188 |
+
Tensor: Output tensor with expected layout of [B, G, P, D].
|
| 189 |
+
"""
|
| 190 |
+
B, G, P, D = x.shape
|
| 191 |
+
H, DH = self.n_heads, self.head_dim
|
| 192 |
+
|
| 193 |
+
qkv = self.to_qkv(x)
|
| 194 |
+
q, k, v = torch.chunk(qkv, 3, dim=-1)
|
| 195 |
+
|
| 196 |
+
q = q.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4)
|
| 197 |
+
k = k.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4)
|
| 198 |
+
v = v.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4)
|
| 199 |
+
|
| 200 |
+
k = k * self.scale_factor
|
| 201 |
+
dot_prod = torch.einsum("B G H I D, B G H J D -> B G H I J", q, k)
|
| 202 |
+
pos_bias = self.get_relative_positional_bias()
|
| 203 |
+
|
| 204 |
+
dot_prod = F.softmax(dot_prod + pos_bias, dim=-1)
|
| 205 |
+
|
| 206 |
+
out = torch.einsum("B G H I J, B G H J D -> B G H I D", dot_prod, v)
|
| 207 |
+
out = out.permute(0, 1, 3, 2, 4).reshape(B, G, P, D)
|
| 208 |
+
|
| 209 |
+
out = self.merge(out)
|
| 210 |
+
return out
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class SwapAxes(nn.Module):
|
| 214 |
+
"""Permute the axes of a tensor."""
|
| 215 |
+
|
| 216 |
+
def __init__(self, a: int, b: int) -> None:
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.a = a
|
| 219 |
+
self.b = b
|
| 220 |
+
|
| 221 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 222 |
+
res = torch.swapaxes(x, self.a, self.b)
|
| 223 |
+
return res
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class WindowPartition(nn.Module):
|
| 227 |
+
"""
|
| 228 |
+
Partition the input tensor into non-overlapping windows.
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
def __init__(self) -> None:
|
| 232 |
+
super().__init__()
|
| 233 |
+
|
| 234 |
+
def forward(self, x: Tensor, p: int) -> Tensor:
|
| 235 |
+
"""
|
| 236 |
+
Args:
|
| 237 |
+
x (Tensor): Input tensor with expected layout of [B, C, H, W].
|
| 238 |
+
p (int): Number of partitions.
|
| 239 |
+
Returns:
|
| 240 |
+
Tensor: Output tensor with expected layout of [B, H/P, W/P, P*P, C].
|
| 241 |
+
"""
|
| 242 |
+
B, C, H, W = x.shape
|
| 243 |
+
P = p
|
| 244 |
+
# chunk up H and W dimensions
|
| 245 |
+
x = x.reshape(B, C, H // P, P, W // P, P)
|
| 246 |
+
x = x.permute(0, 2, 4, 3, 5, 1)
|
| 247 |
+
# colapse P * P dimension
|
| 248 |
+
x = x.reshape(B, (H // P) * (W // P), P * P, C)
|
| 249 |
+
return x
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class WindowDepartition(nn.Module):
|
| 253 |
+
"""
|
| 254 |
+
Departition the input tensor of non-overlapping windows into a feature volume of layout [B, C, H, W].
|
| 255 |
+
"""
|
| 256 |
+
|
| 257 |
+
def __init__(self) -> None:
|
| 258 |
+
super().__init__()
|
| 259 |
+
|
| 260 |
+
def forward(self, x: Tensor, p: int, h_partitions: int, w_partitions: int) -> Tensor:
|
| 261 |
+
"""
|
| 262 |
+
Args:
|
| 263 |
+
x (Tensor): Input tensor with expected layout of [B, (H/P * W/P), P*P, C].
|
| 264 |
+
p (int): Number of partitions.
|
| 265 |
+
h_partitions (int): Number of vertical partitions.
|
| 266 |
+
w_partitions (int): Number of horizontal partitions.
|
| 267 |
+
Returns:
|
| 268 |
+
Tensor: Output tensor with expected layout of [B, C, H, W].
|
| 269 |
+
"""
|
| 270 |
+
B, G, PP, C = x.shape
|
| 271 |
+
P = p
|
| 272 |
+
HP, WP = h_partitions, w_partitions
|
| 273 |
+
# split P * P dimension into 2 P tile dimensionsa
|
| 274 |
+
x = x.reshape(B, HP, WP, P, P, C)
|
| 275 |
+
# permute into B, C, HP, P, WP, P
|
| 276 |
+
x = x.permute(0, 5, 1, 3, 2, 4)
|
| 277 |
+
# reshape into B, C, H, W
|
| 278 |
+
x = x.reshape(B, C, HP * P, WP * P)
|
| 279 |
+
return x
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class PartitionAttentionLayer(nn.Module):
|
| 283 |
+
"""
|
| 284 |
+
Layer for partitioning the input tensor into non-overlapping windows and applying attention to each window.
|
| 285 |
+
|
| 286 |
+
Args:
|
| 287 |
+
in_channels (int): Number of input channels.
|
| 288 |
+
head_dim (int): Dimension of each attention head.
|
| 289 |
+
partition_size (int): Size of the partitions.
|
| 290 |
+
partition_type (str): Type of partitioning to use. Can be either "grid" or "window".
|
| 291 |
+
grid_size (Tuple[int, int]): Size of the grid to partition the input tensor into.
|
| 292 |
+
mlp_ratio (int): Ratio of the feature size expansion in the MLP layer.
|
| 293 |
+
activation_layer (Callable[..., nn.Module]): Activation function to use.
|
| 294 |
+
norm_layer (Callable[..., nn.Module]): Normalization function to use.
|
| 295 |
+
attention_dropout (float): Dropout probability for the attention layer.
|
| 296 |
+
mlp_dropout (float): Dropout probability for the MLP layer.
|
| 297 |
+
p_stochastic_dropout (float): Probability of dropping out a partition.
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
def __init__(
|
| 301 |
+
self,
|
| 302 |
+
in_channels: int,
|
| 303 |
+
head_dim: int,
|
| 304 |
+
# partitioning parameters
|
| 305 |
+
partition_size: int,
|
| 306 |
+
partition_type: str,
|
| 307 |
+
# grid size needs to be known at initialization time
|
| 308 |
+
# because we need to know hamy relative offsets there are in the grid
|
| 309 |
+
grid_size: Tuple[int, int],
|
| 310 |
+
mlp_ratio: int,
|
| 311 |
+
activation_layer: Callable[..., nn.Module],
|
| 312 |
+
norm_layer: Callable[..., nn.Module],
|
| 313 |
+
attention_dropout: float,
|
| 314 |
+
mlp_dropout: float,
|
| 315 |
+
p_stochastic_dropout: float,
|
| 316 |
+
) -> None:
|
| 317 |
+
super().__init__()
|
| 318 |
+
|
| 319 |
+
self.n_heads = in_channels // head_dim
|
| 320 |
+
self.head_dim = head_dim
|
| 321 |
+
self.n_partitions = grid_size[0] // partition_size
|
| 322 |
+
self.partition_type = partition_type
|
| 323 |
+
self.grid_size = grid_size
|
| 324 |
+
|
| 325 |
+
if partition_type not in ["grid", "window"]:
|
| 326 |
+
raise ValueError("partition_type must be either 'grid' or 'window'")
|
| 327 |
+
|
| 328 |
+
if partition_type == "window":
|
| 329 |
+
self.p, self.g = partition_size, self.n_partitions
|
| 330 |
+
else:
|
| 331 |
+
self.p, self.g = self.n_partitions, partition_size
|
| 332 |
+
|
| 333 |
+
self.partition_op = WindowPartition()
|
| 334 |
+
self.departition_op = WindowDepartition()
|
| 335 |
+
self.partition_swap = SwapAxes(-2, -3) if partition_type == "grid" else nn.Identity()
|
| 336 |
+
self.departition_swap = SwapAxes(-2, -3) if partition_type == "grid" else nn.Identity()
|
| 337 |
+
|
| 338 |
+
self.attn_layer = nn.Sequential(
|
| 339 |
+
norm_layer(in_channels),
|
| 340 |
+
# it's always going to be partition_size ** 2 because
|
| 341 |
+
# of the axis swap in the case of grid partitioning
|
| 342 |
+
RelativePositionalMultiHeadAttention(in_channels, head_dim, partition_size**2),
|
| 343 |
+
nn.Dropout(attention_dropout),
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
# pre-normalization similar to transformer layers
|
| 347 |
+
self.mlp_layer = nn.Sequential(
|
| 348 |
+
nn.LayerNorm(in_channels),
|
| 349 |
+
nn.Linear(in_channels, in_channels * mlp_ratio),
|
| 350 |
+
activation_layer(),
|
| 351 |
+
nn.Linear(in_channels * mlp_ratio, in_channels),
|
| 352 |
+
nn.Dropout(mlp_dropout),
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
# layer scale factors
|
| 356 |
+
self.stochastic_dropout = StochasticDepth(p_stochastic_dropout, mode="row")
|
| 357 |
+
|
| 358 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 359 |
+
"""
|
| 360 |
+
Args:
|
| 361 |
+
x (Tensor): Input tensor with expected layout of [B, C, H, W].
|
| 362 |
+
Returns:
|
| 363 |
+
Tensor: Output tensor with expected layout of [B, C, H, W].
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
# Undefined behavior if H or W are not divisible by p
|
| 367 |
+
# https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L766
|
| 368 |
+
gh, gw = self.grid_size[0] // self.p, self.grid_size[1] // self.p
|
| 369 |
+
torch._assert(
|
| 370 |
+
self.grid_size[0] % self.p == 0 and self.grid_size[1] % self.p == 0,
|
| 371 |
+
"Grid size must be divisible by partition size. Got grid size of {} and partition size of {}".format(
|
| 372 |
+
self.grid_size, self.p
|
| 373 |
+
),
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
x = self.partition_op(x, self.p)
|
| 377 |
+
x = self.partition_swap(x)
|
| 378 |
+
x = x + self.stochastic_dropout(self.attn_layer(x))
|
| 379 |
+
x = x + self.stochastic_dropout(self.mlp_layer(x))
|
| 380 |
+
x = self.departition_swap(x)
|
| 381 |
+
x = self.departition_op(x, self.p, gh, gw)
|
| 382 |
+
|
| 383 |
+
return x
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class MaxVitLayer(nn.Module):
|
| 387 |
+
"""
|
| 388 |
+
MaxVit layer consisting of a MBConv layer followed by a PartitionAttentionLayer with `window` and a PartitionAttentionLayer with `grid`.
|
| 389 |
+
|
| 390 |
+
Args:
|
| 391 |
+
in_channels (int): Number of input channels.
|
| 392 |
+
out_channels (int): Number of output channels.
|
| 393 |
+
expansion_ratio (float): Expansion ratio in the bottleneck.
|
| 394 |
+
squeeze_ratio (float): Squeeze ratio in the SE Layer.
|
| 395 |
+
stride (int): Stride of the depthwise convolution.
|
| 396 |
+
activation_layer (Callable[..., nn.Module]): Activation function.
|
| 397 |
+
norm_layer (Callable[..., nn.Module]): Normalization function.
|
| 398 |
+
head_dim (int): Dimension of the attention heads.
|
| 399 |
+
mlp_ratio (int): Ratio of the MLP layer.
|
| 400 |
+
mlp_dropout (float): Dropout probability for the MLP layer.
|
| 401 |
+
attention_dropout (float): Dropout probability for the attention layer.
|
| 402 |
+
p_stochastic_dropout (float): Probability of stochastic depth.
|
| 403 |
+
partition_size (int): Size of the partitions.
|
| 404 |
+
grid_size (Tuple[int, int]): Size of the input feature grid.
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
def __init__(
|
| 408 |
+
self,
|
| 409 |
+
# conv parameters
|
| 410 |
+
in_channels: int,
|
| 411 |
+
out_channels: int,
|
| 412 |
+
squeeze_ratio: float,
|
| 413 |
+
expansion_ratio: float,
|
| 414 |
+
stride: int,
|
| 415 |
+
# conv + transformer parameters
|
| 416 |
+
norm_layer: Callable[..., nn.Module],
|
| 417 |
+
activation_layer: Callable[..., nn.Module],
|
| 418 |
+
# transformer parameters
|
| 419 |
+
head_dim: int,
|
| 420 |
+
mlp_ratio: int,
|
| 421 |
+
mlp_dropout: float,
|
| 422 |
+
attention_dropout: float,
|
| 423 |
+
p_stochastic_dropout: float,
|
| 424 |
+
# partitioning parameters
|
| 425 |
+
partition_size: int,
|
| 426 |
+
grid_size: Tuple[int, int],
|
| 427 |
+
) -> None:
|
| 428 |
+
super().__init__()
|
| 429 |
+
|
| 430 |
+
layers: OrderedDict = OrderedDict()
|
| 431 |
+
|
| 432 |
+
# convolutional layer
|
| 433 |
+
layers["MBconv"] = MBConv(
|
| 434 |
+
in_channels=in_channels,
|
| 435 |
+
out_channels=out_channels,
|
| 436 |
+
expansion_ratio=expansion_ratio,
|
| 437 |
+
squeeze_ratio=squeeze_ratio,
|
| 438 |
+
stride=stride,
|
| 439 |
+
activation_layer=activation_layer,
|
| 440 |
+
norm_layer=norm_layer,
|
| 441 |
+
p_stochastic_dropout=p_stochastic_dropout,
|
| 442 |
+
)
|
| 443 |
+
# attention layers, block -> grid
|
| 444 |
+
layers["window_attention"] = PartitionAttentionLayer(
|
| 445 |
+
in_channels=out_channels,
|
| 446 |
+
head_dim=head_dim,
|
| 447 |
+
partition_size=partition_size,
|
| 448 |
+
partition_type="window",
|
| 449 |
+
grid_size=grid_size,
|
| 450 |
+
mlp_ratio=mlp_ratio,
|
| 451 |
+
activation_layer=activation_layer,
|
| 452 |
+
norm_layer=nn.LayerNorm,
|
| 453 |
+
attention_dropout=attention_dropout,
|
| 454 |
+
mlp_dropout=mlp_dropout,
|
| 455 |
+
p_stochastic_dropout=p_stochastic_dropout,
|
| 456 |
+
)
|
| 457 |
+
layers["grid_attention"] = PartitionAttentionLayer(
|
| 458 |
+
in_channels=out_channels,
|
| 459 |
+
head_dim=head_dim,
|
| 460 |
+
partition_size=partition_size,
|
| 461 |
+
partition_type="grid",
|
| 462 |
+
grid_size=grid_size,
|
| 463 |
+
mlp_ratio=mlp_ratio,
|
| 464 |
+
activation_layer=activation_layer,
|
| 465 |
+
norm_layer=nn.LayerNorm,
|
| 466 |
+
attention_dropout=attention_dropout,
|
| 467 |
+
mlp_dropout=mlp_dropout,
|
| 468 |
+
p_stochastic_dropout=p_stochastic_dropout,
|
| 469 |
+
)
|
| 470 |
+
self.layers = nn.Sequential(layers)
|
| 471 |
+
|
| 472 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 473 |
+
"""
|
| 474 |
+
Args:
|
| 475 |
+
x (Tensor): Input tensor of shape (B, C, H, W).
|
| 476 |
+
Returns:
|
| 477 |
+
Tensor: Output tensor of shape (B, C, H, W).
|
| 478 |
+
"""
|
| 479 |
+
x = self.layers(x)
|
| 480 |
+
return x
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
class MaxVitBlock(nn.Module):
|
| 484 |
+
"""
|
| 485 |
+
A MaxVit block consisting of `n_layers` MaxVit layers.
|
| 486 |
+
|
| 487 |
+
Args:
|
| 488 |
+
in_channels (int): Number of input channels.
|
| 489 |
+
out_channels (int): Number of output channels.
|
| 490 |
+
expansion_ratio (float): Expansion ratio in the bottleneck.
|
| 491 |
+
squeeze_ratio (float): Squeeze ratio in the SE Layer.
|
| 492 |
+
activation_layer (Callable[..., nn.Module]): Activation function.
|
| 493 |
+
norm_layer (Callable[..., nn.Module]): Normalization function.
|
| 494 |
+
head_dim (int): Dimension of the attention heads.
|
| 495 |
+
mlp_ratio (int): Ratio of the MLP layer.
|
| 496 |
+
mlp_dropout (float): Dropout probability for the MLP layer.
|
| 497 |
+
attention_dropout (float): Dropout probability for the attention layer.
|
| 498 |
+
p_stochastic_dropout (float): Probability of stochastic depth.
|
| 499 |
+
partition_size (int): Size of the partitions.
|
| 500 |
+
input_grid_size (Tuple[int, int]): Size of the input feature grid.
|
| 501 |
+
n_layers (int): Number of layers in the block.
|
| 502 |
+
p_stochastic (List[float]): List of probabilities for stochastic depth for each layer.
|
| 503 |
+
"""
|
| 504 |
+
|
| 505 |
+
def __init__(
|
| 506 |
+
self,
|
| 507 |
+
# conv parameters
|
| 508 |
+
in_channels: int,
|
| 509 |
+
out_channels: int,
|
| 510 |
+
squeeze_ratio: float,
|
| 511 |
+
expansion_ratio: float,
|
| 512 |
+
# conv + transformer parameters
|
| 513 |
+
norm_layer: Callable[..., nn.Module],
|
| 514 |
+
activation_layer: Callable[..., nn.Module],
|
| 515 |
+
# transformer parameters
|
| 516 |
+
head_dim: int,
|
| 517 |
+
mlp_ratio: int,
|
| 518 |
+
mlp_dropout: float,
|
| 519 |
+
attention_dropout: float,
|
| 520 |
+
# partitioning parameters
|
| 521 |
+
partition_size: int,
|
| 522 |
+
input_grid_size: Tuple[int, int],
|
| 523 |
+
# number of layers
|
| 524 |
+
n_layers: int,
|
| 525 |
+
p_stochastic: List[float],
|
| 526 |
+
) -> None:
|
| 527 |
+
super().__init__()
|
| 528 |
+
if not len(p_stochastic) == n_layers:
|
| 529 |
+
raise ValueError(f"p_stochastic must have length n_layers={n_layers}, got p_stochastic={p_stochastic}.")
|
| 530 |
+
|
| 531 |
+
self.layers = nn.ModuleList()
|
| 532 |
+
# account for the first stride of the first layer
|
| 533 |
+
self.grid_size = _get_conv_output_shape(input_grid_size, kernel_size=3, stride=2, padding=1)
|
| 534 |
+
|
| 535 |
+
for idx, p in enumerate(p_stochastic):
|
| 536 |
+
stride = 2 if idx == 0 else 1
|
| 537 |
+
self.layers += [
|
| 538 |
+
MaxVitLayer(
|
| 539 |
+
in_channels=in_channels if idx == 0 else out_channels,
|
| 540 |
+
out_channels=out_channels,
|
| 541 |
+
squeeze_ratio=squeeze_ratio,
|
| 542 |
+
expansion_ratio=expansion_ratio,
|
| 543 |
+
stride=stride,
|
| 544 |
+
norm_layer=norm_layer,
|
| 545 |
+
activation_layer=activation_layer,
|
| 546 |
+
head_dim=head_dim,
|
| 547 |
+
mlp_ratio=mlp_ratio,
|
| 548 |
+
mlp_dropout=mlp_dropout,
|
| 549 |
+
attention_dropout=attention_dropout,
|
| 550 |
+
partition_size=partition_size,
|
| 551 |
+
grid_size=self.grid_size,
|
| 552 |
+
p_stochastic_dropout=p,
|
| 553 |
+
),
|
| 554 |
+
]
|
| 555 |
+
|
| 556 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 557 |
+
"""
|
| 558 |
+
Args:
|
| 559 |
+
x (Tensor): Input tensor of shape (B, C, H, W).
|
| 560 |
+
Returns:
|
| 561 |
+
Tensor: Output tensor of shape (B, C, H, W).
|
| 562 |
+
"""
|
| 563 |
+
for layer in self.layers:
|
| 564 |
+
x = layer(x)
|
| 565 |
+
return x
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class MaxVit(nn.Module):
|
| 569 |
+
"""
|
| 570 |
+
Implements MaxVit Transformer from the `MaxViT: Multi-Axis Vision Transformer <https://arxiv.org/abs/2204.01697>`_ paper.
|
| 571 |
+
Args:
|
| 572 |
+
input_size (Tuple[int, int]): Size of the input image.
|
| 573 |
+
stem_channels (int): Number of channels in the stem.
|
| 574 |
+
partition_size (int): Size of the partitions.
|
| 575 |
+
block_channels (List[int]): Number of channels in each block.
|
| 576 |
+
block_layers (List[int]): Number of layers in each block.
|
| 577 |
+
stochastic_depth_prob (float): Probability of stochastic depth. Expands to a list of probabilities for each layer that scales linearly to the specified value.
|
| 578 |
+
squeeze_ratio (float): Squeeze ratio in the SE Layer. Default: 0.25.
|
| 579 |
+
expansion_ratio (float): Expansion ratio in the MBConv bottleneck. Default: 4.
|
| 580 |
+
norm_layer (Callable[..., nn.Module]): Normalization function. Default: None (setting to None will produce a `BatchNorm2d(eps=1e-3, momentum=0.99)`).
|
| 581 |
+
activation_layer (Callable[..., nn.Module]): Activation function Default: nn.GELU.
|
| 582 |
+
head_dim (int): Dimension of the attention heads.
|
| 583 |
+
mlp_ratio (int): Expansion ratio of the MLP layer. Default: 4.
|
| 584 |
+
mlp_dropout (float): Dropout probability for the MLP layer. Default: 0.0.
|
| 585 |
+
attention_dropout (float): Dropout probability for the attention layer. Default: 0.0.
|
| 586 |
+
num_classes (int): Number of classes. Default: 1000.
|
| 587 |
+
"""
|
| 588 |
+
|
| 589 |
+
def __init__(
|
| 590 |
+
self,
|
| 591 |
+
# input size parameters
|
| 592 |
+
input_size: Tuple[int, int],
|
| 593 |
+
# stem and task parameters
|
| 594 |
+
stem_channels: int,
|
| 595 |
+
# partitioning parameters
|
| 596 |
+
partition_size: int,
|
| 597 |
+
# block parameters
|
| 598 |
+
block_channels: List[int],
|
| 599 |
+
block_layers: List[int],
|
| 600 |
+
# attention head dimensions
|
| 601 |
+
head_dim: int,
|
| 602 |
+
stochastic_depth_prob: float,
|
| 603 |
+
# conv + transformer parameters
|
| 604 |
+
# norm_layer is applied only to the conv layers
|
| 605 |
+
# activation_layer is applied both to conv and transformer layers
|
| 606 |
+
norm_layer: Optional[Callable[..., nn.Module]] = None,
|
| 607 |
+
activation_layer: Callable[..., nn.Module] = nn.GELU,
|
| 608 |
+
# conv parameters
|
| 609 |
+
squeeze_ratio: float = 0.25,
|
| 610 |
+
expansion_ratio: float = 4,
|
| 611 |
+
# transformer parameters
|
| 612 |
+
mlp_ratio: int = 4,
|
| 613 |
+
mlp_dropout: float = 0.0,
|
| 614 |
+
attention_dropout: float = 0.0,
|
| 615 |
+
# task parameters
|
| 616 |
+
num_classes: int = 1000,
|
| 617 |
+
) -> None:
|
| 618 |
+
super().__init__()
|
| 619 |
+
_log_api_usage_once(self)
|
| 620 |
+
|
| 621 |
+
input_channels = 3
|
| 622 |
+
|
| 623 |
+
# https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L1029-L1030
|
| 624 |
+
# for the exact parameters used in batchnorm
|
| 625 |
+
if norm_layer is None:
|
| 626 |
+
norm_layer = partial(nn.BatchNorm2d, eps=1e-3, momentum=0.99)
|
| 627 |
+
|
| 628 |
+
# Make sure input size will be divisible by the partition size in all blocks
|
| 629 |
+
# Undefined behavior if H or W are not divisible by p
|
| 630 |
+
# https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L766
|
| 631 |
+
block_input_sizes = _make_block_input_shapes(input_size, len(block_channels))
|
| 632 |
+
for idx, block_input_size in enumerate(block_input_sizes):
|
| 633 |
+
if block_input_size[0] % partition_size != 0 or block_input_size[1] % partition_size != 0:
|
| 634 |
+
raise ValueError(
|
| 635 |
+
f"Input size {block_input_size} of block {idx} is not divisible by partition size {partition_size}. "
|
| 636 |
+
f"Consider changing the partition size or the input size.\n"
|
| 637 |
+
f"Current configuration yields the following block input sizes: {block_input_sizes}."
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
# stem
|
| 641 |
+
self.stem = nn.Sequential(
|
| 642 |
+
Conv2dNormActivation(
|
| 643 |
+
input_channels,
|
| 644 |
+
stem_channels,
|
| 645 |
+
3,
|
| 646 |
+
stride=2,
|
| 647 |
+
norm_layer=norm_layer,
|
| 648 |
+
activation_layer=activation_layer,
|
| 649 |
+
bias=False,
|
| 650 |
+
inplace=None,
|
| 651 |
+
),
|
| 652 |
+
Conv2dNormActivation(
|
| 653 |
+
stem_channels, stem_channels, 3, stride=1, norm_layer=None, activation_layer=None, bias=True
|
| 654 |
+
),
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
# account for stem stride
|
| 658 |
+
input_size = _get_conv_output_shape(input_size, kernel_size=3, stride=2, padding=1)
|
| 659 |
+
self.partition_size = partition_size
|
| 660 |
+
|
| 661 |
+
# blocks
|
| 662 |
+
self.blocks = nn.ModuleList()
|
| 663 |
+
in_channels = [stem_channels] + block_channels[:-1]
|
| 664 |
+
out_channels = block_channels
|
| 665 |
+
|
| 666 |
+
# precompute the stochastich depth probabilities from 0 to stochastic_depth_prob
|
| 667 |
+
# since we have N blocks with L layers, we will have N * L probabilities uniformly distributed
|
| 668 |
+
# over the range [0, stochastic_depth_prob]
|
| 669 |
+
p_stochastic = np.linspace(0, stochastic_depth_prob, sum(block_layers)).tolist()
|
| 670 |
+
|
| 671 |
+
p_idx = 0
|
| 672 |
+
for in_channel, out_channel, num_layers in zip(in_channels, out_channels, block_layers):
|
| 673 |
+
self.blocks.append(
|
| 674 |
+
MaxVitBlock(
|
| 675 |
+
in_channels=in_channel,
|
| 676 |
+
out_channels=out_channel,
|
| 677 |
+
squeeze_ratio=squeeze_ratio,
|
| 678 |
+
expansion_ratio=expansion_ratio,
|
| 679 |
+
norm_layer=norm_layer,
|
| 680 |
+
activation_layer=activation_layer,
|
| 681 |
+
head_dim=head_dim,
|
| 682 |
+
mlp_ratio=mlp_ratio,
|
| 683 |
+
mlp_dropout=mlp_dropout,
|
| 684 |
+
attention_dropout=attention_dropout,
|
| 685 |
+
partition_size=partition_size,
|
| 686 |
+
input_grid_size=input_size,
|
| 687 |
+
n_layers=num_layers,
|
| 688 |
+
p_stochastic=p_stochastic[p_idx : p_idx + num_layers],
|
| 689 |
+
),
|
| 690 |
+
)
|
| 691 |
+
input_size = self.blocks[-1].grid_size
|
| 692 |
+
p_idx += num_layers
|
| 693 |
+
|
| 694 |
+
# see https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L1137-L1158
|
| 695 |
+
# for why there is Linear -> Tanh -> Linear
|
| 696 |
+
self.classifier = nn.Sequential(
|
| 697 |
+
nn.AdaptiveAvgPool2d(1),
|
| 698 |
+
nn.Flatten(),
|
| 699 |
+
nn.LayerNorm(block_channels[-1]),
|
| 700 |
+
nn.Linear(block_channels[-1], block_channels[-1]),
|
| 701 |
+
nn.Tanh(),
|
| 702 |
+
nn.Linear(block_channels[-1], num_classes, bias=False),
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
self._init_weights()
|
| 706 |
+
|
| 707 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 708 |
+
x = self.stem(x)
|
| 709 |
+
for block in self.blocks:
|
| 710 |
+
x = block(x)
|
| 711 |
+
x = self.classifier(x)
|
| 712 |
+
return x
|
| 713 |
+
|
| 714 |
+
def _init_weights(self):
|
| 715 |
+
for m in self.modules():
|
| 716 |
+
if isinstance(m, nn.Conv2d):
|
| 717 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 718 |
+
if m.bias is not None:
|
| 719 |
+
nn.init.zeros_(m.bias)
|
| 720 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 721 |
+
nn.init.constant_(m.weight, 1)
|
| 722 |
+
nn.init.constant_(m.bias, 0)
|
| 723 |
+
elif isinstance(m, nn.Linear):
|
| 724 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 725 |
+
if m.bias is not None:
|
| 726 |
+
nn.init.zeros_(m.bias)
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _maxvit(
|
| 730 |
+
# stem parameters
|
| 731 |
+
stem_channels: int,
|
| 732 |
+
# block parameters
|
| 733 |
+
block_channels: List[int],
|
| 734 |
+
block_layers: List[int],
|
| 735 |
+
stochastic_depth_prob: float,
|
| 736 |
+
# partitioning parameters
|
| 737 |
+
partition_size: int,
|
| 738 |
+
# transformer parameters
|
| 739 |
+
head_dim: int,
|
| 740 |
+
# Weights API
|
| 741 |
+
weights: Optional[WeightsEnum] = None,
|
| 742 |
+
progress: bool = False,
|
| 743 |
+
# kwargs,
|
| 744 |
+
**kwargs: Any,
|
| 745 |
+
) -> MaxVit:
|
| 746 |
+
|
| 747 |
+
if weights is not None:
|
| 748 |
+
_ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
|
| 749 |
+
assert weights.meta["min_size"][0] == weights.meta["min_size"][1]
|
| 750 |
+
_ovewrite_named_param(kwargs, "input_size", weights.meta["min_size"])
|
| 751 |
+
|
| 752 |
+
input_size = kwargs.pop("input_size", (224, 224))
|
| 753 |
+
|
| 754 |
+
model = MaxVit(
|
| 755 |
+
stem_channels=stem_channels,
|
| 756 |
+
block_channels=block_channels,
|
| 757 |
+
block_layers=block_layers,
|
| 758 |
+
stochastic_depth_prob=stochastic_depth_prob,
|
| 759 |
+
head_dim=head_dim,
|
| 760 |
+
partition_size=partition_size,
|
| 761 |
+
input_size=input_size,
|
| 762 |
+
**kwargs,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
if weights is not None:
|
| 766 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 767 |
+
|
| 768 |
+
return model
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
class MaxVit_T_Weights(WeightsEnum):
|
| 772 |
+
IMAGENET1K_V1 = Weights(
|
| 773 |
+
# URL empty until official release
|
| 774 |
+
url="https://download.pytorch.org/models/maxvit_t-bc5ab103.pth",
|
| 775 |
+
transforms=partial(
|
| 776 |
+
ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC
|
| 777 |
+
),
|
| 778 |
+
meta={
|
| 779 |
+
"categories": _IMAGENET_CATEGORIES,
|
| 780 |
+
"num_params": 30919624,
|
| 781 |
+
"min_size": (224, 224),
|
| 782 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/classification#maxvit",
|
| 783 |
+
"_metrics": {
|
| 784 |
+
"ImageNet-1K": {
|
| 785 |
+
"acc@1": 83.700,
|
| 786 |
+
"acc@5": 96.722,
|
| 787 |
+
}
|
| 788 |
+
},
|
| 789 |
+
"_ops": 5.558,
|
| 790 |
+
"_file_size": 118.769,
|
| 791 |
+
"_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""",
|
| 792 |
+
},
|
| 793 |
+
)
|
| 794 |
+
DEFAULT = IMAGENET1K_V1
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
@register_model()
|
| 798 |
+
@handle_legacy_interface(weights=("pretrained", MaxVit_T_Weights.IMAGENET1K_V1))
|
| 799 |
+
def maxvit_t(*, weights: Optional[MaxVit_T_Weights] = None, progress: bool = True, **kwargs: Any) -> MaxVit:
|
| 800 |
+
"""
|
| 801 |
+
Constructs a maxvit_t architecture from
|
| 802 |
+
`MaxViT: Multi-Axis Vision Transformer <https://arxiv.org/abs/2204.01697>`_.
|
| 803 |
+
|
| 804 |
+
Args:
|
| 805 |
+
weights (:class:`~torchvision.models.MaxVit_T_Weights`, optional): The
|
| 806 |
+
pretrained weights to use. See
|
| 807 |
+
:class:`~torchvision.models.MaxVit_T_Weights` below for
|
| 808 |
+
more details, and possible values. By default, no pre-trained
|
| 809 |
+
weights are used.
|
| 810 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 811 |
+
download to stderr. Default is True.
|
| 812 |
+
**kwargs: parameters passed to the ``torchvision.models.maxvit.MaxVit``
|
| 813 |
+
base class. Please refer to the `source code
|
| 814 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/maxvit.py>`_
|
| 815 |
+
for more details about this class.
|
| 816 |
+
|
| 817 |
+
.. autoclass:: torchvision.models.MaxVit_T_Weights
|
| 818 |
+
:members:
|
| 819 |
+
"""
|
| 820 |
+
weights = MaxVit_T_Weights.verify(weights)
|
| 821 |
+
|
| 822 |
+
return _maxvit(
|
| 823 |
+
stem_channels=64,
|
| 824 |
+
block_channels=[64, 128, 256, 512],
|
| 825 |
+
block_layers=[2, 2, 5, 2],
|
| 826 |
+
head_dim=32,
|
| 827 |
+
stochastic_depth_prob=0.2,
|
| 828 |
+
partition_size=7,
|
| 829 |
+
weights=weights,
|
| 830 |
+
progress=progress,
|
| 831 |
+
**kwargs,
|
| 832 |
+
)
|
wemm/lib/python3.10/site-packages/torchvision/models/mnasnet.py
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from functools import partial
|
| 3 |
+
from typing import Any, Dict, List, Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
|
| 9 |
+
from ..transforms._presets import ImageClassification
|
| 10 |
+
from ..utils import _log_api_usage_once
|
| 11 |
+
from ._api import register_model, Weights, WeightsEnum
|
| 12 |
+
from ._meta import _IMAGENET_CATEGORIES
|
| 13 |
+
from ._utils import _ovewrite_named_param, handle_legacy_interface
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"MNASNet",
|
| 18 |
+
"MNASNet0_5_Weights",
|
| 19 |
+
"MNASNet0_75_Weights",
|
| 20 |
+
"MNASNet1_0_Weights",
|
| 21 |
+
"MNASNet1_3_Weights",
|
| 22 |
+
"mnasnet0_5",
|
| 23 |
+
"mnasnet0_75",
|
| 24 |
+
"mnasnet1_0",
|
| 25 |
+
"mnasnet1_3",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Paper suggests 0.9997 momentum, for TensorFlow. Equivalent PyTorch momentum is
|
| 30 |
+
# 1.0 - tensorflow.
|
| 31 |
+
_BN_MOMENTUM = 1 - 0.9997
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class _InvertedResidual(nn.Module):
|
| 35 |
+
def __init__(
|
| 36 |
+
self, in_ch: int, out_ch: int, kernel_size: int, stride: int, expansion_factor: int, bn_momentum: float = 0.1
|
| 37 |
+
) -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
if stride not in [1, 2]:
|
| 40 |
+
raise ValueError(f"stride should be 1 or 2 instead of {stride}")
|
| 41 |
+
if kernel_size not in [3, 5]:
|
| 42 |
+
raise ValueError(f"kernel_size should be 3 or 5 instead of {kernel_size}")
|
| 43 |
+
mid_ch = in_ch * expansion_factor
|
| 44 |
+
self.apply_residual = in_ch == out_ch and stride == 1
|
| 45 |
+
self.layers = nn.Sequential(
|
| 46 |
+
# Pointwise
|
| 47 |
+
nn.Conv2d(in_ch, mid_ch, 1, bias=False),
|
| 48 |
+
nn.BatchNorm2d(mid_ch, momentum=bn_momentum),
|
| 49 |
+
nn.ReLU(inplace=True),
|
| 50 |
+
# Depthwise
|
| 51 |
+
nn.Conv2d(mid_ch, mid_ch, kernel_size, padding=kernel_size // 2, stride=stride, groups=mid_ch, bias=False),
|
| 52 |
+
nn.BatchNorm2d(mid_ch, momentum=bn_momentum),
|
| 53 |
+
nn.ReLU(inplace=True),
|
| 54 |
+
# Linear pointwise. Note that there's no activation.
|
| 55 |
+
nn.Conv2d(mid_ch, out_ch, 1, bias=False),
|
| 56 |
+
nn.BatchNorm2d(out_ch, momentum=bn_momentum),
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 60 |
+
if self.apply_residual:
|
| 61 |
+
return self.layers(input) + input
|
| 62 |
+
else:
|
| 63 |
+
return self.layers(input)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _stack(
|
| 67 |
+
in_ch: int, out_ch: int, kernel_size: int, stride: int, exp_factor: int, repeats: int, bn_momentum: float
|
| 68 |
+
) -> nn.Sequential:
|
| 69 |
+
"""Creates a stack of inverted residuals."""
|
| 70 |
+
if repeats < 1:
|
| 71 |
+
raise ValueError(f"repeats should be >= 1, instead got {repeats}")
|
| 72 |
+
# First one has no skip, because feature map size changes.
|
| 73 |
+
first = _InvertedResidual(in_ch, out_ch, kernel_size, stride, exp_factor, bn_momentum=bn_momentum)
|
| 74 |
+
remaining = []
|
| 75 |
+
for _ in range(1, repeats):
|
| 76 |
+
remaining.append(_InvertedResidual(out_ch, out_ch, kernel_size, 1, exp_factor, bn_momentum=bn_momentum))
|
| 77 |
+
return nn.Sequential(first, *remaining)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float = 0.9) -> int:
|
| 81 |
+
"""Asymmetric rounding to make `val` divisible by `divisor`. With default
|
| 82 |
+
bias, will round up, unless the number is no more than 10% greater than the
|
| 83 |
+
smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88."""
|
| 84 |
+
if not 0.0 < round_up_bias < 1.0:
|
| 85 |
+
raise ValueError(f"round_up_bias should be greater than 0.0 and smaller than 1.0 instead of {round_up_bias}")
|
| 86 |
+
new_val = max(divisor, int(val + divisor / 2) // divisor * divisor)
|
| 87 |
+
return new_val if new_val >= round_up_bias * val else new_val + divisor
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _get_depths(alpha: float) -> List[int]:
|
| 91 |
+
"""Scales tensor depths as in reference MobileNet code, prefers rounding up
|
| 92 |
+
rather than down."""
|
| 93 |
+
depths = [32, 16, 24, 40, 80, 96, 192, 320]
|
| 94 |
+
return [_round_to_multiple_of(depth * alpha, 8) for depth in depths]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class MNASNet(torch.nn.Module):
|
| 98 |
+
"""MNASNet, as described in https://arxiv.org/pdf/1807.11626.pdf. This
|
| 99 |
+
implements the B1 variant of the model.
|
| 100 |
+
>>> model = MNASNet(1.0, num_classes=1000)
|
| 101 |
+
>>> x = torch.rand(1, 3, 224, 224)
|
| 102 |
+
>>> y = model(x)
|
| 103 |
+
>>> y.dim()
|
| 104 |
+
2
|
| 105 |
+
>>> y.nelement()
|
| 106 |
+
1000
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
# Version 2 adds depth scaling in the initial stages of the network.
|
| 110 |
+
_version = 2
|
| 111 |
+
|
| 112 |
+
def __init__(self, alpha: float, num_classes: int = 1000, dropout: float = 0.2) -> None:
|
| 113 |
+
super().__init__()
|
| 114 |
+
_log_api_usage_once(self)
|
| 115 |
+
if alpha <= 0.0:
|
| 116 |
+
raise ValueError(f"alpha should be greater than 0.0 instead of {alpha}")
|
| 117 |
+
self.alpha = alpha
|
| 118 |
+
self.num_classes = num_classes
|
| 119 |
+
depths = _get_depths(alpha)
|
| 120 |
+
layers = [
|
| 121 |
+
# First layer: regular conv.
|
| 122 |
+
nn.Conv2d(3, depths[0], 3, padding=1, stride=2, bias=False),
|
| 123 |
+
nn.BatchNorm2d(depths[0], momentum=_BN_MOMENTUM),
|
| 124 |
+
nn.ReLU(inplace=True),
|
| 125 |
+
# Depthwise separable, no skip.
|
| 126 |
+
nn.Conv2d(depths[0], depths[0], 3, padding=1, stride=1, groups=depths[0], bias=False),
|
| 127 |
+
nn.BatchNorm2d(depths[0], momentum=_BN_MOMENTUM),
|
| 128 |
+
nn.ReLU(inplace=True),
|
| 129 |
+
nn.Conv2d(depths[0], depths[1], 1, padding=0, stride=1, bias=False),
|
| 130 |
+
nn.BatchNorm2d(depths[1], momentum=_BN_MOMENTUM),
|
| 131 |
+
# MNASNet blocks: stacks of inverted residuals.
|
| 132 |
+
_stack(depths[1], depths[2], 3, 2, 3, 3, _BN_MOMENTUM),
|
| 133 |
+
_stack(depths[2], depths[3], 5, 2, 3, 3, _BN_MOMENTUM),
|
| 134 |
+
_stack(depths[3], depths[4], 5, 2, 6, 3, _BN_MOMENTUM),
|
| 135 |
+
_stack(depths[4], depths[5], 3, 1, 6, 2, _BN_MOMENTUM),
|
| 136 |
+
_stack(depths[5], depths[6], 5, 2, 6, 4, _BN_MOMENTUM),
|
| 137 |
+
_stack(depths[6], depths[7], 3, 1, 6, 1, _BN_MOMENTUM),
|
| 138 |
+
# Final mapping to classifier input.
|
| 139 |
+
nn.Conv2d(depths[7], 1280, 1, padding=0, stride=1, bias=False),
|
| 140 |
+
nn.BatchNorm2d(1280, momentum=_BN_MOMENTUM),
|
| 141 |
+
nn.ReLU(inplace=True),
|
| 142 |
+
]
|
| 143 |
+
self.layers = nn.Sequential(*layers)
|
| 144 |
+
self.classifier = nn.Sequential(nn.Dropout(p=dropout, inplace=True), nn.Linear(1280, num_classes))
|
| 145 |
+
|
| 146 |
+
for m in self.modules():
|
| 147 |
+
if isinstance(m, nn.Conv2d):
|
| 148 |
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
| 149 |
+
if m.bias is not None:
|
| 150 |
+
nn.init.zeros_(m.bias)
|
| 151 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 152 |
+
nn.init.ones_(m.weight)
|
| 153 |
+
nn.init.zeros_(m.bias)
|
| 154 |
+
elif isinstance(m, nn.Linear):
|
| 155 |
+
nn.init.kaiming_uniform_(m.weight, mode="fan_out", nonlinearity="sigmoid")
|
| 156 |
+
nn.init.zeros_(m.bias)
|
| 157 |
+
|
| 158 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 159 |
+
x = self.layers(x)
|
| 160 |
+
# Equivalent to global avgpool and removing H and W dimensions.
|
| 161 |
+
x = x.mean([2, 3])
|
| 162 |
+
return self.classifier(x)
|
| 163 |
+
|
| 164 |
+
def _load_from_state_dict(
|
| 165 |
+
self,
|
| 166 |
+
state_dict: Dict,
|
| 167 |
+
prefix: str,
|
| 168 |
+
local_metadata: Dict,
|
| 169 |
+
strict: bool,
|
| 170 |
+
missing_keys: List[str],
|
| 171 |
+
unexpected_keys: List[str],
|
| 172 |
+
error_msgs: List[str],
|
| 173 |
+
) -> None:
|
| 174 |
+
version = local_metadata.get("version", None)
|
| 175 |
+
if version not in [1, 2]:
|
| 176 |
+
raise ValueError(f"version shluld be set to 1 or 2 instead of {version}")
|
| 177 |
+
|
| 178 |
+
if version == 1 and not self.alpha == 1.0:
|
| 179 |
+
# In the initial version of the model (v1), stem was fixed-size.
|
| 180 |
+
# All other layer configurations were the same. This will patch
|
| 181 |
+
# the model so that it's identical to v1. Model with alpha 1.0 is
|
| 182 |
+
# unaffected.
|
| 183 |
+
depths = _get_depths(self.alpha)
|
| 184 |
+
v1_stem = [
|
| 185 |
+
nn.Conv2d(3, 32, 3, padding=1, stride=2, bias=False),
|
| 186 |
+
nn.BatchNorm2d(32, momentum=_BN_MOMENTUM),
|
| 187 |
+
nn.ReLU(inplace=True),
|
| 188 |
+
nn.Conv2d(32, 32, 3, padding=1, stride=1, groups=32, bias=False),
|
| 189 |
+
nn.BatchNorm2d(32, momentum=_BN_MOMENTUM),
|
| 190 |
+
nn.ReLU(inplace=True),
|
| 191 |
+
nn.Conv2d(32, 16, 1, padding=0, stride=1, bias=False),
|
| 192 |
+
nn.BatchNorm2d(16, momentum=_BN_MOMENTUM),
|
| 193 |
+
_stack(16, depths[2], 3, 2, 3, 3, _BN_MOMENTUM),
|
| 194 |
+
]
|
| 195 |
+
for idx, layer in enumerate(v1_stem):
|
| 196 |
+
self.layers[idx] = layer
|
| 197 |
+
|
| 198 |
+
# The model is now identical to v1, and must be saved as such.
|
| 199 |
+
self._version = 1
|
| 200 |
+
warnings.warn(
|
| 201 |
+
"A new version of MNASNet model has been implemented. "
|
| 202 |
+
"Your checkpoint was saved using the previous version. "
|
| 203 |
+
"This checkpoint will load and work as before, but "
|
| 204 |
+
"you may want to upgrade by training a newer model or "
|
| 205 |
+
"transfer learning from an updated ImageNet checkpoint.",
|
| 206 |
+
UserWarning,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
super()._load_from_state_dict(
|
| 210 |
+
state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
_COMMON_META = {
|
| 215 |
+
"min_size": (1, 1),
|
| 216 |
+
"categories": _IMAGENET_CATEGORIES,
|
| 217 |
+
"recipe": "https://github.com/1e100/mnasnet_trainer",
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class MNASNet0_5_Weights(WeightsEnum):
|
| 222 |
+
IMAGENET1K_V1 = Weights(
|
| 223 |
+
url="https://download.pytorch.org/models/mnasnet0.5_top1_67.823-3ffadce67e.pth",
|
| 224 |
+
transforms=partial(ImageClassification, crop_size=224),
|
| 225 |
+
meta={
|
| 226 |
+
**_COMMON_META,
|
| 227 |
+
"num_params": 2218512,
|
| 228 |
+
"_metrics": {
|
| 229 |
+
"ImageNet-1K": {
|
| 230 |
+
"acc@1": 67.734,
|
| 231 |
+
"acc@5": 87.490,
|
| 232 |
+
}
|
| 233 |
+
},
|
| 234 |
+
"_ops": 0.104,
|
| 235 |
+
"_file_size": 8.591,
|
| 236 |
+
"_docs": """These weights reproduce closely the results of the paper.""",
|
| 237 |
+
},
|
| 238 |
+
)
|
| 239 |
+
DEFAULT = IMAGENET1K_V1
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class MNASNet0_75_Weights(WeightsEnum):
|
| 243 |
+
IMAGENET1K_V1 = Weights(
|
| 244 |
+
url="https://download.pytorch.org/models/mnasnet0_75-7090bc5f.pth",
|
| 245 |
+
transforms=partial(ImageClassification, crop_size=224, resize_size=232),
|
| 246 |
+
meta={
|
| 247 |
+
**_COMMON_META,
|
| 248 |
+
"recipe": "https://github.com/pytorch/vision/pull/6019",
|
| 249 |
+
"num_params": 3170208,
|
| 250 |
+
"_metrics": {
|
| 251 |
+
"ImageNet-1K": {
|
| 252 |
+
"acc@1": 71.180,
|
| 253 |
+
"acc@5": 90.496,
|
| 254 |
+
}
|
| 255 |
+
},
|
| 256 |
+
"_ops": 0.215,
|
| 257 |
+
"_file_size": 12.303,
|
| 258 |
+
"_docs": """
|
| 259 |
+
These weights were trained from scratch by using TorchVision's `new training recipe
|
| 260 |
+
<https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
|
| 261 |
+
""",
|
| 262 |
+
},
|
| 263 |
+
)
|
| 264 |
+
DEFAULT = IMAGENET1K_V1
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class MNASNet1_0_Weights(WeightsEnum):
|
| 268 |
+
IMAGENET1K_V1 = Weights(
|
| 269 |
+
url="https://download.pytorch.org/models/mnasnet1.0_top1_73.512-f206786ef8.pth",
|
| 270 |
+
transforms=partial(ImageClassification, crop_size=224),
|
| 271 |
+
meta={
|
| 272 |
+
**_COMMON_META,
|
| 273 |
+
"num_params": 4383312,
|
| 274 |
+
"_metrics": {
|
| 275 |
+
"ImageNet-1K": {
|
| 276 |
+
"acc@1": 73.456,
|
| 277 |
+
"acc@5": 91.510,
|
| 278 |
+
}
|
| 279 |
+
},
|
| 280 |
+
"_ops": 0.314,
|
| 281 |
+
"_file_size": 16.915,
|
| 282 |
+
"_docs": """These weights reproduce closely the results of the paper.""",
|
| 283 |
+
},
|
| 284 |
+
)
|
| 285 |
+
DEFAULT = IMAGENET1K_V1
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class MNASNet1_3_Weights(WeightsEnum):
|
| 289 |
+
IMAGENET1K_V1 = Weights(
|
| 290 |
+
url="https://download.pytorch.org/models/mnasnet1_3-a4c69d6f.pth",
|
| 291 |
+
transforms=partial(ImageClassification, crop_size=224, resize_size=232),
|
| 292 |
+
meta={
|
| 293 |
+
**_COMMON_META,
|
| 294 |
+
"recipe": "https://github.com/pytorch/vision/pull/6019",
|
| 295 |
+
"num_params": 6282256,
|
| 296 |
+
"_metrics": {
|
| 297 |
+
"ImageNet-1K": {
|
| 298 |
+
"acc@1": 76.506,
|
| 299 |
+
"acc@5": 93.522,
|
| 300 |
+
}
|
| 301 |
+
},
|
| 302 |
+
"_ops": 0.526,
|
| 303 |
+
"_file_size": 24.246,
|
| 304 |
+
"_docs": """
|
| 305 |
+
These weights were trained from scratch by using TorchVision's `new training recipe
|
| 306 |
+
<https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
|
| 307 |
+
""",
|
| 308 |
+
},
|
| 309 |
+
)
|
| 310 |
+
DEFAULT = IMAGENET1K_V1
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _mnasnet(alpha: float, weights: Optional[WeightsEnum], progress: bool, **kwargs: Any) -> MNASNet:
|
| 314 |
+
if weights is not None:
|
| 315 |
+
_ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
|
| 316 |
+
|
| 317 |
+
model = MNASNet(alpha, **kwargs)
|
| 318 |
+
|
| 319 |
+
if weights:
|
| 320 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 321 |
+
|
| 322 |
+
return model
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@register_model()
|
| 326 |
+
@handle_legacy_interface(weights=("pretrained", MNASNet0_5_Weights.IMAGENET1K_V1))
|
| 327 |
+
def mnasnet0_5(*, weights: Optional[MNASNet0_5_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet:
|
| 328 |
+
"""MNASNet with depth multiplier of 0.5 from
|
| 329 |
+
`MnasNet: Platform-Aware Neural Architecture Search for Mobile
|
| 330 |
+
<https://arxiv.org/pdf/1807.11626.pdf>`_ paper.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
weights (:class:`~torchvision.models.MNASNet0_5_Weights`, optional): The
|
| 334 |
+
pretrained weights to use. See
|
| 335 |
+
:class:`~torchvision.models.MNASNet0_5_Weights` below for
|
| 336 |
+
more details, and possible values. By default, no pre-trained
|
| 337 |
+
weights are used.
|
| 338 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 339 |
+
download to stderr. Default is True.
|
| 340 |
+
**kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet``
|
| 341 |
+
base class. Please refer to the `source code
|
| 342 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/mnasnet.py>`_
|
| 343 |
+
for more details about this class.
|
| 344 |
+
|
| 345 |
+
.. autoclass:: torchvision.models.MNASNet0_5_Weights
|
| 346 |
+
:members:
|
| 347 |
+
"""
|
| 348 |
+
weights = MNASNet0_5_Weights.verify(weights)
|
| 349 |
+
|
| 350 |
+
return _mnasnet(0.5, weights, progress, **kwargs)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
@register_model()
|
| 354 |
+
@handle_legacy_interface(weights=("pretrained", MNASNet0_75_Weights.IMAGENET1K_V1))
|
| 355 |
+
def mnasnet0_75(*, weights: Optional[MNASNet0_75_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet:
|
| 356 |
+
"""MNASNet with depth multiplier of 0.75 from
|
| 357 |
+
`MnasNet: Platform-Aware Neural Architecture Search for Mobile
|
| 358 |
+
<https://arxiv.org/pdf/1807.11626.pdf>`_ paper.
|
| 359 |
+
|
| 360 |
+
Args:
|
| 361 |
+
weights (:class:`~torchvision.models.MNASNet0_75_Weights`, optional): The
|
| 362 |
+
pretrained weights to use. See
|
| 363 |
+
:class:`~torchvision.models.MNASNet0_75_Weights` below for
|
| 364 |
+
more details, and possible values. By default, no pre-trained
|
| 365 |
+
weights are used.
|
| 366 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 367 |
+
download to stderr. Default is True.
|
| 368 |
+
**kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet``
|
| 369 |
+
base class. Please refer to the `source code
|
| 370 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/mnasnet.py>`_
|
| 371 |
+
for more details about this class.
|
| 372 |
+
|
| 373 |
+
.. autoclass:: torchvision.models.MNASNet0_75_Weights
|
| 374 |
+
:members:
|
| 375 |
+
"""
|
| 376 |
+
weights = MNASNet0_75_Weights.verify(weights)
|
| 377 |
+
|
| 378 |
+
return _mnasnet(0.75, weights, progress, **kwargs)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@register_model()
|
| 382 |
+
@handle_legacy_interface(weights=("pretrained", MNASNet1_0_Weights.IMAGENET1K_V1))
|
| 383 |
+
def mnasnet1_0(*, weights: Optional[MNASNet1_0_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet:
|
| 384 |
+
"""MNASNet with depth multiplier of 1.0 from
|
| 385 |
+
`MnasNet: Platform-Aware Neural Architecture Search for Mobile
|
| 386 |
+
<https://arxiv.org/pdf/1807.11626.pdf>`_ paper.
|
| 387 |
+
|
| 388 |
+
Args:
|
| 389 |
+
weights (:class:`~torchvision.models.MNASNet1_0_Weights`, optional): The
|
| 390 |
+
pretrained weights to use. See
|
| 391 |
+
:class:`~torchvision.models.MNASNet1_0_Weights` below for
|
| 392 |
+
more details, and possible values. By default, no pre-trained
|
| 393 |
+
weights are used.
|
| 394 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 395 |
+
download to stderr. Default is True.
|
| 396 |
+
**kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet``
|
| 397 |
+
base class. Please refer to the `source code
|
| 398 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/mnasnet.py>`_
|
| 399 |
+
for more details about this class.
|
| 400 |
+
|
| 401 |
+
.. autoclass:: torchvision.models.MNASNet1_0_Weights
|
| 402 |
+
:members:
|
| 403 |
+
"""
|
| 404 |
+
weights = MNASNet1_0_Weights.verify(weights)
|
| 405 |
+
|
| 406 |
+
return _mnasnet(1.0, weights, progress, **kwargs)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@register_model()
|
| 410 |
+
@handle_legacy_interface(weights=("pretrained", MNASNet1_3_Weights.IMAGENET1K_V1))
|
| 411 |
+
def mnasnet1_3(*, weights: Optional[MNASNet1_3_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet:
|
| 412 |
+
"""MNASNet with depth multiplier of 1.3 from
|
| 413 |
+
`MnasNet: Platform-Aware Neural Architecture Search for Mobile
|
| 414 |
+
<https://arxiv.org/pdf/1807.11626.pdf>`_ paper.
|
| 415 |
+
|
| 416 |
+
Args:
|
| 417 |
+
weights (:class:`~torchvision.models.MNASNet1_3_Weights`, optional): The
|
| 418 |
+
pretrained weights to use. See
|
| 419 |
+
:class:`~torchvision.models.MNASNet1_3_Weights` below for
|
| 420 |
+
more details, and possible values. By default, no pre-trained
|
| 421 |
+
weights are used.
|
| 422 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 423 |
+
download to stderr. Default is True.
|
| 424 |
+
**kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet``
|
| 425 |
+
base class. Please refer to the `source code
|
| 426 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/mnasnet.py>`_
|
| 427 |
+
for more details about this class.
|
| 428 |
+
|
| 429 |
+
.. autoclass:: torchvision.models.MNASNet1_3_Weights
|
| 430 |
+
:members:
|
| 431 |
+
"""
|
| 432 |
+
weights = MNASNet1_3_Weights.verify(weights)
|
| 433 |
+
|
| 434 |
+
return _mnasnet(1.3, weights, progress, **kwargs)
|
wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .raft import *
|
wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (202 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__pycache__/_utils.cpython-310.pyc
ADDED
|
Binary file (2.16 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/__pycache__/raft.cpython-310.pyc
ADDED
|
Binary file (27.8 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/_utils.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def grid_sample(img: Tensor, absolute_grid: Tensor, mode: str = "bilinear", align_corners: Optional[bool] = None):
|
| 9 |
+
"""Same as torch's grid_sample, with absolute pixel coordinates instead of normalized coordinates."""
|
| 10 |
+
h, w = img.shape[-2:]
|
| 11 |
+
|
| 12 |
+
xgrid, ygrid = absolute_grid.split([1, 1], dim=-1)
|
| 13 |
+
xgrid = 2 * xgrid / (w - 1) - 1
|
| 14 |
+
# Adding condition if h > 1 to enable this function be reused in raft-stereo
|
| 15 |
+
if h > 1:
|
| 16 |
+
ygrid = 2 * ygrid / (h - 1) - 1
|
| 17 |
+
normalized_grid = torch.cat([xgrid, ygrid], dim=-1)
|
| 18 |
+
|
| 19 |
+
return F.grid_sample(img, normalized_grid, mode=mode, align_corners=align_corners)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def make_coords_grid(batch_size: int, h: int, w: int, device: str = "cpu"):
|
| 23 |
+
device = torch.device(device)
|
| 24 |
+
coords = torch.meshgrid(torch.arange(h, device=device), torch.arange(w, device=device), indexing="ij")
|
| 25 |
+
coords = torch.stack(coords[::-1], dim=0).float()
|
| 26 |
+
return coords[None].repeat(batch_size, 1, 1, 1)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def upsample_flow(flow, up_mask: Optional[Tensor] = None, factor: int = 8):
|
| 30 |
+
"""Upsample flow by the input factor (default 8).
|
| 31 |
+
|
| 32 |
+
If up_mask is None we just interpolate.
|
| 33 |
+
If up_mask is specified, we upsample using a convex combination of its weights. See paper page 8 and appendix B.
|
| 34 |
+
Note that in appendix B the picture assumes a downsample factor of 4 instead of 8.
|
| 35 |
+
"""
|
| 36 |
+
batch_size, num_channels, h, w = flow.shape
|
| 37 |
+
new_h, new_w = h * factor, w * factor
|
| 38 |
+
|
| 39 |
+
if up_mask is None:
|
| 40 |
+
return factor * F.interpolate(flow, size=(new_h, new_w), mode="bilinear", align_corners=True)
|
| 41 |
+
|
| 42 |
+
up_mask = up_mask.view(batch_size, 1, 9, factor, factor, h, w)
|
| 43 |
+
up_mask = torch.softmax(up_mask, dim=2) # "convex" == weights sum to 1
|
| 44 |
+
|
| 45 |
+
upsampled_flow = F.unfold(factor * flow, kernel_size=3, padding=1).view(batch_size, num_channels, 9, 1, 1, h, w)
|
| 46 |
+
upsampled_flow = torch.sum(up_mask * upsampled_flow, dim=2)
|
| 47 |
+
|
| 48 |
+
return upsampled_flow.permute(0, 1, 4, 2, 5, 3).reshape(batch_size, num_channels, new_h, new_w)
|
wemm/lib/python3.10/site-packages/torchvision/models/optical_flow/raft.py
ADDED
|
@@ -0,0 +1,934 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.nn.modules.batchnorm import BatchNorm2d
|
| 8 |
+
from torch.nn.modules.instancenorm import InstanceNorm2d
|
| 9 |
+
from torchvision.ops import Conv2dNormActivation
|
| 10 |
+
|
| 11 |
+
from ...transforms._presets import OpticalFlow
|
| 12 |
+
from ...utils import _log_api_usage_once
|
| 13 |
+
from .._api import register_model, Weights, WeightsEnum
|
| 14 |
+
from .._utils import handle_legacy_interface
|
| 15 |
+
from ._utils import grid_sample, make_coords_grid, upsample_flow
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = (
|
| 19 |
+
"RAFT",
|
| 20 |
+
"raft_large",
|
| 21 |
+
"raft_small",
|
| 22 |
+
"Raft_Large_Weights",
|
| 23 |
+
"Raft_Small_Weights",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ResidualBlock(nn.Module):
|
| 28 |
+
"""Slightly modified Residual block with extra relu and biases."""
|
| 29 |
+
|
| 30 |
+
def __init__(self, in_channels, out_channels, *, norm_layer, stride=1, always_project: bool = False):
|
| 31 |
+
super().__init__()
|
| 32 |
+
|
| 33 |
+
# Note regarding bias=True:
|
| 34 |
+
# Usually we can pass bias=False in conv layers followed by a norm layer.
|
| 35 |
+
# But in the RAFT training reference, the BatchNorm2d layers are only activated for the first dataset,
|
| 36 |
+
# and frozen for the rest of the training process (i.e. set as eval()). The bias term is thus still useful
|
| 37 |
+
# for the rest of the datasets. Technically, we could remove the bias for other norm layers like Instance norm
|
| 38 |
+
# because these aren't frozen, but we don't bother (also, we wouldn't be able to load the original weights).
|
| 39 |
+
self.convnormrelu1 = Conv2dNormActivation(
|
| 40 |
+
in_channels, out_channels, norm_layer=norm_layer, kernel_size=3, stride=stride, bias=True
|
| 41 |
+
)
|
| 42 |
+
self.convnormrelu2 = Conv2dNormActivation(
|
| 43 |
+
out_channels, out_channels, norm_layer=norm_layer, kernel_size=3, bias=True
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# make mypy happy
|
| 47 |
+
self.downsample: nn.Module
|
| 48 |
+
|
| 49 |
+
if stride == 1 and not always_project:
|
| 50 |
+
self.downsample = nn.Identity()
|
| 51 |
+
else:
|
| 52 |
+
self.downsample = Conv2dNormActivation(
|
| 53 |
+
in_channels,
|
| 54 |
+
out_channels,
|
| 55 |
+
norm_layer=norm_layer,
|
| 56 |
+
kernel_size=1,
|
| 57 |
+
stride=stride,
|
| 58 |
+
bias=True,
|
| 59 |
+
activation_layer=None,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
self.relu = nn.ReLU(inplace=True)
|
| 63 |
+
|
| 64 |
+
def forward(self, x):
|
| 65 |
+
y = x
|
| 66 |
+
y = self.convnormrelu1(y)
|
| 67 |
+
y = self.convnormrelu2(y)
|
| 68 |
+
|
| 69 |
+
x = self.downsample(x)
|
| 70 |
+
|
| 71 |
+
return self.relu(x + y)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class BottleneckBlock(nn.Module):
|
| 75 |
+
"""Slightly modified BottleNeck block (extra relu and biases)"""
|
| 76 |
+
|
| 77 |
+
def __init__(self, in_channels, out_channels, *, norm_layer, stride=1):
|
| 78 |
+
super().__init__()
|
| 79 |
+
|
| 80 |
+
# See note in ResidualBlock for the reason behind bias=True
|
| 81 |
+
self.convnormrelu1 = Conv2dNormActivation(
|
| 82 |
+
in_channels, out_channels // 4, norm_layer=norm_layer, kernel_size=1, bias=True
|
| 83 |
+
)
|
| 84 |
+
self.convnormrelu2 = Conv2dNormActivation(
|
| 85 |
+
out_channels // 4, out_channels // 4, norm_layer=norm_layer, kernel_size=3, stride=stride, bias=True
|
| 86 |
+
)
|
| 87 |
+
self.convnormrelu3 = Conv2dNormActivation(
|
| 88 |
+
out_channels // 4, out_channels, norm_layer=norm_layer, kernel_size=1, bias=True
|
| 89 |
+
)
|
| 90 |
+
self.relu = nn.ReLU(inplace=True)
|
| 91 |
+
|
| 92 |
+
if stride == 1:
|
| 93 |
+
self.downsample = nn.Identity()
|
| 94 |
+
else:
|
| 95 |
+
self.downsample = Conv2dNormActivation(
|
| 96 |
+
in_channels,
|
| 97 |
+
out_channels,
|
| 98 |
+
norm_layer=norm_layer,
|
| 99 |
+
kernel_size=1,
|
| 100 |
+
stride=stride,
|
| 101 |
+
bias=True,
|
| 102 |
+
activation_layer=None,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
def forward(self, x):
|
| 106 |
+
y = x
|
| 107 |
+
y = self.convnormrelu1(y)
|
| 108 |
+
y = self.convnormrelu2(y)
|
| 109 |
+
y = self.convnormrelu3(y)
|
| 110 |
+
|
| 111 |
+
x = self.downsample(x)
|
| 112 |
+
|
| 113 |
+
return self.relu(x + y)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class FeatureEncoder(nn.Module):
|
| 117 |
+
"""The feature encoder, used both as the actual feature encoder, and as the context encoder.
|
| 118 |
+
|
| 119 |
+
It must downsample its input by 8.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
def __init__(
|
| 123 |
+
self, *, block=ResidualBlock, layers=(64, 64, 96, 128, 256), strides=(2, 1, 2, 2), norm_layer=nn.BatchNorm2d
|
| 124 |
+
):
|
| 125 |
+
super().__init__()
|
| 126 |
+
|
| 127 |
+
if len(layers) != 5:
|
| 128 |
+
raise ValueError(f"The expected number of layers is 5, instead got {len(layers)}")
|
| 129 |
+
|
| 130 |
+
# See note in ResidualBlock for the reason behind bias=True
|
| 131 |
+
self.convnormrelu = Conv2dNormActivation(
|
| 132 |
+
3, layers[0], norm_layer=norm_layer, kernel_size=7, stride=strides[0], bias=True
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
self.layer1 = self._make_2_blocks(block, layers[0], layers[1], norm_layer=norm_layer, first_stride=strides[1])
|
| 136 |
+
self.layer2 = self._make_2_blocks(block, layers[1], layers[2], norm_layer=norm_layer, first_stride=strides[2])
|
| 137 |
+
self.layer3 = self._make_2_blocks(block, layers[2], layers[3], norm_layer=norm_layer, first_stride=strides[3])
|
| 138 |
+
|
| 139 |
+
self.conv = nn.Conv2d(layers[3], layers[4], kernel_size=1)
|
| 140 |
+
|
| 141 |
+
for m in self.modules():
|
| 142 |
+
if isinstance(m, nn.Conv2d):
|
| 143 |
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
| 144 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d)):
|
| 145 |
+
if m.weight is not None:
|
| 146 |
+
nn.init.constant_(m.weight, 1)
|
| 147 |
+
if m.bias is not None:
|
| 148 |
+
nn.init.constant_(m.bias, 0)
|
| 149 |
+
|
| 150 |
+
num_downsamples = len(list(filter(lambda s: s == 2, strides)))
|
| 151 |
+
self.output_dim = layers[-1]
|
| 152 |
+
self.downsample_factor = 2**num_downsamples
|
| 153 |
+
|
| 154 |
+
def _make_2_blocks(self, block, in_channels, out_channels, norm_layer, first_stride):
|
| 155 |
+
block1 = block(in_channels, out_channels, norm_layer=norm_layer, stride=first_stride)
|
| 156 |
+
block2 = block(out_channels, out_channels, norm_layer=norm_layer, stride=1)
|
| 157 |
+
return nn.Sequential(block1, block2)
|
| 158 |
+
|
| 159 |
+
def forward(self, x):
|
| 160 |
+
x = self.convnormrelu(x)
|
| 161 |
+
|
| 162 |
+
x = self.layer1(x)
|
| 163 |
+
x = self.layer2(x)
|
| 164 |
+
x = self.layer3(x)
|
| 165 |
+
|
| 166 |
+
x = self.conv(x)
|
| 167 |
+
|
| 168 |
+
return x
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class MotionEncoder(nn.Module):
|
| 172 |
+
"""The motion encoder, part of the update block.
|
| 173 |
+
|
| 174 |
+
Takes the current predicted flow and the correlation features as input and returns an encoded version of these.
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
def __init__(self, *, in_channels_corr, corr_layers=(256, 192), flow_layers=(128, 64), out_channels=128):
|
| 178 |
+
super().__init__()
|
| 179 |
+
|
| 180 |
+
if len(flow_layers) != 2:
|
| 181 |
+
raise ValueError(f"The expected number of flow_layers is 2, instead got {len(flow_layers)}")
|
| 182 |
+
if len(corr_layers) not in (1, 2):
|
| 183 |
+
raise ValueError(f"The number of corr_layers should be 1 or 2, instead got {len(corr_layers)}")
|
| 184 |
+
|
| 185 |
+
self.convcorr1 = Conv2dNormActivation(in_channels_corr, corr_layers[0], norm_layer=None, kernel_size=1)
|
| 186 |
+
if len(corr_layers) == 2:
|
| 187 |
+
self.convcorr2 = Conv2dNormActivation(corr_layers[0], corr_layers[1], norm_layer=None, kernel_size=3)
|
| 188 |
+
else:
|
| 189 |
+
self.convcorr2 = nn.Identity()
|
| 190 |
+
|
| 191 |
+
self.convflow1 = Conv2dNormActivation(2, flow_layers[0], norm_layer=None, kernel_size=7)
|
| 192 |
+
self.convflow2 = Conv2dNormActivation(flow_layers[0], flow_layers[1], norm_layer=None, kernel_size=3)
|
| 193 |
+
|
| 194 |
+
# out_channels - 2 because we cat the flow (2 channels) at the end
|
| 195 |
+
self.conv = Conv2dNormActivation(
|
| 196 |
+
corr_layers[-1] + flow_layers[-1], out_channels - 2, norm_layer=None, kernel_size=3
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
self.out_channels = out_channels
|
| 200 |
+
|
| 201 |
+
def forward(self, flow, corr_features):
|
| 202 |
+
corr = self.convcorr1(corr_features)
|
| 203 |
+
corr = self.convcorr2(corr)
|
| 204 |
+
|
| 205 |
+
flow_orig = flow
|
| 206 |
+
flow = self.convflow1(flow)
|
| 207 |
+
flow = self.convflow2(flow)
|
| 208 |
+
|
| 209 |
+
corr_flow = torch.cat([corr, flow], dim=1)
|
| 210 |
+
corr_flow = self.conv(corr_flow)
|
| 211 |
+
return torch.cat([corr_flow, flow_orig], dim=1)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class ConvGRU(nn.Module):
|
| 215 |
+
"""Convolutional Gru unit."""
|
| 216 |
+
|
| 217 |
+
def __init__(self, *, input_size, hidden_size, kernel_size, padding):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.convz = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding)
|
| 220 |
+
self.convr = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding)
|
| 221 |
+
self.convq = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding)
|
| 222 |
+
|
| 223 |
+
def forward(self, h, x):
|
| 224 |
+
hx = torch.cat([h, x], dim=1)
|
| 225 |
+
z = torch.sigmoid(self.convz(hx))
|
| 226 |
+
r = torch.sigmoid(self.convr(hx))
|
| 227 |
+
q = torch.tanh(self.convq(torch.cat([r * h, x], dim=1)))
|
| 228 |
+
h = (1 - z) * h + z * q
|
| 229 |
+
return h
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _pass_through_h(h, _):
|
| 233 |
+
# Declared here for torchscript
|
| 234 |
+
return h
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class RecurrentBlock(nn.Module):
|
| 238 |
+
"""Recurrent block, part of the update block.
|
| 239 |
+
|
| 240 |
+
Takes the current hidden state and the concatenation of (motion encoder output, context) as input.
|
| 241 |
+
Returns an updated hidden state.
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
def __init__(self, *, input_size, hidden_size, kernel_size=((1, 5), (5, 1)), padding=((0, 2), (2, 0))):
|
| 245 |
+
super().__init__()
|
| 246 |
+
|
| 247 |
+
if len(kernel_size) != len(padding):
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"kernel_size should have the same length as padding, instead got len(kernel_size) = {len(kernel_size)} and len(padding) = {len(padding)}"
|
| 250 |
+
)
|
| 251 |
+
if len(kernel_size) not in (1, 2):
|
| 252 |
+
raise ValueError(f"kernel_size should either 1 or 2, instead got {len(kernel_size)}")
|
| 253 |
+
|
| 254 |
+
self.convgru1 = ConvGRU(
|
| 255 |
+
input_size=input_size, hidden_size=hidden_size, kernel_size=kernel_size[0], padding=padding[0]
|
| 256 |
+
)
|
| 257 |
+
if len(kernel_size) == 2:
|
| 258 |
+
self.convgru2 = ConvGRU(
|
| 259 |
+
input_size=input_size, hidden_size=hidden_size, kernel_size=kernel_size[1], padding=padding[1]
|
| 260 |
+
)
|
| 261 |
+
else:
|
| 262 |
+
self.convgru2 = _pass_through_h
|
| 263 |
+
|
| 264 |
+
self.hidden_size = hidden_size
|
| 265 |
+
|
| 266 |
+
def forward(self, h, x):
|
| 267 |
+
h = self.convgru1(h, x)
|
| 268 |
+
h = self.convgru2(h, x)
|
| 269 |
+
return h
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class FlowHead(nn.Module):
|
| 273 |
+
"""Flow head, part of the update block.
|
| 274 |
+
|
| 275 |
+
Takes the hidden state of the recurrent unit as input, and outputs the predicted "delta flow".
|
| 276 |
+
"""
|
| 277 |
+
|
| 278 |
+
def __init__(self, *, in_channels, hidden_size):
|
| 279 |
+
super().__init__()
|
| 280 |
+
self.conv1 = nn.Conv2d(in_channels, hidden_size, 3, padding=1)
|
| 281 |
+
self.conv2 = nn.Conv2d(hidden_size, 2, 3, padding=1)
|
| 282 |
+
self.relu = nn.ReLU(inplace=True)
|
| 283 |
+
|
| 284 |
+
def forward(self, x):
|
| 285 |
+
return self.conv2(self.relu(self.conv1(x)))
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class UpdateBlock(nn.Module):
|
| 289 |
+
"""The update block which contains the motion encoder, the recurrent block, and the flow head.
|
| 290 |
+
|
| 291 |
+
It must expose a ``hidden_state_size`` attribute which is the hidden state size of its recurrent block.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def __init__(self, *, motion_encoder, recurrent_block, flow_head):
|
| 295 |
+
super().__init__()
|
| 296 |
+
self.motion_encoder = motion_encoder
|
| 297 |
+
self.recurrent_block = recurrent_block
|
| 298 |
+
self.flow_head = flow_head
|
| 299 |
+
|
| 300 |
+
self.hidden_state_size = recurrent_block.hidden_size
|
| 301 |
+
|
| 302 |
+
def forward(self, hidden_state, context, corr_features, flow):
|
| 303 |
+
motion_features = self.motion_encoder(flow, corr_features)
|
| 304 |
+
x = torch.cat([context, motion_features], dim=1)
|
| 305 |
+
|
| 306 |
+
hidden_state = self.recurrent_block(hidden_state, x)
|
| 307 |
+
delta_flow = self.flow_head(hidden_state)
|
| 308 |
+
return hidden_state, delta_flow
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class MaskPredictor(nn.Module):
|
| 312 |
+
"""Mask predictor to be used when upsampling the predicted flow.
|
| 313 |
+
|
| 314 |
+
It takes the hidden state of the recurrent unit as input and outputs the mask.
|
| 315 |
+
This is not used in the raft-small model.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
def __init__(self, *, in_channels, hidden_size, multiplier=0.25):
|
| 319 |
+
super().__init__()
|
| 320 |
+
self.convrelu = Conv2dNormActivation(in_channels, hidden_size, norm_layer=None, kernel_size=3)
|
| 321 |
+
# 8 * 8 * 9 because the predicted flow is downsampled by 8, from the downsampling of the initial FeatureEncoder,
|
| 322 |
+
# and we interpolate with all 9 surrounding neighbors. See paper and appendix B.
|
| 323 |
+
self.conv = nn.Conv2d(hidden_size, 8 * 8 * 9, 1, padding=0)
|
| 324 |
+
|
| 325 |
+
# In the original code, they use a factor of 0.25 to "downweight the gradients" of that branch.
|
| 326 |
+
# See e.g. https://github.com/princeton-vl/RAFT/issues/119#issuecomment-953950419
|
| 327 |
+
# or https://github.com/princeton-vl/RAFT/issues/24.
|
| 328 |
+
# It doesn't seem to affect epe significantly and can likely be set to 1.
|
| 329 |
+
self.multiplier = multiplier
|
| 330 |
+
|
| 331 |
+
def forward(self, x):
|
| 332 |
+
x = self.convrelu(x)
|
| 333 |
+
x = self.conv(x)
|
| 334 |
+
return self.multiplier * x
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class CorrBlock(nn.Module):
|
| 338 |
+
"""The correlation block.
|
| 339 |
+
|
| 340 |
+
Creates a correlation pyramid with ``num_levels`` levels from the outputs of the feature encoder,
|
| 341 |
+
and then indexes from this pyramid to create correlation features.
|
| 342 |
+
The "indexing" of a given centroid pixel x' is done by concatenating its surrounding neighbors that
|
| 343 |
+
are within a ``radius``, according to the infinity norm (see paper section 3.2).
|
| 344 |
+
Note: typo in the paper, it should be infinity norm, not 1-norm.
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
def __init__(self, *, num_levels: int = 4, radius: int = 4):
|
| 348 |
+
super().__init__()
|
| 349 |
+
self.num_levels = num_levels
|
| 350 |
+
self.radius = radius
|
| 351 |
+
|
| 352 |
+
self.corr_pyramid: List[Tensor] = [torch.tensor(0)] # useless, but torchscript is otherwise confused :')
|
| 353 |
+
|
| 354 |
+
# The neighborhood of a centroid pixel x' is {x' + delta, ||delta||_inf <= radius}
|
| 355 |
+
# so it's a square surrounding x', and its sides have a length of 2 * radius + 1
|
| 356 |
+
# The paper claims that it's ||.||_1 instead of ||.||_inf but it's a typo:
|
| 357 |
+
# https://github.com/princeton-vl/RAFT/issues/122
|
| 358 |
+
self.out_channels = num_levels * (2 * radius + 1) ** 2
|
| 359 |
+
|
| 360 |
+
def build_pyramid(self, fmap1, fmap2):
|
| 361 |
+
"""Build the correlation pyramid from two feature maps.
|
| 362 |
+
|
| 363 |
+
The correlation volume is first computed as the dot product of each pair (pixel_in_fmap1, pixel_in_fmap2)
|
| 364 |
+
The last 2 dimensions of the correlation volume are then pooled num_levels times at different resolutions
|
| 365 |
+
to build the correlation pyramid.
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
if fmap1.shape != fmap2.shape:
|
| 369 |
+
raise ValueError(
|
| 370 |
+
f"Input feature maps should have the same shape, instead got {fmap1.shape} (fmap1.shape) != {fmap2.shape} (fmap2.shape)"
|
| 371 |
+
)
|
| 372 |
+
corr_volume = self._compute_corr_volume(fmap1, fmap2)
|
| 373 |
+
|
| 374 |
+
batch_size, h, w, num_channels, _, _ = corr_volume.shape # _, _ = h, w
|
| 375 |
+
corr_volume = corr_volume.reshape(batch_size * h * w, num_channels, h, w)
|
| 376 |
+
self.corr_pyramid = [corr_volume]
|
| 377 |
+
for _ in range(self.num_levels - 1):
|
| 378 |
+
corr_volume = F.avg_pool2d(corr_volume, kernel_size=2, stride=2)
|
| 379 |
+
self.corr_pyramid.append(corr_volume)
|
| 380 |
+
|
| 381 |
+
def index_pyramid(self, centroids_coords):
|
| 382 |
+
"""Return correlation features by indexing from the pyramid."""
|
| 383 |
+
neighborhood_side_len = 2 * self.radius + 1 # see note in __init__ about out_channels
|
| 384 |
+
di = torch.linspace(-self.radius, self.radius, neighborhood_side_len)
|
| 385 |
+
dj = torch.linspace(-self.radius, self.radius, neighborhood_side_len)
|
| 386 |
+
delta = torch.stack(torch.meshgrid(di, dj, indexing="ij"), dim=-1).to(centroids_coords.device)
|
| 387 |
+
delta = delta.view(1, neighborhood_side_len, neighborhood_side_len, 2)
|
| 388 |
+
|
| 389 |
+
batch_size, _, h, w = centroids_coords.shape # _ = 2
|
| 390 |
+
centroids_coords = centroids_coords.permute(0, 2, 3, 1).reshape(batch_size * h * w, 1, 1, 2)
|
| 391 |
+
|
| 392 |
+
indexed_pyramid = []
|
| 393 |
+
for corr_volume in self.corr_pyramid:
|
| 394 |
+
sampling_coords = centroids_coords + delta # end shape is (batch_size * h * w, side_len, side_len, 2)
|
| 395 |
+
indexed_corr_volume = grid_sample(corr_volume, sampling_coords, align_corners=True, mode="bilinear").view(
|
| 396 |
+
batch_size, h, w, -1
|
| 397 |
+
)
|
| 398 |
+
indexed_pyramid.append(indexed_corr_volume)
|
| 399 |
+
centroids_coords = centroids_coords / 2
|
| 400 |
+
|
| 401 |
+
corr_features = torch.cat(indexed_pyramid, dim=-1).permute(0, 3, 1, 2).contiguous()
|
| 402 |
+
|
| 403 |
+
expected_output_shape = (batch_size, self.out_channels, h, w)
|
| 404 |
+
if corr_features.shape != expected_output_shape:
|
| 405 |
+
raise ValueError(
|
| 406 |
+
f"Output shape of index pyramid is incorrect. Should be {expected_output_shape}, got {corr_features.shape}"
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
return corr_features
|
| 410 |
+
|
| 411 |
+
def _compute_corr_volume(self, fmap1, fmap2):
|
| 412 |
+
batch_size, num_channels, h, w = fmap1.shape
|
| 413 |
+
fmap1 = fmap1.view(batch_size, num_channels, h * w)
|
| 414 |
+
fmap2 = fmap2.view(batch_size, num_channels, h * w)
|
| 415 |
+
|
| 416 |
+
corr = torch.matmul(fmap1.transpose(1, 2), fmap2)
|
| 417 |
+
corr = corr.view(batch_size, h, w, 1, h, w)
|
| 418 |
+
return corr / torch.sqrt(torch.tensor(num_channels))
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class RAFT(nn.Module):
|
| 422 |
+
def __init__(self, *, feature_encoder, context_encoder, corr_block, update_block, mask_predictor=None):
|
| 423 |
+
"""RAFT model from
|
| 424 |
+
`RAFT: Recurrent All Pairs Field Transforms for Optical Flow <https://arxiv.org/abs/2003.12039>`_.
|
| 425 |
+
|
| 426 |
+
args:
|
| 427 |
+
feature_encoder (nn.Module): The feature encoder. It must downsample the input by 8.
|
| 428 |
+
Its input is the concatenation of ``image1`` and ``image2``.
|
| 429 |
+
context_encoder (nn.Module): The context encoder. It must downsample the input by 8.
|
| 430 |
+
Its input is ``image1``. As in the original implementation, its output will be split into 2 parts:
|
| 431 |
+
|
| 432 |
+
- one part will be used as the actual "context", passed to the recurrent unit of the ``update_block``
|
| 433 |
+
- one part will be used to initialize the hidden state of the recurrent unit of
|
| 434 |
+
the ``update_block``
|
| 435 |
+
|
| 436 |
+
These 2 parts are split according to the ``hidden_state_size`` of the ``update_block``, so the output
|
| 437 |
+
of the ``context_encoder`` must be strictly greater than ``hidden_state_size``.
|
| 438 |
+
|
| 439 |
+
corr_block (nn.Module): The correlation block, which creates a correlation pyramid from the output of the
|
| 440 |
+
``feature_encoder``, and then indexes from this pyramid to create correlation features. It must expose
|
| 441 |
+
2 methods:
|
| 442 |
+
|
| 443 |
+
- a ``build_pyramid`` method that takes ``feature_map_1`` and ``feature_map_2`` as input (these are the
|
| 444 |
+
output of the ``feature_encoder``).
|
| 445 |
+
- a ``index_pyramid`` method that takes the coordinates of the centroid pixels as input, and returns
|
| 446 |
+
the correlation features. See paper section 3.2.
|
| 447 |
+
|
| 448 |
+
It must expose an ``out_channels`` attribute.
|
| 449 |
+
|
| 450 |
+
update_block (nn.Module): The update block, which contains the motion encoder, the recurrent unit, and the
|
| 451 |
+
flow head. It takes as input the hidden state of its recurrent unit, the context, the correlation
|
| 452 |
+
features, and the current predicted flow. It outputs an updated hidden state, and the ``delta_flow``
|
| 453 |
+
prediction (see paper appendix A). It must expose a ``hidden_state_size`` attribute.
|
| 454 |
+
mask_predictor (nn.Module, optional): Predicts the mask that will be used to upsample the predicted flow.
|
| 455 |
+
The output channel must be 8 * 8 * 9 - see paper section 3.3, and Appendix B.
|
| 456 |
+
If ``None`` (default), the flow is upsampled using interpolation.
|
| 457 |
+
"""
|
| 458 |
+
super().__init__()
|
| 459 |
+
_log_api_usage_once(self)
|
| 460 |
+
|
| 461 |
+
self.feature_encoder = feature_encoder
|
| 462 |
+
self.context_encoder = context_encoder
|
| 463 |
+
self.corr_block = corr_block
|
| 464 |
+
self.update_block = update_block
|
| 465 |
+
|
| 466 |
+
self.mask_predictor = mask_predictor
|
| 467 |
+
|
| 468 |
+
if not hasattr(self.update_block, "hidden_state_size"):
|
| 469 |
+
raise ValueError("The update_block parameter should expose a 'hidden_state_size' attribute.")
|
| 470 |
+
|
| 471 |
+
def forward(self, image1, image2, num_flow_updates: int = 12):
|
| 472 |
+
|
| 473 |
+
batch_size, _, h, w = image1.shape
|
| 474 |
+
if (h, w) != image2.shape[-2:]:
|
| 475 |
+
raise ValueError(f"input images should have the same shape, instead got ({h}, {w}) != {image2.shape[-2:]}")
|
| 476 |
+
if not (h % 8 == 0) and (w % 8 == 0):
|
| 477 |
+
raise ValueError(f"input image H and W should be divisible by 8, instead got {h} (h) and {w} (w)")
|
| 478 |
+
|
| 479 |
+
fmaps = self.feature_encoder(torch.cat([image1, image2], dim=0))
|
| 480 |
+
fmap1, fmap2 = torch.chunk(fmaps, chunks=2, dim=0)
|
| 481 |
+
if fmap1.shape[-2:] != (h // 8, w // 8):
|
| 482 |
+
raise ValueError("The feature encoder should downsample H and W by 8")
|
| 483 |
+
|
| 484 |
+
self.corr_block.build_pyramid(fmap1, fmap2)
|
| 485 |
+
|
| 486 |
+
context_out = self.context_encoder(image1)
|
| 487 |
+
if context_out.shape[-2:] != (h // 8, w // 8):
|
| 488 |
+
raise ValueError("The context encoder should downsample H and W by 8")
|
| 489 |
+
|
| 490 |
+
# As in the original paper, the actual output of the context encoder is split in 2 parts:
|
| 491 |
+
# - one part is used to initialize the hidden state of the recurent units of the update block
|
| 492 |
+
# - the rest is the "actual" context.
|
| 493 |
+
hidden_state_size = self.update_block.hidden_state_size
|
| 494 |
+
out_channels_context = context_out.shape[1] - hidden_state_size
|
| 495 |
+
if out_channels_context <= 0:
|
| 496 |
+
raise ValueError(
|
| 497 |
+
f"The context encoder outputs {context_out.shape[1]} channels, but it should have at strictly more than hidden_state={hidden_state_size} channels"
|
| 498 |
+
)
|
| 499 |
+
hidden_state, context = torch.split(context_out, [hidden_state_size, out_channels_context], dim=1)
|
| 500 |
+
hidden_state = torch.tanh(hidden_state)
|
| 501 |
+
context = F.relu(context)
|
| 502 |
+
|
| 503 |
+
coords0 = make_coords_grid(batch_size, h // 8, w // 8).to(fmap1.device)
|
| 504 |
+
coords1 = make_coords_grid(batch_size, h // 8, w // 8).to(fmap1.device)
|
| 505 |
+
|
| 506 |
+
flow_predictions = []
|
| 507 |
+
for _ in range(num_flow_updates):
|
| 508 |
+
coords1 = coords1.detach() # Don't backpropagate gradients through this branch, see paper
|
| 509 |
+
corr_features = self.corr_block.index_pyramid(centroids_coords=coords1)
|
| 510 |
+
|
| 511 |
+
flow = coords1 - coords0
|
| 512 |
+
hidden_state, delta_flow = self.update_block(hidden_state, context, corr_features, flow)
|
| 513 |
+
|
| 514 |
+
coords1 = coords1 + delta_flow
|
| 515 |
+
|
| 516 |
+
up_mask = None if self.mask_predictor is None else self.mask_predictor(hidden_state)
|
| 517 |
+
upsampled_flow = upsample_flow(flow=(coords1 - coords0), up_mask=up_mask)
|
| 518 |
+
flow_predictions.append(upsampled_flow)
|
| 519 |
+
|
| 520 |
+
return flow_predictions
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
_COMMON_META = {
|
| 524 |
+
"min_size": (128, 128),
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
class Raft_Large_Weights(WeightsEnum):
|
| 529 |
+
"""The metrics reported here are as follows.
|
| 530 |
+
|
| 531 |
+
``epe`` is the "end-point-error" and indicates how far (in pixels) the
|
| 532 |
+
predicted flow is from its true value. This is averaged over all pixels
|
| 533 |
+
of all images. ``per_image_epe`` is similar, but the average is different:
|
| 534 |
+
the epe is first computed on each image independently, and then averaged
|
| 535 |
+
over all images. This corresponds to "Fl-epe" (sometimes written "F1-epe")
|
| 536 |
+
in the original paper, and it's only used on Kitti. ``fl-all`` is also a
|
| 537 |
+
Kitti-specific metric, defined by the author of the dataset and used for the
|
| 538 |
+
Kitti leaderboard. It corresponds to the average of pixels whose epe is
|
| 539 |
+
either <3px, or <5% of flow's 2-norm.
|
| 540 |
+
"""
|
| 541 |
+
|
| 542 |
+
C_T_V1 = Weights(
|
| 543 |
+
# Weights ported from https://github.com/princeton-vl/RAFT
|
| 544 |
+
url="https://download.pytorch.org/models/raft_large_C_T_V1-22a6c225.pth",
|
| 545 |
+
transforms=OpticalFlow,
|
| 546 |
+
meta={
|
| 547 |
+
**_COMMON_META,
|
| 548 |
+
"num_params": 5257536,
|
| 549 |
+
"recipe": "https://github.com/princeton-vl/RAFT",
|
| 550 |
+
"_metrics": {
|
| 551 |
+
"Sintel-Train-Cleanpass": {"epe": 1.4411},
|
| 552 |
+
"Sintel-Train-Finalpass": {"epe": 2.7894},
|
| 553 |
+
"Kitti-Train": {"per_image_epe": 5.0172, "fl_all": 17.4506},
|
| 554 |
+
},
|
| 555 |
+
"_ops": 211.007,
|
| 556 |
+
"_file_size": 20.129,
|
| 557 |
+
"_docs": """These weights were ported from the original paper. They
|
| 558 |
+
are trained on :class:`~torchvision.datasets.FlyingChairs` +
|
| 559 |
+
:class:`~torchvision.datasets.FlyingThings3D`.""",
|
| 560 |
+
},
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
C_T_V2 = Weights(
|
| 564 |
+
url="https://download.pytorch.org/models/raft_large_C_T_V2-1bb1363a.pth",
|
| 565 |
+
transforms=OpticalFlow,
|
| 566 |
+
meta={
|
| 567 |
+
**_COMMON_META,
|
| 568 |
+
"num_params": 5257536,
|
| 569 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow",
|
| 570 |
+
"_metrics": {
|
| 571 |
+
"Sintel-Train-Cleanpass": {"epe": 1.3822},
|
| 572 |
+
"Sintel-Train-Finalpass": {"epe": 2.7161},
|
| 573 |
+
"Kitti-Train": {"per_image_epe": 4.5118, "fl_all": 16.0679},
|
| 574 |
+
},
|
| 575 |
+
"_ops": 211.007,
|
| 576 |
+
"_file_size": 20.129,
|
| 577 |
+
"_docs": """These weights were trained from scratch on
|
| 578 |
+
:class:`~torchvision.datasets.FlyingChairs` +
|
| 579 |
+
:class:`~torchvision.datasets.FlyingThings3D`.""",
|
| 580 |
+
},
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
C_T_SKHT_V1 = Weights(
|
| 584 |
+
# Weights ported from https://github.com/princeton-vl/RAFT
|
| 585 |
+
url="https://download.pytorch.org/models/raft_large_C_T_SKHT_V1-0b8c9e55.pth",
|
| 586 |
+
transforms=OpticalFlow,
|
| 587 |
+
meta={
|
| 588 |
+
**_COMMON_META,
|
| 589 |
+
"num_params": 5257536,
|
| 590 |
+
"recipe": "https://github.com/princeton-vl/RAFT",
|
| 591 |
+
"_metrics": {
|
| 592 |
+
"Sintel-Test-Cleanpass": {"epe": 1.94},
|
| 593 |
+
"Sintel-Test-Finalpass": {"epe": 3.18},
|
| 594 |
+
},
|
| 595 |
+
"_ops": 211.007,
|
| 596 |
+
"_file_size": 20.129,
|
| 597 |
+
"_docs": """
|
| 598 |
+
These weights were ported from the original paper. They are
|
| 599 |
+
trained on :class:`~torchvision.datasets.FlyingChairs` +
|
| 600 |
+
:class:`~torchvision.datasets.FlyingThings3D` and fine-tuned on
|
| 601 |
+
Sintel. The Sintel fine-tuning step is a combination of
|
| 602 |
+
:class:`~torchvision.datasets.Sintel`,
|
| 603 |
+
:class:`~torchvision.datasets.KittiFlow`,
|
| 604 |
+
:class:`~torchvision.datasets.HD1K`, and
|
| 605 |
+
:class:`~torchvision.datasets.FlyingThings3D` (clean pass).
|
| 606 |
+
""",
|
| 607 |
+
},
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
C_T_SKHT_V2 = Weights(
|
| 611 |
+
url="https://download.pytorch.org/models/raft_large_C_T_SKHT_V2-ff5fadd5.pth",
|
| 612 |
+
transforms=OpticalFlow,
|
| 613 |
+
meta={
|
| 614 |
+
**_COMMON_META,
|
| 615 |
+
"num_params": 5257536,
|
| 616 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow",
|
| 617 |
+
"_metrics": {
|
| 618 |
+
"Sintel-Test-Cleanpass": {"epe": 1.819},
|
| 619 |
+
"Sintel-Test-Finalpass": {"epe": 3.067},
|
| 620 |
+
},
|
| 621 |
+
"_ops": 211.007,
|
| 622 |
+
"_file_size": 20.129,
|
| 623 |
+
"_docs": """
|
| 624 |
+
These weights were trained from scratch. They are
|
| 625 |
+
pre-trained on :class:`~torchvision.datasets.FlyingChairs` +
|
| 626 |
+
:class:`~torchvision.datasets.FlyingThings3D` and then
|
| 627 |
+
fine-tuned on Sintel. The Sintel fine-tuning step is a
|
| 628 |
+
combination of :class:`~torchvision.datasets.Sintel`,
|
| 629 |
+
:class:`~torchvision.datasets.KittiFlow`,
|
| 630 |
+
:class:`~torchvision.datasets.HD1K`, and
|
| 631 |
+
:class:`~torchvision.datasets.FlyingThings3D` (clean pass).
|
| 632 |
+
""",
|
| 633 |
+
},
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
C_T_SKHT_K_V1 = Weights(
|
| 637 |
+
# Weights ported from https://github.com/princeton-vl/RAFT
|
| 638 |
+
url="https://download.pytorch.org/models/raft_large_C_T_SKHT_K_V1-4a6a5039.pth",
|
| 639 |
+
transforms=OpticalFlow,
|
| 640 |
+
meta={
|
| 641 |
+
**_COMMON_META,
|
| 642 |
+
"num_params": 5257536,
|
| 643 |
+
"recipe": "https://github.com/princeton-vl/RAFT",
|
| 644 |
+
"_metrics": {
|
| 645 |
+
"Kitti-Test": {"fl_all": 5.10},
|
| 646 |
+
},
|
| 647 |
+
"_ops": 211.007,
|
| 648 |
+
"_file_size": 20.129,
|
| 649 |
+
"_docs": """
|
| 650 |
+
These weights were ported from the original paper. They are
|
| 651 |
+
pre-trained on :class:`~torchvision.datasets.FlyingChairs` +
|
| 652 |
+
:class:`~torchvision.datasets.FlyingThings3D`,
|
| 653 |
+
fine-tuned on Sintel, and then fine-tuned on
|
| 654 |
+
:class:`~torchvision.datasets.KittiFlow`. The Sintel fine-tuning
|
| 655 |
+
step was described above.
|
| 656 |
+
""",
|
| 657 |
+
},
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
C_T_SKHT_K_V2 = Weights(
|
| 661 |
+
url="https://download.pytorch.org/models/raft_large_C_T_SKHT_K_V2-b5c70766.pth",
|
| 662 |
+
transforms=OpticalFlow,
|
| 663 |
+
meta={
|
| 664 |
+
**_COMMON_META,
|
| 665 |
+
"num_params": 5257536,
|
| 666 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow",
|
| 667 |
+
"_metrics": {
|
| 668 |
+
"Kitti-Test": {"fl_all": 5.19},
|
| 669 |
+
},
|
| 670 |
+
"_ops": 211.007,
|
| 671 |
+
"_file_size": 20.129,
|
| 672 |
+
"_docs": """
|
| 673 |
+
These weights were trained from scratch. They are
|
| 674 |
+
pre-trained on :class:`~torchvision.datasets.FlyingChairs` +
|
| 675 |
+
:class:`~torchvision.datasets.FlyingThings3D`,
|
| 676 |
+
fine-tuned on Sintel, and then fine-tuned on
|
| 677 |
+
:class:`~torchvision.datasets.KittiFlow`. The Sintel fine-tuning
|
| 678 |
+
step was described above.
|
| 679 |
+
""",
|
| 680 |
+
},
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
DEFAULT = C_T_SKHT_V2
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
class Raft_Small_Weights(WeightsEnum):
|
| 687 |
+
"""The metrics reported here are as follows.
|
| 688 |
+
|
| 689 |
+
``epe`` is the "end-point-error" and indicates how far (in pixels) the
|
| 690 |
+
predicted flow is from its true value. This is averaged over all pixels
|
| 691 |
+
of all images. ``per_image_epe`` is similar, but the average is different:
|
| 692 |
+
the epe is first computed on each image independently, and then averaged
|
| 693 |
+
over all images. This corresponds to "Fl-epe" (sometimes written "F1-epe")
|
| 694 |
+
in the original paper, and it's only used on Kitti. ``fl-all`` is also a
|
| 695 |
+
Kitti-specific metric, defined by the author of the dataset and used for the
|
| 696 |
+
Kitti leaderboard. It corresponds to the average of pixels whose epe is
|
| 697 |
+
either <3px, or <5% of flow's 2-norm.
|
| 698 |
+
"""
|
| 699 |
+
|
| 700 |
+
C_T_V1 = Weights(
|
| 701 |
+
# Weights ported from https://github.com/princeton-vl/RAFT
|
| 702 |
+
url="https://download.pytorch.org/models/raft_small_C_T_V1-ad48884c.pth",
|
| 703 |
+
transforms=OpticalFlow,
|
| 704 |
+
meta={
|
| 705 |
+
**_COMMON_META,
|
| 706 |
+
"num_params": 990162,
|
| 707 |
+
"recipe": "https://github.com/princeton-vl/RAFT",
|
| 708 |
+
"_metrics": {
|
| 709 |
+
"Sintel-Train-Cleanpass": {"epe": 2.1231},
|
| 710 |
+
"Sintel-Train-Finalpass": {"epe": 3.2790},
|
| 711 |
+
"Kitti-Train": {"per_image_epe": 7.6557, "fl_all": 25.2801},
|
| 712 |
+
},
|
| 713 |
+
"_ops": 47.655,
|
| 714 |
+
"_file_size": 3.821,
|
| 715 |
+
"_docs": """These weights were ported from the original paper. They
|
| 716 |
+
are trained on :class:`~torchvision.datasets.FlyingChairs` +
|
| 717 |
+
:class:`~torchvision.datasets.FlyingThings3D`.""",
|
| 718 |
+
},
|
| 719 |
+
)
|
| 720 |
+
C_T_V2 = Weights(
|
| 721 |
+
url="https://download.pytorch.org/models/raft_small_C_T_V2-01064c6d.pth",
|
| 722 |
+
transforms=OpticalFlow,
|
| 723 |
+
meta={
|
| 724 |
+
**_COMMON_META,
|
| 725 |
+
"num_params": 990162,
|
| 726 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow",
|
| 727 |
+
"_metrics": {
|
| 728 |
+
"Sintel-Train-Cleanpass": {"epe": 1.9901},
|
| 729 |
+
"Sintel-Train-Finalpass": {"epe": 3.2831},
|
| 730 |
+
"Kitti-Train": {"per_image_epe": 7.5978, "fl_all": 25.2369},
|
| 731 |
+
},
|
| 732 |
+
"_ops": 47.655,
|
| 733 |
+
"_file_size": 3.821,
|
| 734 |
+
"_docs": """These weights were trained from scratch on
|
| 735 |
+
:class:`~torchvision.datasets.FlyingChairs` +
|
| 736 |
+
:class:`~torchvision.datasets.FlyingThings3D`.""",
|
| 737 |
+
},
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
DEFAULT = C_T_V2
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _raft(
|
| 744 |
+
*,
|
| 745 |
+
weights=None,
|
| 746 |
+
progress=False,
|
| 747 |
+
# Feature encoder
|
| 748 |
+
feature_encoder_layers,
|
| 749 |
+
feature_encoder_block,
|
| 750 |
+
feature_encoder_norm_layer,
|
| 751 |
+
# Context encoder
|
| 752 |
+
context_encoder_layers,
|
| 753 |
+
context_encoder_block,
|
| 754 |
+
context_encoder_norm_layer,
|
| 755 |
+
# Correlation block
|
| 756 |
+
corr_block_num_levels,
|
| 757 |
+
corr_block_radius,
|
| 758 |
+
# Motion encoder
|
| 759 |
+
motion_encoder_corr_layers,
|
| 760 |
+
motion_encoder_flow_layers,
|
| 761 |
+
motion_encoder_out_channels,
|
| 762 |
+
# Recurrent block
|
| 763 |
+
recurrent_block_hidden_state_size,
|
| 764 |
+
recurrent_block_kernel_size,
|
| 765 |
+
recurrent_block_padding,
|
| 766 |
+
# Flow Head
|
| 767 |
+
flow_head_hidden_size,
|
| 768 |
+
# Mask predictor
|
| 769 |
+
use_mask_predictor,
|
| 770 |
+
**kwargs,
|
| 771 |
+
):
|
| 772 |
+
feature_encoder = kwargs.pop("feature_encoder", None) or FeatureEncoder(
|
| 773 |
+
block=feature_encoder_block, layers=feature_encoder_layers, norm_layer=feature_encoder_norm_layer
|
| 774 |
+
)
|
| 775 |
+
context_encoder = kwargs.pop("context_encoder", None) or FeatureEncoder(
|
| 776 |
+
block=context_encoder_block, layers=context_encoder_layers, norm_layer=context_encoder_norm_layer
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
corr_block = kwargs.pop("corr_block", None) or CorrBlock(num_levels=corr_block_num_levels, radius=corr_block_radius)
|
| 780 |
+
|
| 781 |
+
update_block = kwargs.pop("update_block", None)
|
| 782 |
+
if update_block is None:
|
| 783 |
+
motion_encoder = MotionEncoder(
|
| 784 |
+
in_channels_corr=corr_block.out_channels,
|
| 785 |
+
corr_layers=motion_encoder_corr_layers,
|
| 786 |
+
flow_layers=motion_encoder_flow_layers,
|
| 787 |
+
out_channels=motion_encoder_out_channels,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
# See comments in forward pass of RAFT class about why we split the output of the context encoder
|
| 791 |
+
out_channels_context = context_encoder_layers[-1] - recurrent_block_hidden_state_size
|
| 792 |
+
recurrent_block = RecurrentBlock(
|
| 793 |
+
input_size=motion_encoder.out_channels + out_channels_context,
|
| 794 |
+
hidden_size=recurrent_block_hidden_state_size,
|
| 795 |
+
kernel_size=recurrent_block_kernel_size,
|
| 796 |
+
padding=recurrent_block_padding,
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
flow_head = FlowHead(in_channels=recurrent_block_hidden_state_size, hidden_size=flow_head_hidden_size)
|
| 800 |
+
|
| 801 |
+
update_block = UpdateBlock(motion_encoder=motion_encoder, recurrent_block=recurrent_block, flow_head=flow_head)
|
| 802 |
+
|
| 803 |
+
mask_predictor = kwargs.pop("mask_predictor", None)
|
| 804 |
+
if mask_predictor is None and use_mask_predictor:
|
| 805 |
+
mask_predictor = MaskPredictor(
|
| 806 |
+
in_channels=recurrent_block_hidden_state_size,
|
| 807 |
+
hidden_size=256,
|
| 808 |
+
multiplier=0.25, # See comment in MaskPredictor about this
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
model = RAFT(
|
| 812 |
+
feature_encoder=feature_encoder,
|
| 813 |
+
context_encoder=context_encoder,
|
| 814 |
+
corr_block=corr_block,
|
| 815 |
+
update_block=update_block,
|
| 816 |
+
mask_predictor=mask_predictor,
|
| 817 |
+
**kwargs, # not really needed, all params should be consumed by now
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
if weights is not None:
|
| 821 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 822 |
+
|
| 823 |
+
return model
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
@register_model()
|
| 827 |
+
@handle_legacy_interface(weights=("pretrained", Raft_Large_Weights.C_T_SKHT_V2))
|
| 828 |
+
def raft_large(*, weights: Optional[Raft_Large_Weights] = None, progress=True, **kwargs) -> RAFT:
|
| 829 |
+
"""RAFT model from
|
| 830 |
+
`RAFT: Recurrent All Pairs Field Transforms for Optical Flow <https://arxiv.org/abs/2003.12039>`_.
|
| 831 |
+
|
| 832 |
+
Please see the example below for a tutorial on how to use this model.
|
| 833 |
+
|
| 834 |
+
Args:
|
| 835 |
+
weights(:class:`~torchvision.models.optical_flow.Raft_Large_Weights`, optional): The
|
| 836 |
+
pretrained weights to use. See
|
| 837 |
+
:class:`~torchvision.models.optical_flow.Raft_Large_Weights`
|
| 838 |
+
below for more details, and possible values. By default, no
|
| 839 |
+
pre-trained weights are used.
|
| 840 |
+
progress (bool): If True, displays a progress bar of the download to stderr. Default is True.
|
| 841 |
+
**kwargs: parameters passed to the ``torchvision.models.optical_flow.RAFT``
|
| 842 |
+
base class. Please refer to the `source code
|
| 843 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/optical_flow/raft.py>`_
|
| 844 |
+
for more details about this class.
|
| 845 |
+
|
| 846 |
+
.. autoclass:: torchvision.models.optical_flow.Raft_Large_Weights
|
| 847 |
+
:members:
|
| 848 |
+
"""
|
| 849 |
+
|
| 850 |
+
weights = Raft_Large_Weights.verify(weights)
|
| 851 |
+
|
| 852 |
+
return _raft(
|
| 853 |
+
weights=weights,
|
| 854 |
+
progress=progress,
|
| 855 |
+
# Feature encoder
|
| 856 |
+
feature_encoder_layers=(64, 64, 96, 128, 256),
|
| 857 |
+
feature_encoder_block=ResidualBlock,
|
| 858 |
+
feature_encoder_norm_layer=InstanceNorm2d,
|
| 859 |
+
# Context encoder
|
| 860 |
+
context_encoder_layers=(64, 64, 96, 128, 256),
|
| 861 |
+
context_encoder_block=ResidualBlock,
|
| 862 |
+
context_encoder_norm_layer=BatchNorm2d,
|
| 863 |
+
# Correlation block
|
| 864 |
+
corr_block_num_levels=4,
|
| 865 |
+
corr_block_radius=4,
|
| 866 |
+
# Motion encoder
|
| 867 |
+
motion_encoder_corr_layers=(256, 192),
|
| 868 |
+
motion_encoder_flow_layers=(128, 64),
|
| 869 |
+
motion_encoder_out_channels=128,
|
| 870 |
+
# Recurrent block
|
| 871 |
+
recurrent_block_hidden_state_size=128,
|
| 872 |
+
recurrent_block_kernel_size=((1, 5), (5, 1)),
|
| 873 |
+
recurrent_block_padding=((0, 2), (2, 0)),
|
| 874 |
+
# Flow head
|
| 875 |
+
flow_head_hidden_size=256,
|
| 876 |
+
# Mask predictor
|
| 877 |
+
use_mask_predictor=True,
|
| 878 |
+
**kwargs,
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
@register_model()
|
| 883 |
+
@handle_legacy_interface(weights=("pretrained", Raft_Small_Weights.C_T_V2))
|
| 884 |
+
def raft_small(*, weights: Optional[Raft_Small_Weights] = None, progress=True, **kwargs) -> RAFT:
|
| 885 |
+
"""RAFT "small" model from
|
| 886 |
+
`RAFT: Recurrent All Pairs Field Transforms for Optical Flow <https://arxiv.org/abs/2003.12039>`__.
|
| 887 |
+
|
| 888 |
+
Please see the example below for a tutorial on how to use this model.
|
| 889 |
+
|
| 890 |
+
Args:
|
| 891 |
+
weights(:class:`~torchvision.models.optical_flow.Raft_Small_Weights`, optional): The
|
| 892 |
+
pretrained weights to use. See
|
| 893 |
+
:class:`~torchvision.models.optical_flow.Raft_Small_Weights`
|
| 894 |
+
below for more details, and possible values. By default, no
|
| 895 |
+
pre-trained weights are used.
|
| 896 |
+
progress (bool): If True, displays a progress bar of the download to stderr. Default is True.
|
| 897 |
+
**kwargs: parameters passed to the ``torchvision.models.optical_flow.RAFT``
|
| 898 |
+
base class. Please refer to the `source code
|
| 899 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/optical_flow/raft.py>`_
|
| 900 |
+
for more details about this class.
|
| 901 |
+
|
| 902 |
+
.. autoclass:: torchvision.models.optical_flow.Raft_Small_Weights
|
| 903 |
+
:members:
|
| 904 |
+
"""
|
| 905 |
+
weights = Raft_Small_Weights.verify(weights)
|
| 906 |
+
|
| 907 |
+
return _raft(
|
| 908 |
+
weights=weights,
|
| 909 |
+
progress=progress,
|
| 910 |
+
# Feature encoder
|
| 911 |
+
feature_encoder_layers=(32, 32, 64, 96, 128),
|
| 912 |
+
feature_encoder_block=BottleneckBlock,
|
| 913 |
+
feature_encoder_norm_layer=InstanceNorm2d,
|
| 914 |
+
# Context encoder
|
| 915 |
+
context_encoder_layers=(32, 32, 64, 96, 160),
|
| 916 |
+
context_encoder_block=BottleneckBlock,
|
| 917 |
+
context_encoder_norm_layer=None,
|
| 918 |
+
# Correlation block
|
| 919 |
+
corr_block_num_levels=4,
|
| 920 |
+
corr_block_radius=3,
|
| 921 |
+
# Motion encoder
|
| 922 |
+
motion_encoder_corr_layers=(96,),
|
| 923 |
+
motion_encoder_flow_layers=(64, 32),
|
| 924 |
+
motion_encoder_out_channels=82,
|
| 925 |
+
# Recurrent block
|
| 926 |
+
recurrent_block_hidden_state_size=96,
|
| 927 |
+
recurrent_block_kernel_size=(3,),
|
| 928 |
+
recurrent_block_padding=(1,),
|
| 929 |
+
# Flow head
|
| 930 |
+
flow_head_hidden_size=128,
|
| 931 |
+
# Mask predictor
|
| 932 |
+
use_mask_predictor=False,
|
| 933 |
+
**kwargs,
|
| 934 |
+
)
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .googlenet import *
|
| 2 |
+
from .inception import *
|
| 3 |
+
from .mobilenet import *
|
| 4 |
+
from .resnet import *
|
| 5 |
+
from .shufflenetv2 import *
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (291 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/googlenet.cpython-310.pyc
ADDED
|
Binary file (8.05 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/mobilenet.cpython-310.pyc
ADDED
|
Binary file (305 Bytes). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/mobilenetv2.cpython-310.pyc
ADDED
|
Binary file (6.17 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/mobilenetv3.cpython-310.pyc
ADDED
|
Binary file (8.57 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/resnet.cpython-310.pyc
ADDED
|
Binary file (15.1 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (1.73 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/torchvision/models/quantization/googlenet.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from functools import partial
|
| 3 |
+
from typing import Any, Optional, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
|
| 10 |
+
from ...transforms._presets import ImageClassification
|
| 11 |
+
from .._api import register_model, Weights, WeightsEnum
|
| 12 |
+
from .._meta import _IMAGENET_CATEGORIES
|
| 13 |
+
from .._utils import _ovewrite_named_param, handle_legacy_interface
|
| 14 |
+
from ..googlenet import BasicConv2d, GoogLeNet, GoogLeNet_Weights, GoogLeNetOutputs, Inception, InceptionAux
|
| 15 |
+
from .utils import _fuse_modules, _replace_relu, quantize_model
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"QuantizableGoogLeNet",
|
| 20 |
+
"GoogLeNet_QuantizedWeights",
|
| 21 |
+
"googlenet",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class QuantizableBasicConv2d(BasicConv2d):
|
| 26 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 27 |
+
super().__init__(*args, **kwargs)
|
| 28 |
+
self.relu = nn.ReLU()
|
| 29 |
+
|
| 30 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 31 |
+
x = self.conv(x)
|
| 32 |
+
x = self.bn(x)
|
| 33 |
+
x = self.relu(x)
|
| 34 |
+
return x
|
| 35 |
+
|
| 36 |
+
def fuse_model(self, is_qat: Optional[bool] = None) -> None:
|
| 37 |
+
_fuse_modules(self, ["conv", "bn", "relu"], is_qat, inplace=True)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class QuantizableInception(Inception):
|
| 41 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 42 |
+
super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
|
| 43 |
+
self.cat = nn.quantized.FloatFunctional()
|
| 44 |
+
|
| 45 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 46 |
+
outputs = self._forward(x)
|
| 47 |
+
return self.cat.cat(outputs, 1)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class QuantizableInceptionAux(InceptionAux):
|
| 51 |
+
# TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
|
| 52 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 53 |
+
super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
|
| 54 |
+
self.relu = nn.ReLU()
|
| 55 |
+
|
| 56 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 57 |
+
# aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14
|
| 58 |
+
x = F.adaptive_avg_pool2d(x, (4, 4))
|
| 59 |
+
# aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4
|
| 60 |
+
x = self.conv(x)
|
| 61 |
+
# N x 128 x 4 x 4
|
| 62 |
+
x = torch.flatten(x, 1)
|
| 63 |
+
# N x 2048
|
| 64 |
+
x = self.relu(self.fc1(x))
|
| 65 |
+
# N x 1024
|
| 66 |
+
x = self.dropout(x)
|
| 67 |
+
# N x 1024
|
| 68 |
+
x = self.fc2(x)
|
| 69 |
+
# N x 1000 (num_classes)
|
| 70 |
+
|
| 71 |
+
return x
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class QuantizableGoogLeNet(GoogLeNet):
|
| 75 |
+
# TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
|
| 76 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 77 |
+
super().__init__( # type: ignore[misc]
|
| 78 |
+
*args, blocks=[QuantizableBasicConv2d, QuantizableInception, QuantizableInceptionAux], **kwargs
|
| 79 |
+
)
|
| 80 |
+
self.quant = torch.ao.quantization.QuantStub()
|
| 81 |
+
self.dequant = torch.ao.quantization.DeQuantStub()
|
| 82 |
+
|
| 83 |
+
def forward(self, x: Tensor) -> GoogLeNetOutputs:
|
| 84 |
+
x = self._transform_input(x)
|
| 85 |
+
x = self.quant(x)
|
| 86 |
+
x, aux1, aux2 = self._forward(x)
|
| 87 |
+
x = self.dequant(x)
|
| 88 |
+
aux_defined = self.training and self.aux_logits
|
| 89 |
+
if torch.jit.is_scripting():
|
| 90 |
+
if not aux_defined:
|
| 91 |
+
warnings.warn("Scripted QuantizableGoogleNet always returns GoogleNetOutputs Tuple")
|
| 92 |
+
return GoogLeNetOutputs(x, aux2, aux1)
|
| 93 |
+
else:
|
| 94 |
+
return self.eager_outputs(x, aux2, aux1)
|
| 95 |
+
|
| 96 |
+
def fuse_model(self, is_qat: Optional[bool] = None) -> None:
|
| 97 |
+
r"""Fuse conv/bn/relu modules in googlenet model
|
| 98 |
+
|
| 99 |
+
Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization.
|
| 100 |
+
Model is modified in place. Note that this operation does not change numerics
|
| 101 |
+
and the model after modification is in floating point
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
for m in self.modules():
|
| 105 |
+
if type(m) is QuantizableBasicConv2d:
|
| 106 |
+
m.fuse_model(is_qat)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class GoogLeNet_QuantizedWeights(WeightsEnum):
|
| 110 |
+
IMAGENET1K_FBGEMM_V1 = Weights(
|
| 111 |
+
url="https://download.pytorch.org/models/quantized/googlenet_fbgemm-c00238cf.pth",
|
| 112 |
+
transforms=partial(ImageClassification, crop_size=224),
|
| 113 |
+
meta={
|
| 114 |
+
"num_params": 6624904,
|
| 115 |
+
"min_size": (15, 15),
|
| 116 |
+
"categories": _IMAGENET_CATEGORIES,
|
| 117 |
+
"backend": "fbgemm",
|
| 118 |
+
"recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models",
|
| 119 |
+
"unquantized": GoogLeNet_Weights.IMAGENET1K_V1,
|
| 120 |
+
"_metrics": {
|
| 121 |
+
"ImageNet-1K": {
|
| 122 |
+
"acc@1": 69.826,
|
| 123 |
+
"acc@5": 89.404,
|
| 124 |
+
}
|
| 125 |
+
},
|
| 126 |
+
"_ops": 1.498,
|
| 127 |
+
"_file_size": 12.618,
|
| 128 |
+
"_docs": """
|
| 129 |
+
These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized
|
| 130 |
+
weights listed below.
|
| 131 |
+
""",
|
| 132 |
+
},
|
| 133 |
+
)
|
| 134 |
+
DEFAULT = IMAGENET1K_FBGEMM_V1
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@register_model(name="quantized_googlenet")
|
| 138 |
+
@handle_legacy_interface(
|
| 139 |
+
weights=(
|
| 140 |
+
"pretrained",
|
| 141 |
+
lambda kwargs: GoogLeNet_QuantizedWeights.IMAGENET1K_FBGEMM_V1
|
| 142 |
+
if kwargs.get("quantize", False)
|
| 143 |
+
else GoogLeNet_Weights.IMAGENET1K_V1,
|
| 144 |
+
)
|
| 145 |
+
)
|
| 146 |
+
def googlenet(
|
| 147 |
+
*,
|
| 148 |
+
weights: Optional[Union[GoogLeNet_QuantizedWeights, GoogLeNet_Weights]] = None,
|
| 149 |
+
progress: bool = True,
|
| 150 |
+
quantize: bool = False,
|
| 151 |
+
**kwargs: Any,
|
| 152 |
+
) -> QuantizableGoogLeNet:
|
| 153 |
+
"""GoogLeNet (Inception v1) model architecture from `Going Deeper with Convolutions <http://arxiv.org/abs/1409.4842>`__.
|
| 154 |
+
|
| 155 |
+
.. note::
|
| 156 |
+
Note that ``quantize = True`` returns a quantized model with 8 bit
|
| 157 |
+
weights. Quantized models only support inference and run on CPUs.
|
| 158 |
+
GPU inference is not yet supported.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
weights (:class:`~torchvision.models.quantization.GoogLeNet_QuantizedWeights` or :class:`~torchvision.models.GoogLeNet_Weights`, optional): The
|
| 162 |
+
pretrained weights for the model. See
|
| 163 |
+
:class:`~torchvision.models.quantization.GoogLeNet_QuantizedWeights` below for
|
| 164 |
+
more details, and possible values. By default, no pre-trained
|
| 165 |
+
weights are used.
|
| 166 |
+
progress (bool, optional): If True, displays a progress bar of the
|
| 167 |
+
download to stderr. Default is True.
|
| 168 |
+
quantize (bool, optional): If True, return a quantized version of the model. Default is False.
|
| 169 |
+
**kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableGoogLeNet``
|
| 170 |
+
base class. Please refer to the `source code
|
| 171 |
+
<https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/googlenet.py>`_
|
| 172 |
+
for more details about this class.
|
| 173 |
+
|
| 174 |
+
.. autoclass:: torchvision.models.quantization.GoogLeNet_QuantizedWeights
|
| 175 |
+
:members:
|
| 176 |
+
|
| 177 |
+
.. autoclass:: torchvision.models.GoogLeNet_Weights
|
| 178 |
+
:members:
|
| 179 |
+
:noindex:
|
| 180 |
+
"""
|
| 181 |
+
weights = (GoogLeNet_QuantizedWeights if quantize else GoogLeNet_Weights).verify(weights)
|
| 182 |
+
|
| 183 |
+
original_aux_logits = kwargs.get("aux_logits", False)
|
| 184 |
+
if weights is not None:
|
| 185 |
+
if "transform_input" not in kwargs:
|
| 186 |
+
_ovewrite_named_param(kwargs, "transform_input", True)
|
| 187 |
+
_ovewrite_named_param(kwargs, "aux_logits", True)
|
| 188 |
+
_ovewrite_named_param(kwargs, "init_weights", False)
|
| 189 |
+
_ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
|
| 190 |
+
if "backend" in weights.meta:
|
| 191 |
+
_ovewrite_named_param(kwargs, "backend", weights.meta["backend"])
|
| 192 |
+
backend = kwargs.pop("backend", "fbgemm")
|
| 193 |
+
|
| 194 |
+
model = QuantizableGoogLeNet(**kwargs)
|
| 195 |
+
_replace_relu(model)
|
| 196 |
+
if quantize:
|
| 197 |
+
quantize_model(model, backend)
|
| 198 |
+
|
| 199 |
+
if weights is not None:
|
| 200 |
+
model.load_state_dict(weights.get_state_dict(progress=progress))
|
| 201 |
+
if not original_aux_logits:
|
| 202 |
+
model.aux_logits = False
|
| 203 |
+
model.aux1 = None # type: ignore[assignment]
|
| 204 |
+
model.aux2 = None # type: ignore[assignment]
|
| 205 |
+
else:
|
| 206 |
+
warnings.warn(
|
| 207 |
+
"auxiliary heads in the pretrained googlenet model are NOT pretrained, so make sure to train them"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
return model
|